texts: Storing arbitrary form data in SQL as an XML blob

texts:
I am currently storing form data in an XML format:

<cfsavecontent variable="myFormData">
<cfoutput>

  <cfloop list="#form.fieldnames#" index="item">
    <cfloop list="#form[item]#" index="eachItem">

#xmlformat(item)# <var>#xmlformat(eachItem)#</var>
    </cfloop>
  </cfloop>

<cfoutput>
</cfsavecontent>

Then do a single insert:

<cfquery>
   INSERT INTO table (formData)
   VALUES (<cfqueryparam value="#myFormData#" cfsqltype="cf_sql_varchar">)
</cfquery>

When I pull the data out, I can:

<cfquery name="qryData">
   SELECT formData
   FROM table
   WHERE ID = <cfqueryparam value="#ID#" cfsqltype="cf_sql_integer">
</cfquery>

<cfoutput query="qryData">#formData#</cfoutput>

OR

<cfquery name="qryData">
   SELECT li.value('(b/text())[1]', 'varchar(50)') AS Item,
      li.value('(var/text())[1]', 'varchar(50)')   AS Value
   FROM table
   CROSS APPLY XmlData.nodes('/ul/li') AS ul(li)
   WHERE ID = <cfqueryparam value="#ID#" cfsqltype="cf_sql_integer">
</cfquery>

<cfoutput query="qryData">#Item# #Value#</cfoutput>

Some developers have concerns about storing the data in this format. Is this the best way to store arbitrary form data?


texts: Critique of FilterInputStream and FilterOutputStream classes

texts:
I'm working my way through The Java Programming Language, Fourth Edition - The Java Series.  This is Exercise Exercise 20.3:

  Create a pair of Filter stream classes that encrypt bytes using any
  algorithm you choose—such as XORing the bytes with some value—with your
  DecryptInputStream able to decrypt the bytes that your EncryptOutputStream
  class creates.

Is the following an adequate solution? I understand that the key should be randomly generated and at least as long as the message. They key used is just for illustration.

EncryptOutputStream.java

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class EncryptOutputStream extends FilterOutputStream {
    private final static int XOR_KEY = 1;

    public EncryptOutputStream(OutputStream out) {
        super(out);
    }

    @Override
    public void write(int b) throws IOException {
        super.write(b ^ XOR_KEY);
    }
}

DecryptInputStream.java

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class DecryptInputStream extends FilterInputStream {
    private final static int XOR_KEY = 1;

    protected DecryptInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read() throws IOException {
        int b = super.read();
        return (b != -1 ? b ^ XOR_KEY : b);
    }
}

EncryptionTest.java

import org.junit.Test;
import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class EncryptionTest {
    @Test
    public void testEncryptOutputStream() throws Exception {
        String testStr = "The quick brown fox jumps over the lazy dog.";
        InputStream in = new ByteArrayInputStream(testStr.getBytes("UTF-8"));
        OutputStream out = new ByteArrayOutputStream();
        FilterOutputStream encryptOut = new EncryptOutputStream(out);

        int b;
        while ((b = in.read()) != -1) {
            encryptOut.write(b);
        }

        assertEquals("Uid!pthbj!csnvo!gny!ktlqr!nwds!uid!m`{x!enf/", out.toString());

        in.close();
        encryptOut.close();
    }

    @Test
    public void testDecryptInputStream() throws Exception {
        String testStr = "Uid!pthbj!csnvo!gny!ktlqr!nwds!uid!m`{x!enf/";
        InputStream in = new ByteArrayInputStream(testStr.getBytes("UTF-8"));
        FilterInputStream decryptIn = new DecryptInputStream(in);
        OutputStream out = new ByteArrayOutputStream();

        int b;
        while ((b = decryptIn.read()) != -1) {
            out.write(b);
        }

        assertEquals("The quick brown fox jumps over the lazy dog.", out.toString());

        decryptIn.close();
        out.close();
    }

    @Test
    public void testEncryptDecrypt() throws Exception {
        String testStr = "The quick brown fox jumps over the lazy dog.";
        OutputStream out = new ByteArrayOutputStream();
        InputStream in = new ByteArrayInputStream(testStr.getBytes("UTF-8"));
        FilterOutputStream encryptOut = new EncryptOutputStream(out);

        int b;
        while ((b = in.read()) != -1) {
            encryptOut.write(b);
        }

        assertEquals("Uid!pthbj!csnvo!gny!ktlqr!nwds!uid!m`{x!enf/", out.toString());

        String resultStr = out.toString();
        InputStream inResult = new ByteArrayInputStream(resultStr.getBytes("UTF-8"));
        FilterInputStream decryptIn = new DecryptInputStream(inResult);
        OutputStream outResult = new ByteArrayOutputStream();

        b = 0;
        while ((b = decryptIn.read()) != -1) {
            outResult.write(b);
        }

        assertEquals(testStr, outResult.toString());

        encryptOut.close();
        decryptIn.close();
        outResult.close();
    }
}


texts: Storing global styles and utilizing them throughout view controllers

texts:
Assuming an app has many display styles, fonts, colors, etc., and that we never want to hardcode values, I've created an AppVariables object that houses properties for all of the necessary styles in my app:

class AppVariables: NSObject {

    /**
     * Fonts
     */
    let UIFontPrimary10 = UIFont(name: "Heiti TC", size: 10)
    let UIFontPrimary12 = UIFont(name: "Heiti TC", size: 12)
    let UIFontPrimary14 = UIFont(name: "Heiti TC", size: 14)

    var attribsFont10: NSDictionary!
    var attribsFont12: NSDictionary!
    var attribsFont14: NSDictionary!

    var paragraphStyleFont10 = NSMutableParagraphStyle()
    var paragraphStyleFont12 = NSMutableParagraphStyle()
    var paragraphStyleFont14 = NSMutableParagraphStyle()

    /**
     * Colors
     */
    let UIColorWhiteOff = UIColor(red: 250.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: 1)
    let UIColorPurple = UIColor(red: 134.0/255.0, green: 129.0/255.0, blue: 204.0/255.0, alpha: 1)
    let UIColorPurpleLight = UIColor(red: 178.0/255.0, green: 176.0/255.0, blue: 217.0/255.0, alpha: 1)
    let UIColorBlueDark = UIColor(red: 40.0/255.0, green: 35.0/255.0, blue: 61.0/255.0, alpha: 1)
    let UIColorBlueDarkAlpha6 = UIColor(red: 40.0/255.0, green: 35.0/255.0, blue: 61.0/255.0, alpha: 0.6)
    let UIColorBlueDarkAlpha95 = UIColor(red: 40.0/255.0, green: 35.0/255.0, blue: 61.0/255.0, alpha: 0.95)

    /**
     * Dimensions and margins
     */
    var screenWidth: CGFloat!
    var screenHeight: CGFloat!
    var viewPadding: CGFloat!
    var viewPaddingSmall: CGFloat!
    var viewWidth: CGFloat!

    init() {
        super.init()

        self.paragraphStyleFont10.lineSpacing = 4
        self.paragraphStyleFont12.lineSpacing = 5
        self.paragraphStyleFont14.lineSpacing = 6

        self.attribsFont10 = [NSFontAttributeName: self.UIFontPrimary10, NSParagraphStyleAttributeName: self.paragraphStyleFont10]
        self.attribsFont12 = [NSFontAttributeName: self.UIFontPrimary12, NSParagraphStyleAttributeName: self.paragraphStyleFont12]
        self.attribsFont14 = [NSFontAttributeName: self.UIFontPrimary14, NSParagraphStyleAttributeName: self.paragraphStyleFont14]

        self.screenWidth = UIScreen.mainScreen().bounds.width
        self.screenHeight = UIScreen.mainScreen().bounds.height
        self.viewPadding = (screenWidth * 0.1) / 2
        self.viewPaddingSmall = 10.0
        self.viewWidth = screenWidth - (viewPadding * 2)
    }
}

Assuming I've instantiated a copy of AppVariables into a property of AppDelegate, I can use them like so:

class Foo {

    func bar() {

        var someLabel = UILabel()
        someLabel.textColor = self.appDelegate.appVariables.UIColorPurpleLight
    }

}

Is there a better way of doing this? It seems like the simplest approach, since these are more than mere constants, but I'm open to thoughts and opinions.


texts:
I've written my own prime number sieve in JavaScript. It loops through numbers 1-100 and puts them in one of two arrays, depending on if it is composite or prime.

I was wondering if there are any inefficient or unnecessary parts of my code that might be slowing down the program. Is there anything I can do so it will work for larger numbers too?

//  Creating variables to use later
var cORp;
var primeNums = [];
var compNums = [];

// Create numberSieve function
function numberSieve(x) {

    // 0 and 1 are not prime or composite
    if (x < 2 && x >= 0) {
        cORp = 'neither';
    }

    // All negative numbers are composite
    else if (x < 0) {
        cORp = 'composite';
    }

    // Sieve for positive numbers above 1
    else {

        // Some more variables for later use
        possibleFactors = [];
        zFactors = [];
        matchingFactors = [];

        // Takes all numbers that are half of x and below because they are possible factors
        for (i=2; i < x/2+1; i++) {
            possibleFactors.push(i);
        }

        // Takes all possible factors and divides x by them
        for (i=0; i < possibleFactors.length; i++) {
            z = x/possibleFactors[i];
            zFactors.push(z);
        }

        // Checks if the x divided by the possible factors is equal to any of the other possible factors
        for (i in possibleFactors) {
            if (zFactors.indexOf(possibleFactors[i]) !== -1) {
                matchingFactors.push(possibleFactors[i]);
            }
        }

        // Checks if there are any matching factors
        if (matchingFactors.length !== 0) {
            cORp = 'composite';
        }
        else {
            cORp = 'prime';
        }
    }

    // Prime numbers go to one array, Composite numbers go to another
    if (cORp === 'prime') {
        primeNums.push(x);
    }
    else if (cORp === 'composite') {
        compNums.push(x);
    }
}

// For each number 0-100 runs the sieve
a=0;
while (a <= 100) {
    numberSieve(a);
    a++;
}

// Prints out the prime number and composite number arrays
console.log("Prime Numbers: " + primeNums);
console.log("Composite Numbers: " + compNums);


texts:
I am trying to build a class similar to std::shared_ptr just to learn and improve my way of thinking. I am hoping that you can tell me if this implementation is correct? If so, how can I improve it?
Here is the code:
#include <iostream>
#include <map>

template<typename dataType>
class shared_ptr
{
public:
    shared_ptr()
    {
        id++;
        internalId = id;
        countMap[id] = 1;
        ptr = new dataType();
    }
    shared_ptr(shared_ptr& a)
    {
        this->ptr = a.ptr;
        this->internalId = a.internalId;
        countMap[internalId]++;
    }

    void operator=(shared_ptr& a)
    {
        this->ptr = a.ptr;
        this->internalId = a.internalId;
        countMap[internalId]++;
    }

    ~shared_ptr()
    {
        countMap[internalId]--;
        if(countMap[internalId]==0)
        {
            delete ptr;
            countMap.erase(internalId);
        }
    }

private:
    static int id;
    int internalId = 0;
    static std::map<int,int> countMap;
    dataType* ptr;
};
template<typename  dataType>
 int shared_ptr<dataType>::id = 1;
 template<typename  dataType>
 std::map<int,int> shared_ptr<dataType>::countMap;

int main()
{
    {
    shared_ptr<int> sp1;
    {
        shared_ptr<int> sp3;
        shared_ptr<int> sp4(sp3);
        shared_ptr<int> sp5;
        sp5 = sp4;
    }
    shared_ptr<int> sp2(sp1);
    }
    return 0;
}


texts:
I have two working configurations that, on the surface, seem to do the same thing. They both accomplish the functionality that I need:

location ~ ^/(css|images|js)/ {
    location ~ '^/(css|js)/[0-9]{8}-(.*)$' {
        alias /$1/$2;
    }
    root /server/path/to/web/root;
}

AND

location ~ ^/(css|images|js)/ {
    rewrite '^/(css|js)/[0-9]{8}-(.*)$' /$1/$2 break;
    root /server/path/to/web/root;
}

They both take a URL like /css/87654321-styles.css and deliver the file /css/styles.css. I lean toward the second solution because it's more succinct, but I don't know if one is better than the other for performance reasons, unintended side-effects, etc.

Here's my original SO post, for reference/context.

After being directed to the documentation for the Nginx rewrite module, I found these interesting lines:

  The ngx_http_rewrite_module module directives are processed in the following order:

  the directives of this module specified on the server level are executed sequentially;
  repeatedly:

  a location is searched based on a request URI;
  the directives of this module specified inside the found location are executed sequentially;
  the loop is repeated if a request URI was rewritten, but not more than 10 times.

So, if I used the rewrite directive without the break flag, there could be at least one additional loop of the server level directive.


texts: Routine to convert decimal digits to Densely Packed Decimal

texts:
I've written an amd64 assembly routine (in gas syntax using the System V calling convention) to convert three decimal digits to Densely packed decimal because I wasn't satisfied by the performance of the assembly generated by gcc and clang for all implementations of the conversion I could think of. Here is the code:

    .section .text
    .type decimal2dpd,@function
    .globl decimal2dpd

    # convert three digits abc to DPD
    # SysV calling convention: a in edi, b in esi, c in edx
    # assumes 0 <= a, b, c < 10
    .align 8
decimal2dpd:
    mov %esi,%eax
    shl $4,%eax
    or %edx,%eax
    and $0021,%eax
    shl $7,%edi
    or %edi,%eax
    and $016,%edx
    btr $10,%eax

    # at this point, eax = (a & 7) << 4 | (b & 1) << 4 | (c & 1) and CF is set if a > 7
    # and edi is free for use
    jc .Lagt7

    # here a < 8
    shl $4,%esi
    btr $7,%esi
    jc .Lbgt7

    # here a < 8 and b < 8
    or %esi,%eax
    or %edx,%eax
    ret

    .align 8
.Lbgt7: # here a < 8 and b > 7
    or $0012,%eax
    shl $4,%edx
    mov $0104,%edi
    btr $7,%edx
    cmovc %edi,%edx
    or %edx,%eax
    ret

    .align 8
.Lagt7: # here a > 7
    shl $7,%edx # eax = (a & 1 | c & 6) << 7 | (b & 1) << 5 | (c & 1)
    or %edx,%eax    # now eax[10] is set if c > 7
    btr $10,%eax
    jc .Lcgt7

    # here a > 7 and c < 8
    or $0014,%eax
    shl $4,%esi
    mov $0002,%edi
    btr $7,%esi
    cmovc %edi,%esi
    or %esi,%eax
    ret

    .align 8
.Lcgt7: # here a > 7 and c > 7
    and $016,%esi
    or $0056,%eax
    shl $7,%esi
    mov $0100,%edi
    btr $10,%esi
    cmovc %edi,%esi
    or %esi,%eax
    ret
    .size decimal2dpd,.-decimal2dpd

This routine is roughly 10% faster than the C code implementing roughly the same algorithm shown below. I would like to know if there is any obvious or less obvious way to improve this routine for better performance.

extern unsigned
decimal2dpd(unsigned a, unsigned b, unsigned c)
{
    unsigned result = c & 1 | (a & 7) << 7;

    if (a < 8) {
        if (b < 8)
            return result | b << 4 | c;
        else
            return result | (c > 7 ? 0104 : (c & 6) << 4) | (b & 1) << 4 | 0012;
    } else {
        result |= (b & 1) << 4;

        if (c < 8)
            return result | (c & 6) << 7 | (b > 7 ? 0002 : b << 4) | 0014;
        else
            return result | (b > 7 ? 0100 : (b & 6) << 7) | 0056;
    }
}

I especially believe that the fact that all arguments are in the range 0–9 can be exploited further, I didn't found a way to do so though (except for a).


texts: Parsing URL query and appending it at end of the other URL

texts:
I am trying to grab the URL query of the URL which is in the browser's address bar, then append it at the end of the other URL and echo it to the browser.

So, if I visit my script at:

  http://script.com/script.php?a=x&b=z

and the other URL is:

  http://google.com/?c=v&d=u

then the browser will display:

  http://google.com?a=x&b=z&c=v&d=u

This code is quite slow. How can I improve this?

 function parse_me($from, &$to) {
    // $to = array();
    $from = urldecode($from);
    $from = urldecode($from);

    foreach (explode('&', $from) as $part) {
        $part = explode('=', $part);
        if ($key = array_shift($part)) {
            $to[$key] = implode('', $part);
        }
    }
    // print_r($to);
}

function add_qsrt_to_url($url) {
    $other_query_string = arrayGet($_SERVER, 'QUERY_STRING', '');

    $url_parsed = parse_url($url);
    $new_qs_parsed = array();

    if (isset($url_parsed['query'])) {
        // parse_str($url_parsed['query'], $new_qs_parsed);
        parse_me($url_parsed['query'], $new_qs_parsed);
    }
    $other_qs_parsed = array();

    // parse_str($other_query_string, $other_qs_parsed);
    parse_me($other_query_string, $other_qs_parsed);
    // print_r($other_qs_parsed);

    $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed);
    // var_dump($final_query_string_array);
    $final_query_string = http_build_query($final_query_string_array);
    $new_url = $url_parsed['scheme'] . '://' . $url_parsed['host'];

    if (isset($url_parsed['path'])) {
        $new_url = $new_url . $url_parsed['path'];
    }

    if ($final_query_string) {
        $new_url = $new_url . '?' . $final_query_string;
    }

    return $new_url;
}

function arrayGet($array, $key, $default = NULL) {
    return isset($array[$key]) ? $array[$key] : $default;
}


texts: Shopping cart program in Java with a text menu

texts:
I wrote this program to implement a shopping cart.  It supports adding/removing items to the cart, viewing the current order, and completing the checkout process.

import java.util.Scanner;

public class Keychains1 {

    public static Scanner keyboard = new Scanner(System.in);
    public static boolean stay = true;

    public static void add_keychains() {
        System.out.println("ADD KEYCHAINS");
    }

    public static void remove_keychains() {
        System.out.println("REMOVE KEYCHAINS");
    }

    public static void view_order() {
        System.out.println("VIEW ORDER");
    }

    public static void checkout() {
        System.out.println("CHECKOUT");
        stay = false;
    }

    public static void main(String[] args) {

        int choice;

        while (stay) {

            System.out.println("Ye Olde Keychain Shoppe");
            System.out.println();

            System.out.println("1. Add Keychains to Order");
            System.out.println("2. Remove Keychains from Order");
            System.out.println("3. View Current Order");
            System.out.println("4. Checkout");
            System.out.println();
            System.out.print("Please enter your choice: ");

            choice = keyboard.nextInt();

            System.out.println();

            if (choice == 1) {
                add_keychains();
            }
            else if (choice == 2) {
                remove_keychains();
            }
            else if (choice == 3) {
                view_order();
            }
            else if (choice == 4) {
                checkout();
            }
            else {
                System.out.println("Error. Please choose again.");
            }
            System.out.println();
        }

    }
}


texts: Sorting an array using a Binary Search Tree with C++

texts:
Given an array of integer (all different from each other), this program creates a BST with the array elements in order to sort them and put them back into the array, using the BST properties.

#include<iostream>
using namespace std;

struct Node
{
    int label;
    Node* left;
    Node* right;

    ~Node() {
      delete left;
      delete right;
      }
};

void insertSearchNode(Node* &tree, int x)       //insert integer x into the BST
{
    if(!tree){
        tree = new Node;
        tree->label = x;
        tree->right = NULL;
        tree->left = NULL;
        return;
    }
    if(x < tree->label) insertSearchNode(tree->left, x);
    if(x > tree->label) insertSearchNode(tree->right, x);
    return;
}

void insertArrayTree(int arr[], int n, Node* &tree)     //insert the array integer into the nodes label of BST
{
    for(int i=0; i<n; i++){
        insertSearchNode(tree, arr[i]);
    }
    return;
}

int insertIntoArray(int arr[], Node* &tree, int i)      //insert into the array the node label touched during an inorder tree traversal
{
    if(!tree) return i;
    i = insertIntoArray(arr, tree->left, i);
    arr[i] = tree->label;
    i++;
    i = insertIntoArray(arr, tree->right, i);
    return i;

}

int main()
{
    Node* maintree;
    maintree = NULL;
    int num = 7;
    int arr[num] = {120, 30, 115, 40, 50, 100, 70};
    insertArrayTree(arr, num, maintree);      //insert elements into BST
    insertIntoArray(arr, maintree, 0);        //modify array sorting his elements using the BST

    for(int y=0; y<num; y++) cout<< arr[y] << ' ';

    return 0;
}

Output:

30 40 50 70 100 115 120

Any advice is welcome.


texts:
The code below compares recv.rcpt_dtim (which is a datetime type) against the current date/time. It calculates an elapsed time resulting in hours and minutes formatted like: "04:22". It took me a while to get it functional, which it is, but it just seems sloppy. Does anyone have any tips to clean it up?

TRIM((((CURRENT YEAR TO SECOND - recv.rcpt_dtim)::INTERVAL SECOND(9) to
SECOND)/3600)::VARCHAR(12) || ':' || CASE WHEN (MOD(MOD(((CURRENT YEAR TO
MINUTE - recv.rcpt_dtim)::INTERVAL MINUTE(9) to
MINUTE)::VARCHAR(12)::INT,60),60))<10 THEN "0" ELSE "" END ||
(MOD(MOD(((CURRENT YEAR TO MINUTE - recv.rcpt_dtim)::INTERVAL MINUTE(9)
to MINUTE)::VARCHAR(12)::INT,60),60))::VARCHAR(12))


texts:
I'm a JavaScript newbie who was first introduced to JavaScript by jQuery. I'm trying to switch over some of the small things I've written in jQuery to JavaScript as a way of learning. I was wondering how I could make my code cleaner and if there were any bad habits which I am guilty of doing.

function getTweets(user) {

    //Adds a little animation to the body when function is executed
    $('.container').html('

');
    var container = document.getElementsByClassName('container')[0];
    container.innerHTML = "

";

    $.getJSON("https://twitter.com/statuses/user_timeline.json?screen_name=" + user + "&callback=?&count=50", function(data) {

        var date = {
            Sun : 'Sunday, ',
            Sat : 'Saturday, ',
            Mon : 'Monday, ',
            Tue : 'Tuesday, ',
            Wed : 'Wednesday, ',
            Fri : 'Friday, ',
            Thu : 'Thursday, ',
        };
        // Creates a box and puts JSON data into it.
        for ( var i = 0 ; i < data.length; i++) {
            // Makes the dates readable and links work.
            data[i].text = data[i].text.replace(/(http[s]*:\/\/[\w/\.]+)/, '$1')
            day = date[ data[i].created_at.match(/\w+/)[0] ];
            data[i].created_at = data[i].created_at.replace(/(\+\d+)/g, '').replace(/\w+/, day);

            var art = document.createElement('article');

            art.innerHTML = "
" + data[i].user.name + "
" + data[i].created_at + "
" + data[i].text + "
";
            container.appendChild(art);

        };
        //Everything after this is to dynamically create a Pinterest type layout
        var width = Math.floor( ( $(window).width() - 200 )/225),
            col = [],
            small = 0,
            articleArray = document.getElementsByTagName('article');

        while ( col.length < width ) {
            col.push(0)
        };

        for (var o = 0; o < articleArray.length; o++) {

            articleArray[o].style.top = col[small] + "px";
            articleArray[o].style.left = small*225 + "px";

            col[small] += articleArray[o].clientHeight + 5;

            for ( var j = 0; j < width; j++ ) {

                if (col[j] < col[small]) {
                    small = j
                }

            };
        };

        container.style.height = col[small] + 'px';
        container.style.width = col.length * 225 - 5 + 'px';

        $('.container .loading').fadeOut();
        $('article').fadeIn();

    });

};


texts:
I have a library which makes HTTP calls to my service. I was trying to calculate running average of how much time my service is taking on an average.

Here is the core logic of how I am calculating "running average":

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.LinkedList;
import java.util.Queue;

public class MovingAverage {

    private final Queue<BigDecimal> window = new LinkedList<BigDecimal>();
    private final int period;
    private BigDecimal sum = BigDecimal.ZERO;

    public MovingAverage(int period) {
        this.period = period;
    }

    public void add(BigDecimal num) {
        sum = sum.add(num);
        window.add(num);
        if (window.size() > period) {
            sum = sum.subtract(window.remove());
        }
    }

    public BigDecimal getAverage() {
        if (window.isEmpty()) return BigDecimal.ZERO;
        BigDecimal divisor = BigDecimal.valueOf(window.size());
        return sum.divide(divisor, 2, RoundingMode.HALF_UP);
    }
}

Is there any better/optimized way to do the same thing? I want to make sure this running average calculation is fast since this library runs under very heavy load so this should not increase the overall latency.


texts: Find select values on one worksheet and copy to a second

texts:
In the Calculator worksheet of my spreadsheet, for any appliance type present in a building being studied, users enter a quantity. There are 18 different appliance types, and users can enter different quantities of any or all appliance types.

On the Calculator sheet they can see a breakdown of energy use per individual appliance, per appliance type, and for all appliances with a quantity entered:

The macro below (run from a second sheet) copies specific values from Calculator so that they can be pasted into another spreadsheet which is used for reporting. It selects only appliance types for which the user entered a quantity.

Sub findAppliances()

    ' Get Range
    Dim rg As Range
    Set rg = ThisWorkbook.Worksheets("Calculator").Range("F5:F22")

    ' Create dynamic array
    Dim ApplianceQty As Variant

    ' Read values into array
    ApplianceQty = rg.Value

    ' Manipulate and copy the appropriate values
    Dim i As Long, j As Long
    j = 4
    Dim target As String
    Dim source As String
    For i = LBound(ApplianceQty) To UBound(ApplianceQty)
        target = j
        If ApplianceQty(i, 1) <> "" Then
            source = i + 4
            Range("B" & target) = Worksheets("Calculator").Range("F" & source) & " units"
            Range("F" & target) = "=F" & target - 1 & "-" & Worksheets("Calculator").Range("J" & source)
            Range("G" & target) = "=G" & target - 1 & "-" & Worksheets("Calculator").Range("K" & source)
            Range("H" & target) = "=H" & target - 1 & "-" & Worksheets("Calculator").Range("L" & source)
            Range("K" & target) = Worksheets("Calculator").Range("E" & source)
            Range("L" & target) = Worksheets("Calculator").Range("C" & source)
            j = j + 1
        End If
    Next i

    ' Select and copy the text for export
    Range("B4:M" & target).WrapText = False
    Range("B4:M" & target).Select
    Range("B4:M" & target).Copy

End Sub

I suspect that the reason this takes so long to run is the group of six Range() = Worksheets("Calculator").Range() lines within my For loop. I further suspect that if I read all the data I need into an array, then printed it back out of the array (rather than reading cells and copying to new cells), the whole thing would run faster.

Is that true? How much improvement can I expect?


texts:
I am a Java dev and trying to prepare for interviews in C++. Can someone please review the below solution for me?

  Assume that you are given the head and tail pointers of a doubly linked list where each node can also have a single child pointer to another similar doubly linked list. There are no cycles in this structure outside of the traditional double links. Write a procedure in C++ that flattens this structure into a single list.

**I am ignoring that it is a doubly linked list for now to make the posted code more simple, since the "doubly" part doesn't seem to be of any help to me for this question.

void LL::flatten(Node *head,Node *tail)
{
    if(!head||!tail) return;

    while(!head->down &&!(head==tail))
    {
        head = head->next;
    }

    // Flattening is complete
    if(head==tail && !head->down) return;

    tail->next = head->down;
    head->down = null;

    //getTail returns the last node of the linkedlist
    flatten(head->next, getTail(tail->next));

}

class Node
{
public:
    Node()
    {
        next = prev = down = null;
        data = -1;
    }
private:
    Node * next;
    Node * down;
    Node * prev;
    int data;
};

I have some questions:

Is the "doubly" part required. What am I missing?
I have read it is better non-recursively. How is that? Since we have only pointers on the stack and the actual objects/list structure are on the heap, this should not take huge space on the stack, apart from usual recursion overheads.
Does someone have a non-recursive way of doing it in C++ or Java. The code on this forum is in C# and I am having trouble understanding it with enumerations and all the iterations
The getTail(tail->next) function is \$O(n)\$. Is there a way of not using this function ?. Even If I attach the 'down' linked list to the next node instead of last node, I will need the last node of the 'down' LL so that I can attach it to the next node of parent.

Though I know there might be many solution already posted elsewhere, I am looking for review for my code as well, this will help me understand my gaps while coding in c++ (at least up to interview standards).


texts:
Let's say I have a collection of expensive-to-generate objects stored in an IEnumerable:

IEnumerable<Expensive> expensiveObjects = CreateExpensiveIEnumerable();

Now I will iterate over everything in expensiveObjects and afterwards, I want to know if it was empty.

Here is how I am doing that currently.

var count = 0;
foreach(var e in expensiveObjects)
{
    count++;
    //other processing
}
if (count == 0)
{
    //do something
}

This works fine, but I'm asking here as a fishing expedition to figure out if there are any clever ways to implement this functionality without either:

iterating over at least part of the collection twice by using the Any() method
Performing a ToList() up-front on my collection

Any other suggestions or should I just stick with a simple counting variable?


texts:
This is my first ever project I've coded in Python so I'm sorry if it's a little novice. I'm just looking for beginner feedback on what I could improve next time.

There is one issue with this calculator: let's say I add 1 and 2, I expect to get 3, instead it returns 3.0, but I'm guessing that's because I'm casting to a float.

The reason I'm casting to a float is to accept decimals in the equation. It would be nicer if it displayed the whole number without the .0

while True:
    calculation = input("Calculation: ")

    if (calculation.__contains__("+")):
        print(float(calculation.split('+')[0]) + float(calculation.split('+')[1]))

    elif (calculation.__contains__("-")):
        print(float(calculation.split('-')[0]) - float(calculation.split('-')[1]))

    elif (calculation.__contains__("*")):
        print(float(calculation.split('*')[0]) * float(calculation.split('*')[1]))

    elif (calculation.__contains__("/")):
        print(float(calculation.split('/')[0]) / float(calculation.split('/')[1]))


texts:
I have written code that reads in a CSV file and creates a tuple from all the items in a group. The group ID is in column 1 of the table and the item name is in column 2. The actual datafile is ~500M rows.

Is there any way to make this code more efficient?

Input file:

"CustID"|"Event"
1|Alpha
1|Beta
1|AlphaWord
1|Delta
2|Beta
2|Charlie
2|CharlieSay

Code:

def sequencer(myfile):
    import csv
    counter = 1
    seq = []
    sequence = []
    with open(myfile, 'rb') as csvfile:
        fileread = csv.reader(csvfile, delimiter='|', quotechar='"')
        next(fileread) ## skip header
        for row in fileread:
            #if counter == 5:
            #    break
            if 'word' in row[1] or 'say' in row[1]: ##if event has either word or say anywhere in the text then ignore (eg: even ignore adword or afdjklSAYwer)
                continue
            if int(row[0]) == counter:
                seq.extend([row[1]])
            else:
                sequence.append(seq)
                seq = [row[1]]
                counter = counter+1
        sequence.append(seq)
    return sequence

Output:

An array which is a list of lists, where each list is the sequence of events in the order of the text file for each customer ID.


texts:
I have code for calculating the date for orthodox Easter and it makes me cry when I look at the if-else part. Please give your suggestions on how to make it shine (if possible).

I guess I can format day/month to DateTime format but I'm afraid it'll bring just more mess.

It works just fine though this.

Source

puts "- Hello, I'm EasterEvaluator. I can tell you when will be(or was) Easter."
puts "- Please enter the year which you'r interested in:"
year = gets.chomp.to_i
a = year % 19
b = year % 4
c = year % 7
d = (19*a+15) % 30
e = (2*b + 4*c + 6*d + 6) % 7
f = d + e
if f<=9
    easter = 22+f
    easter = easter + 13 if year > 1918
    if easter > 31
        easter = easter - 31
        month = "April"
    else
        month = "March"
    end
else
    easter = f-9
    easter = easter + 13 if year > 1918
    if easter > 30
        easter = easter-30
        month = "May"
    else
        month = "April"
    end
end

puts "- In #{year}, Easter is going to be on #{easter} of #{month}."


texts: Specialized version of the cross correlation function

texts:
I am writing a specialized version of the cross correlation function as used in neuroscience. The function below is supposed to take a time series data and ask how many of its values fall in specified bins. My function xcorr works but is horrifically slow even. A test data set with 1000 points (and so 0.5*(1000*999) intervals) distributed over 400 bins takes almost ten minutes.

Bottleneck

The bottleneck is in the line counts = array([sum .... I assume it is there because each iteration of the foreach loop searches through the entire vector diffs, which is of length len(first)**2.

def xcorr(first,second,dt=0.001,window=0.2,savename=None):
    length = min(len(first),len(second))
    diffs = array([first[i]-second[j] for i in xrange(length) for j in xrange(length)])
    bins = arange(-(int(window/dt)),int(window/dt))
    counts = array[sum((diffs>((i-.5)*dt)) & (diffs<((i+.5)*dt))) for i in bins]
    counts -= len(first)**2*dt/float(max(first[-1],second[-1])) #Normalization
    if savename:
        cPickle.dump((bins*dt,counts),open(savename,'wb'))
    return (bins,counts)


texts: Trimming whitespace from the beginning and ending of a file

texts:
In the code below, I want to remove the "white space character" from 2 places only, from the end of 1st line and from the end of last line. How can I optimize it ?

Platform : Linux , gcc compiler

int remove_special_chars(char *file_path, char *dest_file, int flag)
{
    PRINT_FUN_NAME

    struct stat st;
    unsigned char *fileData=NULL;
    FILE *fp = NULL, *dest_file_fp = NULL, *intermidiate_fp = NULL;
    char tmp_str[256] = {0}, str_buffer[100] = {0};
    int file_size = 0, count = 0, read_len = 0;

    /* I have taken 3 files here "file_path" is
       the source file from which i am reading
       data and intermidiate_path is the 2nd file
       in which  iam storing data after removing
       the space from 1st line. Then iam reding
       the intermidiate file and removing the space
       from last line and finally storing it into
       3rd file i.e is "dest_file". */

    if ((fp = fopen(file_path, "r")) == NULL) {
        DPRINTF("File Opening Failed!\n");
        return -1;
    }
    if((intermidiate_fp = fopen(INTERMEDIATE_FILE_PATH, "wb+")) == NULL) {
        DPRINTF("File Opening Failed!\n");
        return -1;
    }
    if((dest_file_fp = fopen(dest_file, "wb")) == NULL) {
        DPRINTF("File Opening Failed!\n");
        return -1;
    }

    while(fgets(tmp_str, sizeof(tmp_str), fp) != NULL) {
        DPRINTF("tmp_str : %s\n", tmp_str);

        fputs(tmp_str, intermidiate_fp);

        if(count == 0) {
            rewind(intermidiate_fp);
            strncpy(str_buffer, tmp_strstrlen(tmp_str));
            str_buffer[strlen(str_buffer) - 1] = '\0';
            DPRINTF("str_buffer : %s\n", str_buffer);
            fputs(str_buffer, intermidiate_fp);
            count ++;
        }
    }

    rewind(intermidiate_fp);

    stat(INTERMEDIATE_FILE_PATH, &st);
    if (st.st_size == 0) {
        return (-2);
    }
    file_size = st.st_size;
    DPRINTF("File size : %d\n", file_size);
    fileData = (unsigned char *)malloc(sizeof(char)*file_size);
    if(fileData == NULL) {
        DPRINTF("Unable to allocate size for fileData!\n");
        return -1;
    }
    if ((read_len=fread(fileData, 1, file_size, intermidiate_fp)) == 0) {
        DPRINTF("Reading Failed!\n");
        free(fileData); fileData=NULL;
        return (-3);
    }
    fileData[(file_size-1)] = '\0';
    DPRINTF("File Data : %s\n", fileData);

    fputs((char*)fileData, dest_file_fp);

    fclose(dest_file_fp); fclose(fp);
    fclose(intermidiate_fp);

    return 0;
}


texts: Advent of Code 2017 Day 3 (part 1) in Functional Programming (FP)

texts:
I wanted to practice functional programming (FP) without using any library but using vanilla JS only. So I took a problem from Advent of Code.

https://adventofcode.com/2017/day/3

  You come across an experimental new kind of memory stored on an
  infinite two-dimensional grid.

  Each square on the grid is allocated in a spiral pattern starting at a
  location marked 1 and then counting up while spiraling outward. For
  example, the first few squares are allocated like this:

  17  16  15  14  13
  18   5   4   3  12
  19   6   1   2  11
  20   7   8   9  10
  21  22  23---> ...

  While this is very space-efficient (no squares are skipped), requested
  data must be carried back to square 1 (the location of the only access
  port for this memory system) by programs that can only move up, down,
  left, or right. They always take the shortest path: the Manhattan
  Distance between the location of the data and square 1.

  For example:

  Data from square 1 is carried 0 steps, since it's at the access port.
  Data from square 12 is carried 3 steps, such as: down, left, left.
  Data from square 23 is carried only 2 steps: up twice. Data from
  square 1024 must be carried 31 steps. How many steps are required to
  carry the data from the square identified in your puzzle input all the
  way to the access port?

  Your puzzle input is still 289326.

My solution in FP is:

const getSquare = (b, n) => {
  const result = Math.pow(b, 2);
  if (n === 1) {
    return 1;
  }
  if (result >= n) {
    return b;
  }
  return getSquare(b + 2, n);
};
const seq = (m, n) => m > n ? [] : [m].concat(seq(m + 1, n));
const getDirection = (square, n) => {
  const steps = (square - 1) / 2;
  if (n === 1) return 0;
  const east = seq(Math.pow(square - 2, 2) + 1, Math.pow(square - 2, 2) +
    square - 1);
  const north = seq(east[east.length - 1] + 1, east[east.length - 1] +
    square - 1);
  const west = seq(north[north.length - 1] + 1, north[north.length - 1] +
    square - 1);
  const south = seq(west[west.length - 1] + 1, west[west.length - 1] +
    square - 1);
  const x_directions = [east, west];
  const y_directions = [north, south];
  const getSteps = getStepsOf(n);
  const xy_direction = getSteps(x_directions);
  const yx_direction = getSteps(y_directions);
  const addSteps = addXAndYSteps(steps);

  return xy_direction !== -1 ? addSteps(xy_direction) : addSteps(yx_direction);
};
const addXAndYSteps = steps => directions => {
  if ((directions + 1) > steps) {
    return steps + ((directions + 1) - steps);
  } else if ((directions + 1) === steps) {
    return steps;
  } else {
    return steps + (steps - (directions + 1));
  }
};
const getStepsOf = n => directions => directions.reduce((res, direction) => {
  const position = direction.findIndex(dir => dir === n);
  return (position > -1) ? position : res;
}, -1);
const num = 289326;
const solution = n => getDirection(getSquare(1, n), n);
console.log("Total Steps: ", solution(num));

Is there a better way to write it in FP with pure JavaScript, i.e. no additional FP library? Any improvement suggestions are welcomed.


texts:
I'm trying to solve Alphacode on SPOJ.  The challenge is to count the ways to split a string of up to 5000 digits into a sequence of numbers, each ranging from 1 to 26.

It works fine for small numbers but exceeds the time limit for bigger numbers. I'm using the exhaustive recursive traversing.

Is there a way to make it optimal?

import java.util.HashSet;
import java.util.Scanner;

public class AlphaCode {

    static int n;
    static HashSet<String> set;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            String s = sc.nextLine();
            if (s.equals("0")) {
                break;
            }
            n = s.length();
            char[] c = new char[n];
            set = new HashSet<String>();
            count = 0;
            solve(s, 0, c);
            System.out.println(count);
        }
    }

    static int count = 0;

    private static int solve(String s, int i, char[] st) {
        if (n == i) {
            // System.out.println(st);
            if (set.contains(st.toString())) {
                return 0;
            }
            count++;
            return 0;
        }
        for (int j = 0; j < 2 && i + j < n; ++j) {
            int x = Integer.parseInt(s.substring(i, i + j + 1) + "");
            if (x <= 26) {
                // System.out.println(i + " " + j + " " + s.substring(i, i + j +
                // 1));
                st[i] = (char) (x + 'A' - 1);
                solve(s, i + j + 1, st);
            }
        }
        return 0;
    }

}


texts: Refactoring Java transmitter delegate implementation

texts:
I have 3 classes: a transmitter, a view for displaying and a recording view for flushing the screen contents into a file. The view and the recording view classes register themselves from their constructor in the transmitter, which keeps them in a HashMap. The transmitter implements all the view and recording view classes' interfaces, and delegates the incoming method invocations to them based on the actually registered implementors.

To make things clear:

public interface IRecordingView {
  public void recordingViewMethod1();
  public void recordingViewMethod2();
}

public class RecordingView implements IRecordingView {
  public RecordingView {
    Transmitter.getInstance().register(this);
  }

  @Override public void recordingViewMethod1() { ... }
  @Override public void recordingViewMethod2() { ... }
}

public interface IView {
  public void viewMethod1();
  public void viewMethod2();
}

public class View implements IView {
  public View() {
    Transmitter.getInstance().register(this);
  }

  @Override public void viewMethod1() { ... }
  @Override public void viewMethod2() { ... }
}

public class Transmitter implements IRecordingView, IView {
  private static final Transmitter instance = new Transmitter();
  private HashMap<Class, Set> register = new HashMap<Class, Set>();

  public Transmitter() {
    for (Class cl : this.getClass().getInterfaces()) {
      register.put(cl, new HashSet());
    }
  }

  public void register(Object listener) {
    for (Class interf : register.keySet()) {
      if (interf.isInstance(listener)) {
        Set implementors = register.get(interf);
        implementors.add(listener);
      }
    }
  }

  @Override public void viewMethod1() {
    for (IView delegate : register.get(IView.class)) {
      delegate.viewMethod1();
    }
  }

  @Override public void recordingViewMethod1() {
    for (IRecordingView delegate : register.get(IRecordingView.class)) {
      delegate.recordingViewMethod1();
    }
  }

  // and so on for the rest of the methods
}

This is the basic concept of the legacy code. Of course there are many transmitters, each implementing more interfaces, with each interface having more methods. Is there an optimal and/or elegant way to further reduce code size? The delegation mechanism looks quite the same in every method, but I don't want to mess with reflection.


texts:
Here are two very small blocks of code I wrote while trying to fix a bug in AngularJS. Both do the same thing. I'm trying to understand how the two differ, mainly in terms of the tradeoff between cpu and memory efficiency.

Here is version 1:

function findSearch(url) {
  var index = url.indexOf('?');
  return index === -1 ? false : url.substr(index + 1, url.indexOf('#') === -1 ? url.length : url.indexOf('#') - index - 1);
}

//version 1
// more memory intensive, less cpu intensive?
var paramRewrittenUrl = withoutHashUrl;
var search = findSearch(appBase);
if (search !== false) {
  var indexOfAppFragment = withoutHashUrl.indexOf('#');
  if (indexOfAppFragment !== -1) {
    paramRewrittenUrl = withoutHashUrl.substr(0, indexOfAppFragment) + '?' + search + withoutHashUrl.substr(indexOfAppFragment, withoutHashUrl.length);
  } else {
    paramRewrittenUrl = withoutHashUrl + '?' + search;
  }
  if (findSearch(withoutHashUrl) !== false) {
    var indexOfAppPath = withoutHashUrl.indexOf('?');
    if (indexOfAppPath !== -1) {
      paramRewrittenUrl = withoutHashUrl.substr(0, indexOfAppPath + 1) + search + '&' + withoutHashUrl.substr(indexOfAppPath + 1, withoutHashUrl.length);
    }
  }
}
withoutHashUrl = paramRewrittenUrl;

And here is Version 2 (note that findSearch() is identical)

//version 2 - more cpu intensive, less memory intensive?
var search = findSearch(appBase);
if (search !== false) {
  if (findSearch(withoutHashUrl) === false) {
    var indexOfAppFragment = withoutHashUrl.indexOf('#');
    if (indexOfAppFragment !== -1) {
      withoutHashUrl = withoutHashUrl.substr(0, indexOfAppFragment) + '?' + search + withoutHashUrl.substr(indexOfAppFragment, withoutHashUrl.length);
    } else {
      withoutHashUrl = withoutHashUrl + '?' + search;
    }
  } else {
    search = parseKeyValue(search);
    var indexOfAppPath = withoutHashUrl.indexOf('?');
    if (indexOfAppPath !== -1) {
      withoutHashUrl = withoutHashUrl.substr(0, indexOfAppPath + 1) + toKeyValue(search) + '&' + withoutHashUrl.substr(indexOfAppPath + 1, withoutHashUrl.length);
    } else {
      var indexOfAppFragment = withoutHashUrl.indexOf('#');
      if (indexOfAppFragment !== -1) {
        withoutHashUrl = withoutHashUrl.substr(0, indexOfAppFragment) + '?' + toKeyValue(search) + withoutHashUrl.substr(indexOfAppFragment, withoutHashUrl.length);
      } else {
        withoutHashUrl = withoutHashUrl + '?' + toKeyValue(search);
      }
    }
  }
}

I think the first version is less cpu intensive but more memory intensive, while the second version is more cpu intensive but uses less memory. Do you think that's an accurate understanding of the two implementations?  Is there something else I'm missing?  Are they genuinely equivalent in terms of behaviour?  Is there a particular reason to prefer one over the other?


texts: Skinny model, fat controller in Rails managing user IP addresses

texts:
As part of learning Rails framework, I have small app in progress. Basically idea is, user can create IP address, define is it in use, to which server is assigned, which user is it using and role of IP address in web hosting environment. I have 3 models, IpAddress, IpAddressRole and IpAddressUser. User is able to define IpAddressRole and IpAddressUser from prepopulated postgresql database.

Main controller is IpAddressesController, which is responsible for creating, showing and other CRUD operations on primary model.

ip_addresses_controller.rb code is here:

class IpAddressesController < ApplicationController

    def index
        @ip_addresses = IpAddress.all.order(:title)
    end

    def show
        @ip_address = IpAddress.find(params[:id])
    end

    def new
        @ip_address_roles = IpAddressRole.all
        @servers = Server.all
        @ip_address_users = IpAddressUser.all
    end

    def create
        @ip_address_roles = IpAddressRole.all
        @servers = Server.all
        @ip_address_users = IpAddressUser.all

        @ip_address = IpAddress.new(ip_address_params)
        @ip_address.save
        redirect_to ip_addresses_path
        #render plain: params[:ip_address].inspect
    end

    def destroy
        @ip_address = IpAddress.find(params[:id])
        @ip_address.destroy
        flash[:success] = "Record successfully deleted"
        redirect_to ip_addresses_path
    end

    private
        def ip_address_params
            params.require(:ip_address).permit(:title, :server, :user, :is_in_use, :role)
        end
end

And ip_address.rb code is here:

class IpAddress < ActiveRecord::Base
    def is_ip_address_in_use
        if self.is_in_use == 'true'
            self.is_in_use = 'yes'
        else
            self.is_in_use = 'no'
        end
    end

end

I have some great resources near hand, but my controller is getting fat, and model skinny, also, in my controller I have a lot of repetition. How can I refactor model and controller? Controller is really ugly.


texts: Would be possible to refactor this PHP code more?

texts:
I really don't like the so many return statements. Anyone think that this could be refactored more?

public function validate($value, Constraint $constraint)
{
    if('' === $value || null === $value) {
        return;
    }

    if(!preg_match('/^[0-9]{7}([0-9]{3})[0-9]{1}$/', $value, $matches)) {
        $this->context->addViolation($constraint->message, array(
            '{{ value }}' => $value
        ));
        return;
    }

    // Fast Luhn check
    $vatin = (string) $matches[0];

    $luhn = array(0, 2, 4, 6, 8, 1, 3, 5, 7, 9);
    $sum  = 0;

    for($i = 0; $i < strlen($vatin); $i++) {
        $dgt  = (int) substr($vatin, $i, 1);
        $sum += (0 === $i % 2) ? $dgt : $luhn[$dgt];
    }

    if(0 !== ($sum % 10)) {
        $this->context->addViolation($constraint->message, array(
            '{{ value }}' => $value
        ));
        return;
    }

    // Province check
    $provinceCode = $matches[1];

    if(!in_array((int) $provinceCode, range(1, 121) + array(888, 999))) {
        $this->context->addViolation($constraint->provinceMessage, array(
            '{{ value }}' => $provinceCode
        ));
    }
}


texts:
Mac doesn't have the Unix clock_gettime so I am trying to create something that's really portable and only dependent on C.

So far I've come across this function:

static void current_utc_time(struct timespec *ts) {
#ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
    clock_serv_t cclock;
    mach_timespec_t mts;
    host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
    clock_get_time(cclock, &mts);
    mach_port_deallocate(mach_task_self(), cclock);
    ts->tv_sec = mts.tv_sec;
    ts->tv_nsec = mts.tv_nsec;
#else
  clock_gettime(CLOCK_REALTIME, ts);
#endif
}

I would like to be able to get seconds and milliseconds for my purposes. This is what I am currently doing and would like some feedback on correctness:

struct timespec requestStart, requestEnd;
current_utc_time(&requestStart);
int i = 0;
while(i < 1000000000)
{
    ++i;
}
current_utc_time(&requestEnd);
printf("total: ms:  %lu\n", (requestStart.tv_nsec - requestEnd.tv_nsec) / (unsigned long)1000000);

This prints out: total: ms:  131

It seems to be correct but I just wanted to make sure before I proceeded. Am I doing my calculations correctly and how can I get the seconds as well as milliseconds?


texts: Python shuffle the middle letters in all the words of a sentence

texts:
The purpose of the program is to shuffle only the middle letters of each word in a sentence, leaving it still readable like this:

  Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae.

def garble(sentence):

    return ' '.join([word[0] + ''.join(random.sample([char for char in word[1:-1]],len(word[1:-1]))) + word[-1] if len(word) > 1 else word for word in  sentence.split()])

I definitely think I have gone overboard putting it all in one line but I'm not sure where to separate it


texts:
I'm a Clojure beginner and I implemented Game of life to learn how I should code things in Clojure.

(def state (ref [
    [false false false false false]
    [false false true  false false]
    [false false true  false false]
    [false false true  false false]
    [false false false false false]]))

(defn get-state [state x y]
  (nth (nth state y) x))

(defn count-true-neighbours [state x y]
  (let [size (count state)]
    (->>
      (for [p (range (- x 1) (+ x 2))
            q (range (- y 1) (+ y 2))
            :when (not (and (= x p) (= y q)))]
        [p q])
      (map (fn [coord]
        (let [[p q] coord]
          (if (or (< p 0) (>= p size) (< q 0) (>= q size))
            false
            (get-state state p q)))))
      (filter true?)
      (count))))

(defn next-state-of [state x y]
  (let [alive (get-state state x y)
        alive-neighbours (count-true-neighbours state x y)]
    (cond
      (and (not alive) (= alive-neighbours 3)) true
      (and alive (or (= alive-neighbours 2) (= alive-neighbours 3))) true
      :else false)))

(defn next-state [state]
  (let [size (count state)]
    (mapv
      (fn [row]
        (mapv
          #(next-state-of state %1 row)
          (range 0 size)))
      (range 0 size))))

(defn pretty-print [state]
  (let [size (count state)]
    (loop [i 0]
      (if (< i size)
        (do
          (println
            (->>
              (nth state i)
              (mapv #(if %1 "■ " "□ "))
              (reduce str)))
          (recur (inc i)))))))

(defn tick
  ([times] (tick 0 times))
  ([i times]
    (if (< i times)
      (do
        (dosync
          (println (str i ":"))
          (pretty-print @state)
          (ref-set state (next-state @state)))
        (recur (inc i) times))
      nil)))

(defn -main [& args]
  (tick 5))

I used ref to learn how to manage state although it seems like an overkill for this tiny program.

As you see my code is terrible, but I couldn't improve this by myself.

I already checked this answer, but I think I did this in a quite different way and need a different advice.


texts: Classical model for database connection provider

texts:
Let's forget about Spring Singleton Beans and about other frameworks in Java. We have one or more simple HttpServlets. And we should make database connection. (doesn't matter what is it,  hibernate session factory or JDBC connection). Always I write the following pattern:

class DatabaseService {

    private static DatabaseService instance;

    public static void init() {
        instance = new DatabaseService();
    }

    public static void destroy() {
        //.. destroy
    }

    public static DatabaseService getInstance() {
        return instance;
    }

    private Connection conn;

    private DatabaseService() {
        conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
    }

    public Connection getConnection() {
        return conn;
    }
}

And every my servlet gets database connection from singleton. But what you think about efficiency that solution? Where I should initialize my DatabaseService singleton? Are there a better solution?


texts:
I have 12 games that I need to sort through that each have a date and img string.  I'm fairly new to jQuery and was wondering what is the best way to accomplish this. Is there a way that I can run this through a loop of some sort rather than having 12 else-if statements like I currently have (code condensed to 3 for readability)? This code works, I was just looking for the cleaner more concise way of writing it.

var now = new Date();
boise = { date: new Date ('May 15, 2012'), img: 'Boise' };
central = { date: new Date ('May 21, 2012'), img: 'Central' };
notreDame = { date: new Date ('May 27, 2012'), img: 'NotreDame' };
    ...
banner = $('#nextGameBanner');
imgDir = 'images/nextGame';

if (now < boise.date ) {
    banner.attr('src', imgDir+boise.img+'.jpg');
}
else if (now < central.date) {
    banner.attr('src', imgDir+central.img+'.jpg');
}
else if (now < notreDame.date) {
    banner.attr('src', imgDir+notreDame.img+'.jpg');
}
    ...

HTML

<img src="/website/images/nextGame.jpg" id="nextGameBanner" />


texts: Replicating C#-style events in Java using reflection

texts:
For something I'm doing, it would just make things so much easier, quicker, and cleaner to have C# style events. I've written a class I believe should replicate a C# style event using reflection. Since I've never actually used reflection before in any meaningful sense, I'm very much not happy using it without, at the very least, a second opinion.

I want to declare an event with:

public Event SomeEvent = new Event();

Raise the event (presumably within the declaring class) with (where SomeArguments is whatever class that may be specified in the Javadocs boxed in an Object):

SomeEvent.Raise(this, SomeArguments);

Add a method to be called when the event is raised with:

SomeEvent.AddListener(this, "onSomeEvent");

Stop a method being called when an event is raised with:

SomeEvent.RemoveListener(this, "onSomeEvent");

And cancel all listeners with:

SomeEvent.ClearListeners();

Methods to listen to the event should be formatted like:

public void onSomeEvent(object Sender, object SomeArguments)
{ }

And this is my class:

package puppy.hanii.library;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class Event
{
    public Event()
    {
        Methods = new ArrayList<Method>();
        DeclaringClasses = new ArrayList<Object>();
    }

    ArrayList<Method> Methods;
    ArrayList<Object> DeclaringClasses;

    public boolean AddListener(Object Class, String MethodName)
    {
        try
        {
            Method MTR = Class.getClass().getMethod(MethodName, Object.class, Object.class); // MTR = Method To Register.

            if(Methods.contains(MTR))
                return false;
            else
            {
                Methods.add(MTR);
                DeclaringClasses.add(Class);
                return true;
            }
        }
        catch (NoSuchMethodException error) { throw new RuntimeException("No such method, or correct overloads of method, exists."); }
    }

    public boolean RemoveListener(Object Class, String MethodName)
    {
        try
        {
            DeclaringClasses.remove(Class);
            return Methods.remove(Class.getClass().getMethod(MethodName, Object.class, Object.class));
        }
        catch (NoSuchMethodException error) { throw new RuntimeException("No such method, or correct overload of method, exists."); }
    }

    public void ClearListeners()
    {
        Methods.clear();
        DeclaringClasses.clear();
    }

    public void Raise(Object Sender, Object Arguments)
    {
        for(int i = 0; i < Methods.size(); i++)
        {
            try
            { Methods.get(i).invoke(DeclaringClasses.get(i), Sender, Arguments); }
            catch(IllegalAccessException error)
            { }
            catch(InvocationTargetException error)
            { throw new RuntimeException("Error in event handler"); }
        }
    }
}


texts:
Basically, the code converts a large select list with optgroups into a more user-friendly tabbed Twitter-bootstrap component.

I'm not sure how much into detail I need to get but on GitHub I uploaded a working example. This is the first time I write a jquery plugin and any advise is welcome.

(function($) {
    $.fn.bootstrapSelect = function(options) {

        //Extend default options with those provided.
        var opts = $.extend({}, $.fn.bootstrapSelect.defaults, options);

        var topLevel='';
        var subLevel='';
        var selectedValue ='';
        var sectionActive = false;
        var selected = '';

        // Rewrite the info in the select box
        $('optgroup',this).each(function(x) { //for each optgroup

            //get section label
            var sectionLabel = $(this).attr('label');

            //get section content
            var sectionContent = '';
            $('option',this).each(function(x) {

                /*Check if an option is selected, and set section active*/
                if ($(this).attr('selected')) {
                    selectedValue = $(this).attr('value');
                    sectionActive = true;
                }
                sectionContent += '' + $(this).text() + '\n';
            });

            sectionActive ? selected = true : false;

            topLevel += '
' + sectionLabel + '
\n';

            subLevel += '
\n' + sectionContent + '
\n';

            sectionActive = false;

        });
        //Replacement tabbed select
        var tabbedselect = '
\n';
        if ( opts.position != "tabs-below") tabbedselect += '
\n'+topLevel+'
\n';
        tabbedselect += '
\n'+subLevel+'
\n'
        if ( opts.position == "tabs-below") tabbedselect += '
\n'+topLevel+'
\n';
        tabbedselect += '
\n';

        // Replace the select with the tabbed menu
        this.replaceWith(tabbedselect);

        // Add hidden input field with the selected value
        $("form").append('<input type="hidden" name="'+opts.inputId+'" id="'+opts.inputId+'" value="'+selectedValue+'" />');

        //set first tab and content area active if nothing is selected
        if (selected == false) {
            $("div.tab-content div:first-child").addClass("active");
            $("ul.nav-tabs li:first-child").addClass("active");
        }

        // set input field value on click
        $(".tab-content a").click(function () {
            $("*").removeClass("bsactive");
            $(this).addClass("bsactive");
            $('input#'+opts.inputId).attr('value', $(this).attr('value'));
        })
    };

    //default settings
    $.fn.bootstrapSelect.defaults = {
        'position' : 'tabs-left',
        'inputId'  : 'bootstrap-select'
    };

})(jQuery);


texts:
Firstly, would appreciate some code-review feedback, from a TDD and design perspective.

Secondly, what are your thoughts on implementing test case: testNumbersAreUnique()? The fact that API returns a Set of immutable objects means elements will be unique, but just wanted to know your thoughts. The reason I used a do-while as against a  while or for loop (and iterate ‘x’ times to populate ‘x’ Random numbers) is to ensure the set has correct number of elements (which will of course be unique) even if the random number gives something that is already existing in the Set.

The problem: Lottery Generator

  The goal of the program is to generate ‘x’ distinct lottery numbers within a given range 1 to ‘N’. Both x and N are int for simplicity.

Following is my code.
I wrote a controller, which will call service layer to fetch ‘x’ distinct lottery numbers:

public class Controller {
  private LotteryGeneratorService lotteryGeneratorService;
  @RequestMapping(method=RequestMethod.GET)
  public Set<Integer> getLotteryNumbers(int x){
    lotteryGeneratorService = new  LotteryGeneratorService();
    return lotteryGeneratorService.generateNRandom (x);
  }
}

This is the Service class:

public class LotteryGeneratorService {
private  Set<Integer> set = new HashSet<>();
private static int generateRandomInt(){
    Random random = new Random();
    return random.nextInt(N);
}
public Set<Integer> generateNRandom(int x){
    int tmp;
    do{
        tmp =generateRandomInt();
        if(tmp!=0)
        set.add(tmp);
    }
    while(set.size()<x);
    return set;
}
public int getSizeOfRandomlyGeneratedSet(){
    return set.size();
 }

}

The tests:

public class LotteryTest {
LotteryGeneratorService lotteryGeneratorService;
int N;
@Before
public void setup() {
    lotteryGeneratorService = new LotteryGeneratorService();
    N=100;
}
@After
public void tearDown() {
    lotteryGeneratorService = null;
}
@Test
public void testNumberOfNumbersGeneratedIsCorrect() {
    assertEquals(6, lotteryGeneratorService.generateNRandom(6).size());
}
@Test
public void testRangeIsCorrect() {
    Set<Integer> set = lotteryGeneratorService.generateNRandom(6);
    for (int i : set) {
        assertTrue(i >= 1 && i <= N);
    }
}
@Test
public void testNumbersAreUnique() {
    //..?
 }
}


texts: Devise a program that counts the number of characters in its input up to the end of file

texts:
This is my code:

#include <stdio.h>
#include <ctype.h>

int main()

{
    int ch;
    int numberOfCharacters = 0;
    printf("please enter a word, and ctrl + d to see the resault\n");

    while ((ch = getchar()) != EOF && isprint(ch))

    {
        numberOfCharacters++;
    }

    printf("The number of characters is %d", numberOfCharacters);

    return 0;
}

Is this a good code?


texts: Create an array with the highest values from each array

texts:
I am working my way through FreeCodeCamp's Javascript challenges and Return Largest Numbers in Arrays took me a minute. In this one the goal was to create an array with the highest values from each array as its elements.

I am currently using for loops to iterate through the various arrays and arrays of arrays. I wanted to see if there was a better way to do this challenge.

function largestOfFour(arr) {
  // You can do this!
  var largestNum = 0;
  var newArray = [];
  for(var i = 0; i < arr.length; i++){
    for(var k = 0; k < arr.length; k++){
      console.log(arr[i][k]);
      //create comparison
      a = arr[i][k];
      if(a>largestNum){
        largestNum = a;
        newArray[i] = largestNum;
      }
    }
    largestNum=0;
  }
  console.log('complete Test' + newArray);
  return newArray;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);


texts: Find indices of white space characters in a string

texts:
This function returns the indices of all white spaces as an array of Integer. It works fine with a small string:

func whiteSpacesIndices(value : String) -> Array<Int> {
    var indices: Array<Int> = []
    for (index, char) in value.enumerated() {
        if char == " " || char == "\n" || char == "\t" {
            indices.append(index)
        }
    }
    return indices
}

However when the string is too long, it could be very slow, because it is looping in every character.

Is there a better way for doing it?


texts: Manager for customer billing and subscriptions in Rails

texts:
I'm looking to get rid of a couple dependencies that I have a sneaking suspicion are present in the code that I'm writing.

Right now I have a service class that manages my subscriptions for part of my application in Rails. The problem is that we have Recurly as our management platform right now, but I don't know if we will keep this in 6 months, 12 months, 5 years, etc. So there is an inherent dependency in place for this that I want to try to eliminate.

Additionally, I have a couple lines that I've added to manage updating subscription status for plans on our ActiveRecord models that I think might be adding some additional complexity to the class that I don't know if that's a good practice or if there is another pattern I should be following.

  module Tollbooth
      class Manager
        include Tollbooth::Querying

        attr_reader :business

        def initialize business
          @business = business
        end

        ##################################################
        # Customer and plan details
        ##################################################

        def on_trial?
          current_subscription.trial_ends_at && current_subscription.trial_ends_at >= Time.zone.now
        end

        def trial_ends
          current_subscription.trial_ends_at
        end

        def next_billing_date
          current_subscription.current_period_ends_at
        end

        def set_to_expire?
          current_subscription && current_subscription.canceled_at.present?
        end

        def current_subscription
          @current_subscription ||= Recurly::Subscription.find(business_subscription_uuid)
        end

        def pending_subscription
          return(@pending_subscription) if defined?(@pending_subscription)
          @pending_subscription ||= begin
            current_subscription.pending_subscription
          rescue Recurly::Resource::NotFound
            nil
          end
        end

        def current_plan
          @current_plan ||= Recurly::Plan.find(current_subscription.plan_code)
        end

        def pending_plan
          @pending_plan ||= Recurly::Plan.find(pending_subscription.plan_code)
        end

        def billing_info
          @billing_info ||= account.billing_info
        end

        def transactions
          account.transactions
        end

        ##################################################
        # Changing plan details
        ##################################################

        def change_subscription_to code
          current_amount  = current_plan.unit_amount_in_cents['USD']
          future_amount   = Recurly::Plan.find(code).unit_amount_in_cents['USD']
          timeframe       = current_amount > future_amount ? 'renewal' : 'now'
          success, result = query(current_subscription, :update_attributes, { plan_code: code, timeframe: timeframe })
          business.update(plan: Plan.where(plan_code: code).first) if success
          # The above line is one where I'm not sure if this is how I should be doing this since Plan is another ActiveRecord model
          success
        end

        def start_subscription code
          success, result = query(account.subscriptions, :create, { plan_code: code })
          business.update(subscription_uuid: result.uuid, subscription_state: 'active', plan: Plan.where(plan_code: code).first) if success
   # The above line is one where I'm not sure if this is how I should be doing this since Plan is another ActiveRecord model
          success
        end

        def cancel_subscription
          success, result = query(current_subscription, :cancel)
          success
        end

        def reactivate_subscription
          success, result = query(current_subscription, :reactivate)
          success
        end

        def destroy
          account.destroy
        end

      end
    end


texts:
Another exercise in Scala in which the goal is to find the target position as fast as possible. The initial input provides the grid size and the initial position. Each turn, this code provide a new position using println and the direction to the target is given back as a string ("UR" up-right, "DL" down-left, etc). The exercise does not require to end the infinite loop.

import math._
import scala.util._

object Player extends App {
    def getDirection(input: String): (Int, Int) = {
        input match {
            case "U" => (0, -1)
            case "UR" => (1, -1)
            case "R" => (1, 0)
            case "DR" => (1, 1)
            case "D" => (0, 1)
            case "DL" => (-1, 1)
            case "L" => (-1, 0)
            case "UL" => (-1, -1)
        }
    }

    def findNewRelativePositionOnAxis(direction: Int, min : Int, max : Int, current : Int) : Int = {
        direction match {
            case 1 => (max - current + 1 ) / 2
            case -1 => if(current == 1) -1 else (min - current - 1 ) / 2    //edge case for when the goal is at position 0
            case _ => 0
        }
    }

    def loop(x: Int, y: Int, minX: Int, minY: Int, maxX: Int, maxY: Int): Nothing = {
        val goaldir = getDirection(readLine)

        //Update min and max values to narrow down the search
        val newMaxX = if(goaldir._1 == -1) x else maxX
        val newMaxY = if(goaldir._2 == -1) y else maxY
        val newMinX = if(goaldir._1 == 1) x else minX
        val newMinY = if(goaldir._2 == 1) y else minY

        //Compute the next position
        val newX = x + findNewRelativePositionOnAxis(goaldir._1, newMinX, newMaxX, x)
        val newY = y + findNewRelativePositionOnAxis(goaldir._2, newMinY, newMaxY, y)

        //Send the result
        println(newX + " " + newY)

        loop(newX, newY, newMinX, newMinY, newMaxX, newMaxY)
    }

    // w: width of the building.
    // h: height of the building.
    val Array(width, height) = for(i <- readLine split " ") yield i.toInt
    val Array(x0, y0) = for(i <- readLine split " ") yield i.toInt

    loop(x0, y0, 0, 0, width, height)
}


texts: Using Timer with Backgroundworker to ensure the doWork method is called

texts:
I have a windows forms application in which a backgroundworker is called again and again.
I need to avoid concurrent access of the code in dowork method for the backgroundWorker; but also need to ensure that the code in the dowork method is called; hence I cannot simply avoid running the backgroundworker altogether if it is busy.

The code is provided below with detailed comments:
The code as it is works nicely; Please evaluate the code and this way of achieving the intended; Please let me know of any potential problems,code smells, design flaws or better way of doing this. Any kind of comments, answers will be of great help.

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
 {
  public partial class Form1 : Form
   {
    // this timer calls bgWorker again and again after regular intervals
    System.Windows.Forms.Timer tmrCallBgWorker;

    // this is our worker
    BackgroundWorker bgWorker;

    // this is the timer to make sure that worker gets called
    System.Threading.Timer tmrEnsureWorkerGetsCalled;

    // object used for safe access
    object lockObject = new object();

    public Form1()
    {
        InitializeComponent();
        // this timer calls bgWorker again and again after regular intervals
        tmrCallBgWorker = new System.Windows.Forms.Timer();
        tmrCallBgWorker.Tick += new EventHandler(tmrCallBgWorker_Tick);
        tmrCallBgWorker.Interval = 100;

        // this is our worker
        bgWorker = new BackgroundWorker();
        // work happens in this method
        bgWorker.DoWork += new DoWorkEventHandler(bg_DoWork);
        bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);

    }

    void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Complete");
    }

    void bg_DoWork(object sender, DoWorkEventArgs e)
    {
        // does a job like writing to serial communication, webservices etc
        System.Threading.Thread.Sleep(100);
    }

    void tmrCallBgWorker_Tick(object sender, EventArgs e)
    {
        if (Monitor.TryEnter(lockObject))
        {
            try
            {
                // if bgworker is not busy the call the worker
                if (!bgWorker.IsBusy)
                    bgWorker.RunWorkerAsync();
            }
            finally
            {
                Monitor.Exit(lockObject);
            }

        }
        else
        {

            // as the bgworker is busy we will start a timer that will try to call the bgworker again after some time
            tmrEnsureWorkerGetsCalled = new System.Threading.Timer(new TimerCallback(tmrEnsureWorkerGetsCalled_Callback), null, 0, 10);

        }

    }

    void tmrEnsureWorkerGetsCalled_Callback(object obj)
    {
        // this timer was started as the bgworker was busy before now it will try to call the bgworker again
        if (Monitor.TryEnter(lockObject))
        {
            try
            {
                if (!bgWorker.IsBusy)
                    bgWorker.RunWorkerAsync();
            }
            finally
            {
                Monitor.Exit(lockObject);
            }
            tmrEnsureWorkerGetsCalled = null;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        tmrCallBgWorker.Start();
    }
  }
}


texts:
I have written a password checker using PHP, consisting of many if else statements. Is there any possible way to shorten this code?

function passtest($pass) {
            if (!empty($pass)) { //check if string is empty
                if (ctype_alnum($pass)) { //check if string is alphanumeric
                    if (7 < strlen($pass)){ //check if string meets 8 or more characters
                        if (strcspn($pass, '0123456789') != strlen($pass)){ //check if string has numbers
                            if (strcspn($pass, 'abcdefghijklmnopqrstuvwxyz') != strlen($pass)) { //check if string has small letters
                                if (strcspn($pass, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') != strlen($pass)) { //check if string has capital letters
                                    return "
Password passed";
                                }
                                else {
                                    return "
No capital letter";
                                }
                            }
                            else {
                                return "
No small letter";
                            }
                        }
                        else {
                            return "
No number";
                        }
                    }
                    else {
                        return "
Password is short";
                    }
                }
                else {
                    return "
Password has special character";
                }
            }
            else {
                return "
Password field is empty";
            }
        }


texts: Program that finds the stretch factor of a parabola

texts:
Being a newcomer to C++, I decided to write a simple program that would accomplish a simple task.

I settled on writing a program that, given the vertex and point on a parabola, find the "stretch factor", or \$a\$ in the vertex-form equation \$y=a(x-h)^2+k\$.

This is my first go at working with pointers/references, and I expect this attempt to be rather feeble. The program works fine, however, I would love to know if I am employing any measures that are inefficient or that break good practice.

/*
 * pwidth.cpp
 * Given the vertex and a point on a parabola, attempts to find the "stretch factor",
 * which is the `a` var in vertex form equation y=a(x-h)^2+k.
 */

#include <iostream>
#include <cmath>

using namespace std;

float pwidth(int *vx, int *vy, int *px, int *py) {
    return (*py - *vy) / pow(*px - *vx, 2);
}

void gcin(int &cstor, const string &message) {
    cout << message;
    cin >> cstor;

    while (cin.fail()) {
        cout << message;

        cin.clear();
        cin.ignore(256, '\n');

        cin >> cstor;
    }
}

int main() {
    int vx = 0, vy = 0, px = 0, py = 0;

    gcin(vx, "enter vertex X: ");
    gcin(vy, "enter vertex Y: ");
    gcin(px, "enter point X: ");
    gcin(py, "enter point Y: ");

    cout << "a = " << pwidth(&vx, &vy, &px, &py) << endl;

    return 0;
}


texts:
There is my SSCCE to generate a value of discrete random variable.

values is set of value the RV can take and procents is equivalent to discrete pdf.

Can you anticipate any issue with this snippet?

import java.util.Random;

public class RandomTest {
    public static void main (String[] args) throws Exception {
        RandomTest rt = new RandomTest();

        int[] values = {0, 1, 2};
        int[] procents = {30, 60, 10};

        for (int i=0; i < 10; i++) {
            System.out.print(rt.discreteRV(values, procents) + " ");
        }
    }

    public int discreteRV (int[] values, int[] procents) throws Exception {
        if (values == null || procents == null) throw new Exception("Input parameters are null");
        if (values.length != procents.length) throw new Exception("Input parameters length mismatch");

        int sumProcents = 0;
        for (int i=0; i < procents.length; i++) {
            if (procents[i] < 0) throw new Exception("Negative procents are not allowed");
            sumProcents += procents[i];
        }

        if (sumProcents != 100) throw new Exception("Sum of procents is not 100");

        int rand = new Random().nextInt(100);

        int left = 0, right = 0;
        for (int i=0; i < procents.length; i++) {
            right += procents[i];
            if (rand >= left && rand < right)
                return values[i];
            left = right;
        }

        throw new Exception("");
    }
}


texts:
I am solving a puzzle (Finding if there exists an input for a given automata for which no matter what the starting state is, final state would be same everytime) and have written following Python code. A few testcases are written in check method in the code. For these cases program is running fairly fast. However, for testcases where 50 lists (nodes) are present, the program is taking forever to execute. I am storing intermediate results to use further as well. Can someone please review the code and give suggestions on how to increase the performance of the code?

from itertools import product
from copy import deepcopy

class Node:
    def __init__(self,id):
        self.id = id
        self.dict = {}

    def __str__(self):
        return str(self.id) + " : " + str(self.dict)

    def __repr__(self):
        return str(self.id) + " : " + str(self.dict)

def tryDelete(nodes,_len):
    for i in range(len(nodes)):
        y = nodes[:]
        x = y[i]
        del y[i]
        tNodes = []
        for node in y:
            for input,result in node.dict.items():
                if result == x:
                    node.tDict = deepcopy(node.dict)
                    if x.dict[input] == x.id:
                        node.dict[input] = node
                    else:
                        node.dict[input] = x.dict[input]

        if pathPossible(y,_len ,False) == -1:
            return x.id
        for n in tNodes:
            n.dict = n.tDict
            del n.tDict
    return -2

target = {}
def FindTarget(node,p):
    if len(p) == 1:
        return node.dict[p[0]]
    if node not in target or p not in target[node]:
        x = Gnodes[FindTarget(node,p[:-1])].dict[p[-1]]
        if node not in target:
            target[node] = {}
        target[node][p] = x
    return target[node][p]

def allSatisy(nodes,p):
    x = None
    for node in nodes:
        if x is None:
            x = FindTarget(node,p)
        elif FindTarget(node,p) != x:
            return False
    return True

def allPossiblePaths(l,n):
    #x = int(((l+1)*(l+2))/2)
    for i in range(1, n + 1):
        for p in product(range(l),repeat=i):
            yield p

def pathPossible(nodes,_len ,isItereate=True):
    i = 1
    isFound = False
    for p in allPossiblePaths(_len,len(nodes)):
        if allSatisy(nodes,p):
            isFound = True
            break

    if isFound:
        return -1
    elif not isItereate:
        return -2
    else:
        return tryDelete(nodes,_len)

Gnodes = []
def answer(li):
    Gnodes[:] = []
    for i in range(len(li)):
        Gnodes.append(Node(i))#[i] = Node(i)
    for i in range(len(li)):
        for j in range(len(li[i])):
            Gnodes[i].dict[j] = li[i][j]
    return pathPossible(Gnodes,len(Gnodes[0].dict))

def check(li,ans):
    x = answer(li)
    print(str(li) + " : " + str(ans) + " : " + str(x))

def main():
    check([[2,1],[2,0],[3,1],[1,0]],-1)
    check([[1,2],[1,1],[2,2]],1)
    check([[1,3,0],[1,0,2],[1,1,2],[3,3,3]],-1)

if __name__ == '__main__':
    main()


texts:
I have a section of code that repeats many lines and I am looking to refactor this code possibly so that a function can be used instead of the same lines of code each time. Below is the section of code and the repeating code occurs in each if statement

Traversal::Traversal(string source, bool isFileName)
 {
      using namespace XML_Parser;
      using std::endl;

      std::ostringstream ppd;
  if (isFileName)
  {
      string content, line;
      std::ifstream file(source);
      if (! file)
      {
          ppd << endl << "error opening file " << source;
          cRep = ppd.str();
          cSuc = false;
          return;
      }
      ppd << endl << " file " << source << " opened ";
      while (file.good())
      {
          getline(file, line);
          content += '\n';
          content += line;
      }
      ppd << endl << "file " << source << " read ";
      source = content;
  }
  if (! elementExists(source,"afcd"))
  {
      ppd << endl << "no afcd tag";
      cRep = ppd.str();
      cSuc = false;
      return;
  }
  if (! elementExists(source,"rteirl"))
  {
      ppd << endl << "no rteirl tag";
      cRep = ppd.str();
      cSuc = false;
      return;
  }

How would I go about making this cleaner?


texts:
Exercise 2.20

  The procedures +, *,
  and list take arbitrary numbers of
  arguments. One way to define such
  procedures is to use define with
  dotted-tail notation. In a procedure
  definition, a parameter list that has
  a dot before the last parameter name
  indicates that, when the procedure is
  called, the initial parameters (if
  any) will have as values the initial
  arguments, as usual, but the final
  parameter's value will be a list of
  any remaining arguments.

  For instance, given the definition

(define (f x y . z) <body>)

  the procedure f can be called with two
  or more arguments. If we evaluate

(f 1 2 3 4 5 6)

  then in the body of f, x will be 1, y
  will be 2, and z will be the list (3 4
  5 6). Given the definition

(define (g . w) <body>)

  the procedure g can be called with
  zero or more arguments. If we evaluate

(g 1 2 3 4 5 6)

  then in the body of g, w will be the
  list

(1 2 3 4 5 6)

  Use this notation to write a procedure
  same-parity that takes one or more
  integers and returns a list of all the
  arguments that have the same even-odd
  parity as the first argument. For
  example,

(same-parity 1 2 3 4 5 6 7)
(1 3 5 7)

(same-parity 2 3 4 5 6 7)
(2 4 6)

I wrote the following:

(define (same-parity n . l)
  (define (even? n) (= (remainder n 2) 0))
  (define (odd? n) (not (even? n)))
  (define (rec n . l)
    (define (include-and-go)
      (cons (car l) (apply rec (cons n (cdr l)))))
    (define (exclude-and-go)
      (apply rec (cons n (cdr l))))
    (if (null? l) null
        (if (or (and (even? (car l))
                     (even? n))
                (and (odd? (car l))
                     (odd? n)))
            (include-and-go)
            (exclude-and-go))))
  (cons n (apply rec (cons n l))))

Is there a better way?


texts: Print the list of winter bash 2014 hats as a list of checkboxes in GFM format

texts:
In Winter Bash 2014,
since there is no easy way to see the hats I'm missing per site,
I decided to use Gists for that.
A perhaps not so well-known feature of GitHub Flavered Markdown (GFM) format used everywhere on GitHub is that if you write bullet point lists with embedded [ ] like this:

- [ ] Bill Lumbergh: answer 5 questions on Saturday (UTC)
- [ ] On The Road: ask using the app
- [ ] Bugdroid: use the Android app
- [ ] Not a cherry: use the iOS app
- [ ] I Voted Today: vote limit and 10+ questions

These will be rendered not as regular bullet point lists but a list of checkboxes:
clicking on an item will toggle the checkbox, triggering a commit.

Just one little problem:
there's no obviously easy way to copy-paste the hat names and descriptions from the Winter Bash website.
So I cooked up this simple soup (pun totally intended) using Python's Beautiful Soup:

#!/usr/bin/env python

from urllib import request

from bs4 import BeautifulSoup
import os

URL = 'http://winterbash2014.stackexchange.com/'

def load_html_doc(url):
    cached_file = 'page.html'
    if os.path.isfile(cached_file) and os.path.getsize(cached_file):
        with open(cached_file) as fh:
            html_doc = fh.read()
    else:
        html_doc = request.urlopen(url).read()
        with open(cached_file, 'wb') as fh:
            fh.write(html_doc)
    return html_doc

def get_soup(url):
    html_doc = load_html_doc(url)
    return BeautifulSoup(html_doc)

def print_hats_as_gfm_checkboxes(soup):
    for box in soup.find_all('a', attrs={'class': 'box'}):
        name = box.find(attrs={'class': 'hat-name'}).text
        description = box.find(attrs={'class': 'hat-description'}).text
        print('- [ ] {}: {}'.format(name, description))

def print_pretty(soup):
    print(soup.prettify())

def main():
    soup = get_soup(URL)
    print_hats_as_gfm_checkboxes(soup)
    # print_pretty(soup)

if __name__ == '__main__':
    main()

This produces a list of all the hats in the right format to be suitable for copy-pasting into a Gist.

Anything to improve here?


texts:
I wrote a simple shared pointer, which I think works pretty well. I would like to see your review of it.

This is the header file:

#pragma once

#include <algorithm>

template <class T>
class SharedPointer
{
private:
    T* ptr;
    int* counter;

    void swapp(SharedPointer& first, SharedPointer& second);

public:
    SharedPointer(void);
    SharedPointer(T* val);
    SharedPointer(const SharedPointer& sp);

    T& operator*();
    T* operator->();
    SharedPointer& operator=(const SharedPointer& sp);
    ~SharedPointer(void);
};

template <class T>
void SharedPointer<T>::swapp(SharedPointer& first, SharedPointer& second)
{
    using std::swap;

    swap(first.ptr, second.ptr);
    swap(first.counter, second.counter);
}

template <class T>
SharedPointer<T>::SharedPointer(void)
{
    ptr = new T;
    counter = new int;
    *counter = 1;
}

template <class T>
SharedPointer<T>::SharedPointer(T* val) : ptr(val)
{
    counter = new int;
    *counter = 1;
}

template <class T>
SharedPointer<T>::SharedPointer(const SharedPointer& sp)
{
    ptr = sp.ptr;
    counter = sp.counter;
    ++(*counter);
}

template <typename T>
T& SharedPointer<T>::operator*()
{
    return *ptr;
}

template <typename T>
T* SharedPointer<T>::operator->()
{
    return ptr;
}

template <class T>
SharedPointer<T>& SharedPointer<T>::operator=(const SharedPointer& sp)
{
    SharedPointer temp(sp);
    swapp(*this,temp);

    return *this;
}

template <class T>
SharedPointer<T>::~SharedPointer(void)
{
    if(--(*counter) == 0)
    {
        delete ptr;
        delete counter;
    }
}


texts: Combine lists of objects with no duplicates

texts:
I have 2 groovy sql resultset, I need to combine the result set so that project_no should be unique and case_no can have multiple elements if there is a duplicate project_no

Below are the 2 groovy sql resultset

[[project_no:0-10001,case_no:00492268],[project_no:0-10160,case_no:01957580],[project_no:1-10014,case_no:02022686]]

[[project_no:0-10160,case_no:01957590],[project_no:1-10014,case_no:019126],[project_no:1-2896337,case_no:02039596]]

Desired List

[[project_no:0-10001,case_nos:[00492268]], [project_no:0-10160,case_nos:[01957580,01957590]] ,[project_no:1-10014,case_nos:[02022686,019126]], [project_no:1-2896337,case_nos:[02039596]]]

This is what I have tried

caseResultForAnalysis.each { ca ->
    def ptmp = [:], caseList = []
    tempPrList.add(ca["project_no"])
    ptmp["project_no"] = ca["project_no"]
    caseList.add(ca["case_no"])
    if (caseList.size() > 0) {
        ptmp["case_nos"] = caseList
        mergedCaseResult.push(ptmp)
    }
}
mergedCaseResult.each { ma ->
    def ptmp = [:], caseList = []
    caseResultForUploads.each { cp ->
        if (!tempPrList.contains(cp["project_no"])) {
            ptmp["project_no"] = ma["project_no"]
            caseList.add(cp["case_no"])
        } else if (ma["project_no"] == cp["project_no"]) {
            //if (!ma["case_nos"].contains(cp["case_no"]))
            List tmp = ma["case_nos"]
            if (!tmp.contains(cp["case_no"]))
                ma["case_nos"].add(cp["case_no"])
        }
    }
    if (caseList.size() > 0) {
        ptmp["case_nos"] = caseList
        mergedCaseResult.push(ptmp)
    }
}

//1st list caseResultForAnalysis
//2nd List caseResultForUploads
//desired List mergedCaseResult

Is there a better way to do this, for better readability and less resource consumption?


texts:
Is this the right way to use async/await with the JavaScript MySQL client? I had to use the promise-mysql package because it wraps the function calls with Bluebird promises, so that I'm able to use async/await.

const express = require('express');
const mysql = require('promise-mysql');

let app = express();

let pool = mysql.createPool({
    host: '',
    user: '',
    password: '',
    database: ''
});

app.get('/', async (req, res) => {
    try {
        let conn = await pool.getConnection();
        let results = await conn.query('SELECT 1 + 1');
        res.send(results[0]);
    } catch (err) {
        return res.send(err);
    }
});

app.listen(3000, () => {
    console.log('server is listening on port 3000');
});


texts: Periodically monitor if record is not updated using Node, Event and setTimeOut

texts:
Here is my scenario:

Every user checks in every five minutes.
If some user doesn't check in after 5 minutes, I should be able to keep track of it.
If some user doesn't check in N number of times, an alert should be generated , like send email or SMS.

Here is what I have implemented so far:

var Report = function(attendence) {
  this.attendence = attendence;
  EventEmitter.call(this);
};

util.inherits(Report, EventEmitter);

Report.prototype.addAPSStatsData = function() {

  var attendenceDB = new Report(this.attendence);

  //Promise
  var prSave = attendenceDB.save();
  var self = this;
  prSave.then(function(data) {

    //emitting event that data has been saved
    self.emit('attendenceRecieved', data.userName);

    var saveTime = Date.now();
    self.moniterAPSStatsData(data.userName, saveTime);

  }).catch(function(err) {
    self.emit('error', err);
  });
};

Report.prototype.moniterAPSStatsData = function(userName, time) {

  var cacheKey = appConfig.CACHE_KEY_UserTimeInterval + userName;
  var prevTimer = memoryCache.get(cacheKey);

  if(!prevTimer)
    clearTimeout(prevTimer);

  var timer = setTimeout(this.moniterCallBackAfterInterval, (5 * 60000), userName, time ,cacheKey);

  //Putting timout in cache so later on it can be clearedout if the new attendence comes in
  memoryCache.set(cacheKey, timer);

};

Report.prototype.moniterCallBackAfterInterval = function(userName, time ,cacheKey) {
  //Removing from cache
  memoryCache.del(cacheKey);

  //Emitting event so email can be send out
  this.emit('ReportNotRecieved_SENDEMAIL');
};

Do you think this is a good approach?
Will it hold in a production environment?
Are there any alternatives to setTimeOut which can be used here?


texts:
Many of the variables in my 2D mining game were declared as constants like so:

DWConstants.h

static const int kBlockSpriteWidth = 64;
static const float kBufferFactor = 2.5;
static const int kMaxBlockDamage = 3;

This was all well and good for initial testing, but I soon found out that there were quite a few variables that I wanted to be able to adjust based on what device the game was running on.  I thought about a couple approaches to this, and I decided on this one.  The values of the variables are set based on the memory of the device.  I would love to know what you think.

DWMemoryConstants.h

#import <Foundation/Foundation.h>

@interface DWMemoryConstants : NSObject

@property int startingChunks;
@property int chunkSize;
@property int chunksToGenerate;
@property float maxZoom;

@end

DWMemoryConstants.m

#import "DWMemoryConstants.h"

@implementation DWMemoryConstants

-(instancetype) init {
    self = [super init];
    if (self) {

        unsigned long long memorySize = [NSProcessInfo processInfo].physicalMemory;
        unsigned long long memSize = memorySize/1000/1000;

        if (memSize < 256) {
            _startingChunks = 0;
            _chunkSize = 0;
            _chunksToGenerate = 0;
            _maxZoom = 0.00;
        } else if (memSize >= 256 && memSize < 800) {
            //ipod 5 is in this range
            _startingChunks = 8;
            _chunkSize = 16;
            _chunksToGenerate = 4;
            _maxZoom = 0.45;
        } else if (memSize >= 800 && memSize < 1800) {
            //ipad 4 will fall in this range
            _startingChunks = 10;
            _chunkSize = 18;
            _chunksToGenerate = 6;
            _maxZoom = 0.25;
        } else if (memSize >= 1800 && memSize < 2800) {
            //previous typical settings
            _startingChunks = 10;
            _chunkSize = 24;
            _chunksToGenerate = 8;
            _maxZoom = 0.05;
        } else if (memSize >= 2800) {
            _startingChunks = 12;
            _chunkSize = 30;
            _chunksToGenerate = 10;
            _maxZoom = 0.04;
        }
    }
    return self;
}

@end

As always, I am open to any sort of feedback about the code.


texts: what is the correct way to write an endpoint?

texts:
Here is a rather large endpoint that I have written in Python using Flask and SQLAlchemy, I was wondering if there are any tips I could get.

The endpoint takes a post request which contains specific user information and then passes some of that information to a function that calculates a percent and then it places the information into a database.

@app.route('/api/pineapple/create_investment', methods=['POST'])
@cross_origin()
def create_investment():
    auth_token = request.headers['Authorization']
    bearer, _, token = auth_token.partition(' ')
    if bearer != 'Bearer':
        raise ValueError('Invalid Access Token')
    else:

        percentage_of_fund = equity_calculator(request.json['amount_invested'],
                                               request.json['size_of_fund'],
                                               request.json['total_equity_offered'])

        new_investment = Investment(user_id=request.json['email'],
                                    company_name=request.json['company_name'],
                                    company_id=request.json['company_id'],
                                    amount_invested=request.json['amount_invested'],
                                    percentage_of_fund=percentage_of_fund)

        db.session.add(new_investment)
        investment_schema = InvestmentSchema()
        try:
            db.session.commit()
            return investment_schema.dump(new_investment), 200
        except exc.SQLAlchemyError as e:
            return jsonify(error=502, text=str(e))