texts: Making a string by reading down a matrix

texts:
Suppose I have a string with a length always a multiple of four:

'CodeReviewSE'

My goal is to create a permutation. First, I arrange the string into a matrix (where each row has a length of 4):

    C  o  d  e
    R  e  v  i
    e  w  S  E

And then I simply read down, starting from the top-left corner. I get four segments: CRe, oew, dvs and eiE. I concatenate them, to get the following string:

'CReoewdvSeiE'

Reversing the operation is just reversing the steps, kinda. It follows the same steps, except for row length are len(text) / 4, and we read down again, to look like this:

    C  R  e
    o  e  w
    d  v  S
    e  i  E

I've implemented the following code in Python:

import collections

def permute(text):
    # type: (str) -> str

    rows = collections.deque()
    output = ''

    # Create matrix
    for i in xrange(0, len(text), 4):
        rows.append(text[i:i+4])

    # Read matrix downwards
    for counter in xrange(4):
        for row in rows:
            output += row[counter]

    return output

def unpermute(text):
    # type: (str) -> str

    rows = collections.deque()
    output = ''
    length = len(text) / 4

    # Create matrix
    for i in xrange(0, len(text), length):
        rows.append(text[i:i+length])

    # Now read downwards
    for counter in xrange(length):
        for row in rows:
            output += row[counter]

    return output

I also ran a performance tests using the timeit module, using random strings of different lengths (where n is the length):

n = 32                                    Best:       |       Avg
Permute: (10,000 loops, best of 10):     0.06563            0.07080
Unpermute: (10,000 loops, best of 10):   0.06337            0.06655

n = 64                                    Best:       |       Avg
Permute: (10,000 loops, best of 10):     0.11592            0.11939
Unpermute: (10,000 loops, best of 10):   0.10358            0.10530

n = 256                                   Best:       |       Avg
Permute: (10,000 loops, best of 10):     0.43404            0.44310
Unpermute: (10,000 loops, best of 10):   0.37202            0.38102

n = 1024                                  Best:       |       Avg
Permute: (10,000 loops, best of 10):     1.82779            1.85647
Unpermute: (10,000 loops, best of 10):   1.72195            1.78491


texts: Finding a common prefix/suffix in a list/tuple of strings

texts:
The question that sparked this question, was one on Stack Overflow in which the OP was looking for a way to find a common prefix among file names( a list of strings). While an answer was given that said to use something from the os library, I began to wonder how one might implement a common_prefix function.

I deiced to try my hand at finding out, and along with creating a common_prefix function, I also created a common_suffix function. After verifying that the functions worked, I deiced to go the extra mile; I documented my functions and made them into a package of sorts, as I'm sure they will come in handy later.

But before sealing up the package for good, I deiced I would try to make my code as "Pythonic" as possible, which lead me here.

I made sure to document my code heavily, so I feel confident that I shouldn't have to explain how the functions work, and how to use them:

from itertools import zip_longest

def all_same(items: (tuple, list, str)) -> bool:
    '''
    A helper function to test if
    all items in the given iterable
    are identical.

    Arguments:
    item -> the given iterable to be used

    eg.
    >>> all_same([1, 1, 1])
    True
    >>> all_same([1, 1, 2])
    False
    >>> all_same((1, 1, 1))
    True
    >> all_same((1, 1, 2))
    False
    >>> all_same("111")
    True
    >>> all_same("112")
    False
    '''
    return all(item == items[0] for item in items)

def common_prefix(strings: (list, tuple), _min: int=0, _max: int=100) -> str:
    '''
    Given a list or tuple of strings, find the common prefix
    among them. If a common prefix is not found, an empty string
    will be returned.

    Arguments:
    strings -> the string list or tuple to
    be used.

    _min, _max - > If a common prefix is  found,
    Its length will be tested against the range _min
    and _max. If its length is not in the range, and
    empty string will be returned, otherwise the prefix
    is returned

    eg.
    >>> common_prefix(['hello', 'hemp', 'he'])
    'he'
    >>> common_prefix(('foobar', 'foobaz', 'foobam'))
    'foo'
    >>> common_prefix(['foobar', 'foobaz', 'doobam'])
    ''
    '''
    prefix = ""
    for tup in zip_longest(*strings):
        if all_same(tup):
            prefix += tup[0]
        else:
            if _min <= len(prefix) <= _max:
                return prefix
            else:
                return ''

def common_suffix(strings: (list, tuple), _min: int=0, _max: int=100) -> str:
    '''
    Given a list or tuple of strings, find the common suffix
    among them. If a common suffix is not found, an empty string
    will be returned.

    Arguments:
    strings -> the string list or tuple to
    be used.

    _min, _max - > If a common suffix is  found,
    Its length will be tested against the range _min
    and _max. If its length is not in the range, and
    empty string will be returned, otherwise the suffix
    is returned

    eg.
    >>> common_suffix([rhyme', 'time', 'mime'])
    'me'
    >>> common_suffix(('boo', 'foo', 'goo'))
    'oo'
    >>> common_suffix(['boo', 'foo', 'goz'])
    ''
    '''
    suffix = ""
    strings = [string[::-1] for string in strings]
    for tup in zip_longest(*strings):
        if all_same(tup):
            suffix += tup[0]
        else:
            if _min <= len(suffix) <= _max:
                return suffix[::-1]
            else:
                return ''


texts: Resize renderer on browser window size change

texts:
For a game, there is some WebGLRenderer object that wraps around canvas element. There is need to update it's size when browser window size changes. Here goes my current code written using BaconJS. What do you think about it ? Would you improve it in any way or maybe do it other way? I have read that listening to resize event is just slow for game purposes.

# Make the property of window object
rWindow = Bacon.constant window

# Sample window by tick event
sTickWindow = rWindow.sampledBy app.land.stream('tick')

# Look for width and height changes on every tick
sWidth = sTickWindow.map('.innerWidth').skipDuplicates()
sHeight = sTickWindow.map('.innerHeight').skipDuplicates()
sSize = Bacon.combineAsArray sWidth, sHeight

# Resize renderer when size is changed
Bacon.onValues rRenderer, sSize, (renderer, size) ->
    # Apply size update to renderer
    renderer.setSize size...

Note that app.land.stream('tick') is basically EventStream of requestAnimationFrame invocations.

Update

To make the understanding easier, I have made fiddle for it. Open dev console and try to resize the Result window rather then browser window.


texts:
https://leetcode.com/problems/delete-and-earn/

Given an array nums of integers, you can perform operations on the
array.
In each operation, you pick any nums[i] and delete it to earn nums[i]
points. After, you must delete every element equal to nums[i] - 1 or
nums[i] + 1.
You start with 0 points. Return the maximum number of points you can
earn by applying such operations.
Example 1:
Input: nums = [3,4,2] Output: 6 Explanation: Delete 4 to earn 4
points, consequently 3 is also deleted. Then, delete 2 to earn 2
points. 6 total points are earned. Example 2:
Input: nums = [2,2,3,3,3,4] Output: 9 Explanation: Delete 3 to earn 3
points, deleting both 2's and the 4. Then, delete 3 again to earn 3
points, and 3 again to earn 3 points. 9 total points are earned.
Constraints:
1 <= nums.length <= 2 * 10^4
1 <= nums[i] <= 10^4

please review for performance, I know I am copying the dictionary over and over again.
Leetcode offers a solution based on range of numbers array[10001]. I don't like that solution (counting sort). my head usually sees this is a dictionary.. but I think there is room for optimizations.
Thanks
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DynamicProgrammingQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/delete-and-earn/
    /// </summary>
    [TestClass]
    public class DeleteAndEarnTest
    {

        [TestMethod]
        public void TestMethod1()
        {
            int[] nums = {3, 4, 2};
            Assert.AreEqual(6, DeleteAndEarn(nums));
            Assert.AreEqual(6, DeleteAndEarn2(nums));
        }

        [TestMethod]
        public void TestMethod2()
        {
            int[] nums = { 2, 2, 3, 3, 3, 4 };
            Assert.AreEqual(9, DeleteAndEarn(nums));
            Assert.AreEqual(9, DeleteAndEarn2(nums));
        }

        [TestMethod]
        public void FailedTestMethod()
        {
            int[] nums = { 1,1,1,2,4,5,5,5,6 };
            Assert.AreEqual(18, DeleteAndEarn(nums));
            Assert.AreEqual(18, DeleteAndEarn2(nums));
        }

        [TestMethod]
        public void FailedTestMethod2()
        {
            int[] nums = { 3,1 };
            Assert.AreEqual(4, DeleteAndEarn(nums));
            Assert.AreEqual(4, DeleteAndEarn2(nums));
        }

        public int DeleteAndEarn(int[] nums)
        {
            if (nums == null || nums.Length == 0)
            {
                return 0;
            }

            var dict = new Dictionary<int, int>();
            foreach (var curr in nums)
            {
                if (!dict.ContainsKey(curr))
                {
                    dict.Add(curr, 1);
                }
                else
                {
                    dict[curr]++;
                }
            }

            int max = 0;
            foreach (var key in dict.Keys)
            {
                max = Math.Max(max, Helper(key, new Dictionary<int, int>(dict)));
            }
            return max;
        }

        private int Helper(int key, Dictionary<int, int> dict)
        {
            int max = key * dict[key];
            dict.Remove(key);
            if (dict.ContainsKey(key + 1))
            {
                dict.Remove(key + 1);
            }
            if (dict.ContainsKey(key - 1))
            {
                dict.Remove(key - 1);
            }

            int temp = 0;
            foreach (var curr in dict.Keys.ToList())
            {
                temp = Math.Max(temp,Helper(curr, new Dictionary<int, int>(dict)));
            }
            return max + temp;
        }
    }
}


texts: Add two digit strings and return the result as string

texts:
I haven't done C in a while.
This looks like a simple problem to start.

Leetcode problem 415

  Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
  …
  Note: [1. … 2. … 3. … ] 4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

It is working but I would like the comment on the style and being proper C code.

char * addStrings(char * num1, char * num2){
    int len1 = strlen(num1);
    int len2 = strlen(num2);

    int result_len = len1 > len2? len1: len2;
    result_len += 1;

    char *result = malloc(result_len+1);

    char *p1 = num1 + len1-1;
    char *p2 = num2 + len2-1;

    char *rp = result + result_len;

    *rp = '\0';
    rp--;

    int carry = 0;
    char zero='0';
    int digit;
    int d1;
    int d2;

    while (len1 || len2) {
        if (len1) {
            d1 = (*p1)-zero;
            p1--;
            len1--;
        }
        if (len2) {
            d2 = (*p2)-zero;
            p2--;
            len2--;
        }
        int tmp = d1 + d2 + carry;
        digit = tmp % 10;
        carry = tmp / 10;
        *rp = digit+zero;
        rp--;
        d1 = 0;
        d2 = 0;
    }

    if (carry) {
        *rp = carry+zero;
    } else {
        rp++;
    }
    return rp;
}


texts: Write int, short int or any integer value in a file in binary form using fputc

texts:
I am trying to write binary values in a file using fputc. In my case it is a short int.
The file must be opened in "w" mode.

I'm using this function, which is working. I need to know if I'm doing it right or if there are cases that I hadn't anticipated.

void writeListPos(Compressor* comp, short int listPos){
    ++listPos;
    char* posChar = (char*)(&listPos);
    int i;
    for(i=0 ; i<(sizeof(short int)) ; ++i){
        fputc(posChar[i] , comp->outputFile);
    }
}

The function to read the file later:

short int readListPos(Compressor* comp){
    char* posChar = (char*)(malloc(sizeof(short int)));
    int i;
    for(i=0 ; i<sizeof(short int) ; ++i){
        posChar[i] = comp->lastRead;/* comp->lastRead initialised with a first fgetc*/
        comp->lastRead = fgetc(comp->inputFile);
    }
    short int* positionp = (short int*)posChar;
    short int position = (*positionp);
    free(posChar);
    --position;
    return position;
}


texts: Matrix Multiplication Python -- Memory Hungry

texts:
Here is a snippet from my python script where I am performing:

a dictionary lookup
a cartesian multiplication of a list of len=500 against a list of len=60,
calculating a cumulative addition for each multiplcation combination
repeat this down a 20,000 rows

This is slowing things way down and making it hard to debug with the ~10 min wait times.  How can I write this in a more efficient way, and that makes use of more than just one CPU?

ccle_head, dot_prod_total = [], []
with open(ccle_mRNA_file, mode='r') as ccle:
    for _ in range(2): #skip to data
        next(ccle)
    exp_mat = [line.rstrip().split('\t') for line in ccle]
for row in exp_mat:
    if row[0] != 'Name' and row[1] in pat_mRNA: # data row
        n_row = [float(s) for s in row[2:]]
        # get ready for some slow matrix multiplication:
        prod = [p*n for n in n_row for p in pat_mRNA[row[1]]] # slows here
        if dot_prod_total:
            dot_prod_total = [cum_prod + prod for (cum_prod,prod)
                        in zip(dot_prod_total,prod)] # cumulative addition
        else: dot_prod_total = prod  # first record of matrix products
     else: ccle_exp_head = row   # header row

Here are the docs for the input params:

"""
:param ccle_mRNA_file: text file, rows are gene expression across sample columns
:param pat_head: list, patient id [pat_1(str), pat_2...]
:param pat_mRNA: dict, patient RNA {gene(str):[pat_1(float), pat_2..}
:param cell_interest: set, cells of same tissue {cell_1, cell_2}
"""


texts:
I have several UI elements that can be opened using hotkeys for example the settings menu's key is Escape. The problem is that I have the Keycode stored in Dictionary along with an Action or a Button.ButtonClickedEvent here's how the two dictionaries are declared:

    public static readonly Dictionary<KeyCode, Button.ButtonClickedEvent> KeysUIElementsWithButtonEvents = new Dictionary<KeyCode, Button.ButtonClickedEvent>
    {
        { KeyCode.P, SpellbookButton.onClick },
        { KeyCode.Escape, SettingsMenuButton.onClick },
    };

    public static readonly Dictionary<KeyCode, Action> KeysUIElementsWithActions = new Dictionary<KeyCode, Action>
    {
        { KeyCode.LeftAlt, SwitchCursorState},
    };

And here's how I used to invoke them :

        foreach (var item in Settings.Settings.KeysUIElementsWithButtonEvents)
        {
            if(Input.GetKeyDown(item.Key))
            {
                if(Cursor.lockState == CursorLockMode.Locked)
                {
                    Settings.Settings.SwitchCursorState();
                }
                item.Value.Invoke();
            }
        }

        foreach (var item in Settings.Settings.KeysUIElementsWithActions)
        {
            if (Input.GetKeyDown(item.Key))
            {
                if (Cursor.lockState == CursorLockMode.Locked)
                {
                    Settings.Settings.SwitchCursorState();
                }
                item.Value.Invoke();
            }
        }

I didn't like the repetitive code in here so I decided to create a function which solves the problem:

    CheckUIKeysCollection(Settings.Settings.KeysUIElementsWithButtonEvents);
    CheckUIKeysCollection(Settings.Settings.KeysUIElementsWithActions);

    private void CheckUIKeysCollection<T>(Dictionary<KeyCode, T> collection)
    {
        foreach (var item in collection)
        {
            if (Input.GetKeyDown(item.Key))
            {
                if (Cursor.lockState == CursorLockMode.Locked)
                {
                    Settings.Settings.SwitchCursorState();
                }
                if (item.Value is Action)
                {
                    (item.Value as Action).Invoke();
                    continue;
                }
                (item.Value as Button.ButtonClickedEvent).Invoke();
            }
        }
    }

However I'm not sure if the method is efficient enough it involves some casting here and there and it's also being called in the Update function (every frame) and if I have big collections it might hurt the performance. What can I do to improve the method?


texts:
I'm going to post some of my solutions to common interview questions. I would love it if you could critique me from a C++ purist's standpoint. Also, tell me if there's a better algorithm for each one of these.

Find the mode (most common element) of an array.

Note: My solution returns an arbitrary mode if there's a tie; assumes the array is non-empty, too

int mode(int* arr, int sz) {
    std::map<int,int> cntMap;
    int most = arr[0];
    for (int i = 0; i < sz; i++) {
       if (!cntMap.count(arr[i])) {
          cntMap[arr[i]] = 0;
       } else {
          cntMap[arr[i]]++;
       }
       if (cntMap[arr[i]] > most) {
          most = cntMap[arr[i]];
       }
    }
    return most;
}

Sum the largest 2 largest elements of an array.

Note: Assumes the array contains at least 2 elements

int largest2(int* arr, int sz) {
    int largest(arr[0]), secondLargest[arr[0]];
    for (int i = 0; i < sz; i++) {
       if (arr[i] > largest) {
          secondLargest = largest;
          largest = arr[i];

       } else if (arr[i] > secondLargest && arr[i] <= largest) {
          secondLargest = arr[i];
       }
    }
    return (largest + secondLargest);
}

Find whether an array as repeated elements, where it's known that the numbers of the array are between 1 and 100.

bool contains_repeats(int* arr, int sz) {
    std::vector<bool> booVec(100,false);
    for (int i = 0; i < sz; i++) {
       if (booVec[arr[i]-1]) {
           return true;
       } else {
           booVec[arr[i]-1] = true;
       }
    }
    return false;
}


texts: Organizing JavaScript code for a website

texts:
I'm in the process of building a website for the company I work for and I'm trying to think of the best way to namespace and organize the site's JavaScript code.

I've written several jQuery/JavaScript plugins for the big chunks of code, but now I'd like a namespaced place to "call" said plugins and any other random JavaScript that's needed throughout the site.

I'm considering using a singleton (NAMESPACE.js):

// http://stackoverflow.com/a/1479341/922323
var NAMESPACE = (function() {

    //var privateVar = '';

    function weather() {

        var $weather = $('#weather');

        if ($weather.length) {

            // Do jQuery stuff with $weather here.

        }

    } // weather()

    function navigation() {

        var $baz = $('#baz'),
        $html = $('html');

        $baz
            .myOtherPlugin({
                cloneRemove : 'li > div',
                cloneId     : false
            })
            .anotherPlugin({
                eventType      : 'hoverIntent',
                onStartOutside : function() {
                    $html.addClass('mw-outside');
                },
                onEndOutside   : function() {
                    $html.removeClass('mw-outside');
                }
            });

    } // navigation()

    function footer() {

        $('footer ul').myPlugin({
            //openTab : true,
            currentPage : true
        });

    } // footer()

    return {

        init : function() {

            weather();

            navigation();

            footer();

            // Add more here as project grows...

        } // init()

    };

})();

HTML would look like so (in foot of document):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="plugins.js"></script>
<script src="NAMESPACE.js"></script>

<script type="text/javascript">
    <!--

        $(document).ready(function() {

            NAMESPACE.init();

        });

    //-->
</script>

Question(s):

Do you see anything out of the ordianary with my (pseudo) code above?
Am I headed in the right direction? If not, could you suggest an alternative?
Am I over-complicating things?
I really like how Yahoo! does: YAHOO.namespace("myProject"); YAHOO.myProject.myModule = function () { ... } ... it seems like if I did something similar, that would allow me to easily add/remove "modules" on a "per page" basis. Would anyone recommend this approach? If so, how could I modify my example to mimic YUI's functionality (I'm going to research YUI's namespace() code and post back my results if I figure it out).


texts: Disposing SQL objects inside another using block

texts:
In one sql connection I have multiple sql commands and I wonder what approach is better - create and dispose SqlCommand for each operation or use only one sql command?

Eg:

using (SqlConnection connection = new SqlConnection(ConnectionString))
{
   connection.Open();

   using(SqlCommand cmd = new SqlCommand("select...", connection))
   {
       cmd.ExecuteNonQuery();

       cmd.CommandText = @"another query...";
       cmd.ExecuteNonQuery();

       //and so on
   }
}

or

using (SqlConnection connection = new SqlConnection(ConnectionString))
{
   connection.Open();

   using(SqlCommand cmd = new SqlCommand("select...", connection))
   {
       cmd.ExecuteNonQuery();
   }

   using(SqlCommand cmd = new SqlCommand("another query...", connection))
   {
       cmd.ExecuteNonQuery();
   }
}

If SqlCommand(s) are inside another using block (in this cae SqlConnection), disposing will be done after close connection or immediately after running SqlCommand?

I'm asking because I have web api which receives a few hundred requests per minute and my goal is to optimize application for better garbage collector working - there might be memory leak


texts: Basic one way hash to store a password C#

texts:
I am storing a password in a database (school coursework so nothing too complicated but I want to challenge myself), I am using a one way hash function, is this suitable? It works I just feel there may be nicer ways of storing the password. The database is SQL, language is C#

static class Encryption
{
    public static string OneWayEncrpyt(string toEncrypt)
    {
        byte[] data = System.Text.Encoding.ASCII.GetBytes("password");
        data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
        return System.Text.Encoding.ASCII.GetString(data);
    }
}


texts:
I've made my first-ever program in Go, which sorts a given input of integers. There are 2 options: The list of unsorted integers and the algorithm to use.

Since it's my first go project I'm a bit unsure of a few things. For example, the "floating" variable declarations.

I think that the algorithms itself are okay, therefore I only post the executable program:

package main

import (
    "fmt"
    "flag"
    "strings"
    "strconv"
    "os"
    "github.com/afroewis/go-sorting-algorithms/sortalgos"
)

func main() {
    inputFlag := flag.String("input", "", "Input numbers to sort. Example: 10 20 5 1003 94 928")
    algoFlag := flag.String("algo", "", "Sorting algo to use. Available values: bubble, selection, insertion. ")
    flag.Parse()

    // Parse input
    input := strings.Split(*inputFlag, " ")
    var numbers [] int

    for i := 0; i < len(input); i++ {
        val, err := strconv.Atoi(input[i])

        if err != nil {
            panic(err)
        }

        numbers = append(numbers, val)
    }

    var result []int;

    switch *algoFlag {
    case "bubble":
        result = sortalgos.BubbleSort(numbers)
    case "selection":
        result = sortalgos.SelectionSort(numbers)
    case "insertion":
        result = sortalgos.InsertionSort(numbers)
    case "":
        fmt.Println("Error: -algo flag not set. For usage infos use ./main -help")
        os.Exit(1)
    }

    fmt.Println(result)
}


texts: Opening an XML File and Returning the XmlDocument

texts:
I'm working on my first Windows Forms tool for a project; this is my first time using C# extensively. Right now, my only objective is to be able to open an XML file and have the resulting XML in hand. I know this works, but I want to know if there's a better, or proper, way to do it.

There is also the issue that when I was first trying to load it, it didn't like the fact that I was using if statements, so the return class was giving me an error that said that not all of the branches returned a value.  So, I had to throw in a messy else statement that I don't like.

One thing to note; if the empty XML file is returned, I'll have a statement for handling the returned XML document to do nothing with it.

class LoadXML
{
    public XmlDocument LoadXML_Window(object sender, System.EventArgs e)
    {
        //  The stream will hold the results of opening the XML
        Stream myStream = null;
        OpenFileDialog openFileDialogXML = new OpenFileDialog();

        openFileDialogXML.InitialDirectory = "C:\\";
        openFileDialogXML.Filter = "XML Files|*.xml";
        openFileDialogXML.RestoreDirectory = true;

        if(openFileDialogXML.ShowDialog() == true)
        {
            myStream = openFileDialogXML.OpenFile();
            using (myStream)
            {
                try
                {
                    //  Successfully return the XML
                    XmlDocument parsedMyStream = new XmlDocument();
                    parsedMyStream.Load(myStream);
                    return parsedMyStream;
                }
                catch (XmlException ex)
                {
                    MessageBox.Show("The XML could not be read. " + ex);
                    XmlDocument emptyMyStream = new XmlDocument();
                    return emptyMyStream;
                }
            }
        }
        else
        {
            //  Return an empty XmlDocument if the open file window was closed
            XmlDocument emptyMyStream = new XmlDocument();
            return emptyMyStream;
        }
    }
}


texts: Class to construct paths based on the path to the current class file

texts:
I have written a class that locates relative root project directory path from where I'm calling that class.

E.g. I have structure:

rootProjectDir
 |_sub
 |__subsub
 |___subsubfile.txt
 |_another_sub
 |__another_sub_file.py

and what I'm doing is when I'm working within another_sub_file.py I'm calling my class GetRootPath to get /home/user/dev/rootProjectDir and then I can construct the path to the ./rootProjectDir/sub/subsub/subsubfile.txt to get that subsubfile.txt. I didn't found any better solution... I hope there is, but I wrote class helper for me to achieve this:

import os

class GetRootPath:
    def __init__(self):
        self.rootFolder = '/rootProjectDir'

    def get_root(self):
        working_file_dir = os.path.dirname(os.path.abspath(__file__))

        i = len(working_file_dir.split('/'))
        root = list(working_file_dir.split('/'))
        new_root = []

        for item in root[1:]:
            new_root.append('/' + str(item))

        while True:
            if self.rootFolder == new_root[-1]:
                builded = ''.join(new_root) + '/'
                return builded
            else:
                new_root.pop()
            i -= 1

Is there any better way to achieve my goal and also, what could be done better with my class to improve performance and stability of creating relative path to root directory of my project. Or is there a better Pythonic way of navigating your project folder to get files and etc as you need? Because my GetRootPath class looks kind of Non-Pythonic way of doing this.

p.s. I'm working in PyCharm and my project is created with it, so it's not just folders... I guess. :}


texts:
Here is a recursive function that I wrote to search a file-system to a child depth defined by $depth.

Could it be optimized more?

function stringSearch($working_dir,&$results_array,$depth)
{
    global $search_string;
    global $dir_count;
    global $file_count;
    global $working_url;
    global $max_depth;

    if($max_depth>=($depth+1))
    {
        $dir_array = glob($working_dir.'/*', GLOB_ONLYDIR);
        foreach($dir_array as $new_path)
        {
            stringSearch($new_path,$results_array,($depth+1));
            $dir_count++;
        }
    }

    $handle = opendir($working_dir);
    while ($file = readdir($handle))
    {
        if(is_file($working_dir.'/'.$file))
        {
            if(stripos(str_replace('_',' ',$file),$search_string))
                $results_array[] = array('file'=>$file,'path'=>$working_dir,'url'=>$working_url.str_replace($_SERVER["DOCUMENT_ROOT"],'',$working_dir));

            $file_count++;
        }
    }

    return;
}


texts:
I have a naming problem: lists with un-named elements.  I wish to get the names of the elements in the list, without going back upstream to where the list was created. An example is modelList below:

## naming problem
lmNms <- c( "mod1", "mod2", "mod3", "mod4", "mod5", "mod6")
lapply(lmNms,
       function(N) assign(N, lm(runif(10) ~ rnorm(10)), env = .GlobalEnv))
modelList <- list(mod1, mod2, mod3, mod4, mod5, mod6)

I have written the below function which takes the list and the environment as arguments (as well as an argument to return names only), looks for a matching object in the target environment, and then attaches that name to the element and returns the list.

nameListObjects <- function(LIST, ENV = NULL, NAMES.ONLY = FALSE) {
    if(is.null(ENV)) ENV <- .GlobalEnv
    for(i in seq_along(LIST)){
        # check the class of all objects in the target environment
        classMatches <- sapply(ls(ENV),
                               function(N) class(get(N)) == class(LIST[[i]]))
        # see which objects of matching class are all.equal to the subject
        TF <- sapply(names(classMatches[classMatches]),
                 function(N) is.logical(all.equal(LIST[[i]], get(N))))
        names(LIST)[i] <- names(classMatches[classMatches])[TF]
    }
    if(NAMES.ONLY) names(LIST) else LIST
}

R>nameListObjects(modelList, NAMES.ONLY=TRUE)
[1] "mod1" "mod2" "mod3" "mod4" "mod5" "mod6"

This took me to the edge of my R ability.

I'm interested in better ways to do this (i presume there are multiple better ways), problems with this approach, and any other comments.


texts: Efficiently matching IP addresses with a list of CIDRs

texts:
I am using Python3 to extract some information from a dictionary that contains 10k of CIDRs, but the running time is pretty long.

Here is my purpose: I have a dictionary of CIDRs (10000) and a list of IPs (5000), then I want to go through each IP in the list and check if it belongs to one CIDR in the dictionary.

Could you please give me some trick to reduce the running time?

#python 3:
import os
import ipaddress

Dict = {127.0.0.0/8 : ABC, 169.128.0.0/16 : DEF}
List = {127.0.0.1, 126.1.1.1, 169.2.2.2, 150.0.22.2}

for IP in List:
  for CIDR in Dict.keys():
    if ipaddress.ip_address(IP) in ipaddress.ip_network(CIDR):
      print(CIDR)
      break


texts:
I've been tinkering around with making a fancy clock on a Raspberry Pi B. This little application will sync the Pi's time with an NTP server, then display it using toilet so it's nice n' big & centered on a monitor. This was made for a GUI-less Pi, and I'm looking to hopefully make it more efficient. Right now the seconds aren't a uniform duration (the time.sleep(0.3) is there to even it out), and I'm sure it's because the Pi is struggling to keep up with my newbie code.

#!/usr/bin/env python
import subprocess
import sys
import os
import time
from datetime import datetime
import ntplib

NTP_MISS = 0

def display_clock():
    #Clock Positioning
    rows, columns = os.popen('stty size', 'r').read().split()
    h_pos = int(int(columns) / 6)
    v_pos = "\033[" + str(int(int(rows) / 6)) + ";0H"

    #Initialization
    check_ntp_time = time.time()
    os.system('setterm --cursor off -powersave off')
    subprocess.call("clear")

    #Meat & Potatoes
    try:
        while check_ntp_time + 86400 >= time.time():
            current_date = subprocess.check_output(["date", "+%r"]).strip().decode("utf-8")
            current_date = " " * h_pos + current_date
            sys.stdout.write(v_pos + subprocess.check_output(["toilet", "-w 200", current_date]).decode("utf-8"))
            sys.stdout.flush()
            time.sleep(0.3)
    except KeyboardInterrupt:
        print("Closing NTP Clock")
        os.system('setterm --cursor on -powersave on')
        subprocess.call("clear")
        print("Closed NTP Clock")
        exit()

    #Update time using NTP pool.
    get_ntp_time()

def get_ntp_time():
    call = ntplib.NTPClient()
    while True:
        try:
            #Try to connect to the NTP pool...
            response = call.request('pool.ntp.org')
            print("Time updated!")
            break
        except:
            NTP_MISS += 1
            if NTP_MISS >= 5:
                print("NTP server unavailable for too long! Terminating...")
                os.system('setterm --cursor on -powersave on')
                subprocess.call("clear")
                print("NTP Clock failed. Server unresponsive for too long.")
                exit()
            #Not a huge deal if we miss it, just continue displaying the clock.
            print("Could not connect to pool.")
            display_clock()
    #If we get a response, update the system time.
    t = datetime.fromtimestamp(response.tx_time)
    t = t.strftime('%Y-%m-%d %I:%M:%S %Z')
    set_string = "--set=" + t
    subprocess.call(["date", set_string])
    display_clock()

if __name__ == "__main__":
    display_clock()

I'd prefer to use the subprocess instead of os.system, but for some reason using subprocess with setterm returned a "command not found" error. So that's why I'm using os.system instead.

What all can I do to optimize & clean up this code?


texts: TypeScript implicit 'any' type with computed property key

texts:
(irrelevant code removed for demo purposes)

I am new to using TypeScript and I have this React component which has an object literal inside the component, which I'm then accessing using a computed property key. Everything works as expected but I was getting the following TS error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ keyword: string; hex: string; rgb: string; }'.
No index signature with a parameter of type 'string' was found on type '{ keyword: string; hex: string; rgb: string; }'.ts(7053)

I managed to get rid of the error by adding the : any to the formats object, though I think this is not the best solution?

interface Props {
  keyword: string;
  hex: string;
  rgb: string;
  copyFormat: string;
}

export default ({ keyword, hex, rgb, copyFormat }: Props) => {
  const formats: any = {
    keyword,
    hex: hex.toUpperCase(),
    rgb: `rgb(${rgb})`,
  };

  return <p>{formats[copyFormat]}</p>;
};


texts:
I've been getting to grips with some Monads in Haskell recently, and to get some practice I plucked a Mealy Machine out of thin air and decided to implement it using the State Monad (it's a simple machine and a simple implementation, don't worry).

The input is a string of characters from +, -, n, e.

+, "plus". Output a 1,
-, "minus". Output a -1.
n, "toggle negated". Until "toggled off", flip the sign of the output from + or -.
e, "toggle enabled". Until "toggled back on", output 0 from + or -.

The output is just a sequence of the same length as the input, containing 1, 0, and -1s as outputted by the DFA. In the code below, the output is actually the sum of this sequence, acting as a quick checksum. All states are accepting states.

For example, an input of +-n+-e+e+ would result in [1, -1, 0, -1, 1, 0, 0, 0, -1].

To unambiguously define the behaviour, here's a pretty messy state transition diagram:

If "posate" (as the opposite of negate) isn't a word already, it is now!
The transitions are labelled with the "english name", the symbol used to represent this transition, and the "output" from the machine. All states are accepting states, I left out the conventional double rings.

At last, the code:

import Control.Monad.Trans.State.Lazy
import Control.Monad (foldM)

data Input = Plus | Minus | ToggleNegate | ToggleEnabled
type Emission = Integer
type Accum = [Emission]
type Output = [Emission]
type Negated = Bool
type Enabled = Bool

toInput :: Char -> Input
toInput '+' = Plus
toInput '-' = Minus
toInput 'n' = ToggleNegate
toInput 'e' = ToggleEnabled
toInput  _  = error "Invalid input representation"

-- Determine new state of state machine along with transition emission
step :: (Negated, Enabled, Input) -> (Negated, Enabled, Emission)
step (n, e, ToggleNegate)  = (not n, e, 0)
step (n, e, ToggleEnabled) = (n, not e, 0)
step (n, False, i)         = (n, False, 0)
step (n, e, Plus)          = (n, e, if n then -1 else  1)
step (n, e, Minus)         = (n, e, if n then  1 else -1)

-- Helper function for "evaluate"'s foldM
mapEmissions :: Accum -> Input -> State (Negated, Enabled) Output
mapEmissions accum input = do
    (negated, enabled) <- get
    let (negated', enabled', emission) = step (negated, enabled, input)
    put (negated', enabled')
    return (accum ++ [emission])

-- Process an input string and return the result
-- (False, True) is the start state: (not negated, enabled)
evaluate :: [Input] -> Output
evaluate inputs = evalState (foldM mapEmissions [] inputs) (False, True)

-- Convenience function for output formatting
shouldEqual :: String -> Integer -> IO ()
shouldEqual input expected = do
    let actual = (sum . evaluate . map toInput) input
    putStrLn $ "Expected " ++ show expected ++ ", got " ++ show actual ++ ": " ++ input

main :: IO ()
main = do
    "+-n--n" `shouldEqual` 2
    "+e----e++" `shouldEqual` 3
    "-n++e++e--+-n++" `shouldEqual` 1

Code online here.

I'm happy to hear any and all critiques and advice, but in particular:

Am I using the State monad idiomatically? Can I write any bits of code more elegantly?
Is this an appropriate use for this monad? This isn't a particularly complex task, but I feel like it makes passing around the DFA's state simpler.

Thanks for taking the time to read, and Happy New Year!


texts: Implementation of Dijkstra's algorithm in C++

texts:
This is my implementation of Dijkstra's algorithm. Could you tell me what am I doing wrong and what should be fixed? I was not sure how to keep track of the shortest outgoing edge from a node and I store -1 if there weren't any edges found yet. I am not sure if it is okay.

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

#define MAX_LENGTH 10000

int dijkstra(vector<vector<int>> graph, int source, int target) {
    size_t number_of_nodes = graph.size();
    vector<int> visited;
    map<int, int> lengths_to_nodes; // keeps pairs of lengths like 0:0, 1:20, 2:40

    //fill with max lengths and set source as 0 eg. 0:0 1:10000, 2:10000...
    for (int i = 0; i < number_of_nodes; ++i) {
        lengths_to_nodes.insert(make_pair(i, MAX_LENGTH));
    }
    lengths_to_nodes[source] = 0;

    //set actual node we look path from
    int actual_node = source;

    while (visited.size() < number_of_nodes) {
        //keep track of the shortest path found from this node because it will be
        //the next one we will looking for path from
        //if there was no paths from this node then go back
        int the_shortest_found_now = -1;    /***  IS IT OKEY?  ***/
        int the_shortest_found_now_length = MAX_LENGTH;

        for (int actual_target = 0; actual_target < number_of_nodes; ++actual_target) {
            if (graph[actual_target][actual_node] > 0) {
                int new_length = graph[actual_target][actual_node] + lengths_to_nodes.find(actual_node)->second;
                if (lengths_to_nodes.find(actual_target)->second > new_length) {
                    lengths_to_nodes.find(actual_target)->second = new_length;
                }
                if (new_length < the_shortest_found_now_length) {
                    the_shortest_found_now_length = new_length;
                    the_shortest_found_now = actual_target;
                }
            }
        }
        if (the_shortest_found_now == -1) {
            //if there was no outgoing edges
            actual_node = *(visited.end() - 1);
            visited.erase(visited.end() - 1, visited.end());
        }
        else {
            actual_node = the_shortest_found_now;
            visited.push_back(the_shortest_found_now);
        }
    }
    return lengths_to_nodes.find(target)->second;
}

int main() {
    vector<vector<int>> graph =
            {{{0, 0, 0, 0, 0, 0, 20, 0,},
                     {20, 0, 0, 0, 50, 50, 0, 0,},
                     {0, 0, 0, 10, 0, 0, 0, 0,},
                     {80, 0, 10, 0, 0, 40, 0, 0,},
                     {0, 0, 0, 0, 0, 0, 0, 0,},
                     {0, 10, 10, 0, 30, 0, 0, 0,},
                     {90, 0, 0, 20, 0, 0, 0, 0,},
                     {0, 0, 20, 0, 0, 0, 0, 0,},
             }};

    cout << dijkstra(graph, 0, 7) << endl;

    return 0;
}


texts: String de-duplication using a custom string pool

texts:
First let me address why I'm not using the built-in string interning. My code is used in a utility that needs to free all of its memory once it's closed. Strings that are interned are not likely to be freed until the CLR is restarted. I can't create that situation since my utility is used on servers that primarily run .NET based services. (See this reference on CLR not releasing interned strings)

On to the question:

I have created a custom string pool in C#, implemented as an extension method in a static class that contains the actual "pool" in the form of a dictionary:

internal static Dictionary<string, string> StringPool = new Dictionary<string, string>();

internal static string Pool(this string value)
{
    if (!string.IsNullOrEmpty(value) && value.Length <= 200)
    {
        string poolRef;

        if (StringPool.TryGetValue(value, out poolRef))
            value = poolRef;
    else
        StringPool.Add(value, value);
}

return value;
}

To use it, I simply append .Pool() to any string in my project that I want to be pooled. The assumption I am making is that this approach is storing two copies of strings. My assumption comes from the fact that I can recover the actual strings by iterating the Keys in the StringPool object and printing or viewing their contents.

The question I have is whether anyone knows of another indexed object type that I could use as a StringPool object such that the string data would only be stored once, as the Key, rather than twice, as both Key and Value. Additionally I need the fast Key lookup feature that a Dictionary has.

Here's the pseudo code that I believe conveys what I'm after in practice:

internal static CoolClass<string> StringPool = new CoolClass<string>();

internal static string Pool(this string s)
{
    if (!string.IsNullOrEmpty(s) && s.Length <= 200)
    {
        string keyRef = null;

        // obtain reference to key in CoolClass if it already exists
        if (StringPool.TryGetKey(s, out keyRef))
            s = keyRef;
    else
        StringPool.AddKey(s);
}

return s;
}


texts: Inserting into a binary search tree in C

texts:
I am in the process of refactoring this simple binary search tree code responsible for adding new values:

void add_internal(Node *root, int value) {
    // Decide whether to insert left or right
    if (root->value >= value) {
        // Decide whether to insert here or down the subtree
        if (root->left) {
            add_internal(root->left, value);
        } else {
            root->left = create_node(value);
        }
    } else {
        // Decide whether to insert here or down the subtree
        if (root->right) {
            add_internal(root->right, value);
        } else {
            root->right = create_node(value);
        }
    }
}

to this:

Node **relevant_node = (root->value >= value) ? &root->left : &root->right;

if (*relevant_node) {
    add_internal(*relevant_node, value);
} else {
    *relevant_node = create_node(value);
}

Both solutions work. My refactored one tho is pretty much the result of trial and error, will it be as robust as the first solution?


texts: Loading and displaying JSON quickly in PhoneGap app

texts:
I have this tap event in an iOS app that I'm developing with PhoneGap. When I click on the left arrow, it finds the desired content and retrieves it from a JSON file. It then displays those results on the screen.

How can I improve this? There's a bit of lag... I know that some of the lag is attributed to the 300ms delay (which fastclick.js and other libraries could resolve), but what else can I do to restructure this code and make it more snappy? I need it to respond quickly.

// PREVIOUS DAYS
    $('.left-arrow').on("tap", function() {
        dateArrayIndex--;
        todaysDate = morehShiur[dateArrayIndex]['date'];
        todaysContent = morehShiur[dateArrayIndex]['description'];
        $('.date').text(todaysDate);
        var path = window.location.href.replace('index.html', '');
        $.getJSON(path + "data/heb-text/" + todaysContent, function(data) {
            $('.title').empty();
            $('ol').empty();
            $('.title').append(data['title']);
            for (var i = 0; i < data.content.length; ++i) {
                $('ol').append('<li>' + data.content[i]['content'] + '</li>');
            }
            $("html, body").animate({ scrollTop: 0 }, 0);
        });
    });


texts: Recording error messages from an exception

texts:
How do I shorten these if else statements? As you can see, those elses are repeated.

if (exception.InnerException != null)
{
    if (!string.IsNullOrEmpty(exception.InnerException.Message))
    {
        errorMessage = exception.InnerException.Message;
    }
    else if (!string.IsNullOrEmpty(exception.Message))
    {
        errorMessage = exception.Message;
    }
    else
    {
        errorMessage = exception.ToString();
    }
}
else if (!string.IsNullOrEmpty(exception.Message))
{
    errorMessage = exception.Message;
}
else
{
    errorMessage = exception.ToString();
}


texts:
Simple task - deploy war-file from TeamCity agent to remote web-server.

I realized it with Fabric, because of it make readable output, and give opportunity to login via SSH with RSA-key. Also - during deploy - build agent must make some additional steps - create backup, stop-start Tomcat service etc.

URL to deploy to can be passed via variable on build-server.

import os
import sys
import time

from fabric.api import run, env, put

VAR_PREFIX = 'bamboo_'

"""Cloudlibrary functions"""

def deploy(logger, rds_basedir):

    """Deploy cloudlibrary.war to remote box, passed via BASE_URL"""

    logger.logger.info('Running cloudlibrary.war deploy')

    # file to deploy
    local_file = 'target/cloudlibrary.war'
    # local_file = 'd:\\RDS\\rdsmanager\\file.txt'

    # file will be created during backup command
    back_file = '/home/ec2-user/backups/cloudlibrary/cloudlibrary_%s.war' % time.strftime('%Y-%m-%d')

    # commands list
    status = 'sudo service tomcat7 status'
    backup = 'cp /var/lib/tomcat7/webapps/cloudlibrary.war %s' % back_file
    check_bkp = 'file %s' % back_file
    tomcat_kill = 'sudo kill -9 $(cat /var/run/tomcat7.pid)'
    tomcat_start = 'sudo /etc/init.d/tomcat7 start'

    try:
        base_url = os.environ[VAR_PREFIX + 'BASE_URL']
        logger.logger.info('\nURL found %s' % base_url)
    except KeyError:
        base_url = 'www.dev.domain.com'
        logger.logger.info('URL variable not found, will default - %s' % base_url)

    # Fabric connection settings
    env.host_string  = base_url
    env.key_filename = [os.path.join(rds_basedir, '.ssh', 'rdsmanager_priv.openssh')]
    env.user = 'user'
    env.project_root = '/var/lib/tomcat7/webapps'

    logger.logger.info('Using URL: %s, user: %s, RDS-key: %s, Tomcat webapps: %s' % (env.host_string, env.user, env.key_filename[0], env.project_root))

    if os.path.isfile(local_file):
        # make backup of current cloudlibrary.war to ~/backup/cloulibrary
        run(backup)

        # if new file doesn't found - Fabric will exit
        run(check_bkp)

        # stop Omcat before put new war-file
        run(tomcat_kill)

        # put new builded war-file
        put(local_file, env.project_root)

        # start Tomcat
        run(tomcat_start)

        # cgeck it's status
        run(status)
    else:
        logger.logger.error('ERROR: file %s not found. Exit.' % local_file)
        sys.exit(1)


texts: Scoreboard with score evolution plots using classes

texts:
I've very recently started using OOP paradigms for the code in my work (academic research). As an exercise I tried coding this quick scoreboard.

I'm not interested in improving the 'display' part, I know there would be a lot to do there, but does my use of classes make any sense?

import os
from numpy import nan, nansum
from matplotlib import interactive
import matplotlib.pyplot as plt

class Player:
    def __init__(self, name):
        self.name = name
        self.score = []
        self.cumulative_score = []
        self.total_score = 0

    def add_score(self, score):
        self.score[-1] = score
        self.cumulative_score[-1] = self.total_score + score
        self.total_score = nansum(self.score)

class ScoreBoard:
    def __init__(self):
        plt.style.use('ggplot')
        interactive(True)
        player_name = True
        self.players = []
        while player_name:
            player_name = input('Player name ? ')
            if player_name:
                self.players += [Player(player_name)]
        self.round = 0
        self.figure = plt.figure()
        self.ax = self.figure.add_subplot(111)
        self.plots = {}
        for player in self.players:
            self.plots[player.name], = plt.plot(range(1, self.round + 1),
                                                player.cumulative_score,
                                                label=player.name, marker='*')
        plt.legend()

    def new_round(self):
        self.round += 1
        for player in self.players:
            player.score += [nan]
            player.cumulative_score += [nan]
        for i, player in enumerate(self.players):
            self.display()
            new_score = input('Score pour {}: '.format(player.name))
            if new_score:
                player.add_score(int(new_score))

    def display(self):
        self.ax.clear()
        for player in self.players:
            self.plots[player.name], = plt.plot(range(1, self.round + 1),
                                                player.cumulative_score,
                                                label=player.name, marker='*')
        plt.legend()
        os.system('cls' if os.name == 'nt' else 'clear')
        print(' \t| '.join(player.name for player in self.players))
        print(''.join(['-'] * 80))
        for round in range(self.round):
            print(' \t| '.join(str(player.score[round]) for player in
                               self.players))
        print(''.join(['-'] * 80))
        print(' \t| '.join(str(player.total_score)
                           for player in self.players))

score_board = ScoreBoard()

while True:
    score_board.new_round()


texts: Add 1 to a number represented as an array of digits, using recursion

texts:
Given a non-negative number represented as an array of digits, plus one to the number.
  The digits are stored such that the most significant digit is at the head of the list.

Explanation for using array vs ArrayList:

I could have used ArrayList and that would have been simpler while appending a 1 at the beginning but I wanted to use arrays only as the functions declarations were given and I didn't want to keep converting list to array and vice versa there by adding another O(n) operation.

Any feedback is appreciated. I know there are similar questions in other languages and using iterative approach, but I want feedback on my particular approach.

public class plusOne {

    public static void main(String args[]){
        plusOne obj = new plusOne();
        int[] digits = {0};
        int[] result = obj.plusOne(digits);
        System.out.println(Arrays.toString(result));
    }

    public int[] plusOne(int[] digits) {
        int length = digits.length-1;
        return increment(digits, length);
    }

    public int[] increment(int [] digits, int index) {
        if(digits[index]!=9)
        {
            digits[index]+=1;
            return digits;
        } else {
            if(index==0) {
                int[] newDigits = Arrays.copyOf(digits,digits.length+1);
                newDigits[digits.length] = 0;
                newDigits[index]=1;
                return newDigits;
            }
            digits[index] = 0;
            return increment(digits, index-1);
        }
    }
}


texts: Improving python3 processing speed (against a reference perl script)

texts:
In order to create fast map/reduce processor for hadoop, I'm evaluating many languages. I'm learning python so I would like my python processor to go as fast as my perl processor.

So, for this question, the point is to increase the performance of simpleprocessor.py. To measure improvement, there is a benchmarking suite available there: https://github.com/Fade78/Stream-processing-benchmark

simpleprocessor.py

#!/usr/bin/python3
import sys
import re

scripttitle="PYTHON SIMPLE PROCESSOR (regex parsing)"

linecount=0
commentary=0
unknownline=0
DATA={}

pattern_data=re.compile(r"^(\d+)\s+(\S+)\s+(\S+)\s+(\d+(?:\.\d+)?)")

print("#",scripttitle,"\n#TRANSFORMED INPUT",sep='')

for line in sys.stdin:
    linecount+=1
    if line.startswith("#"):
        commentary+=1
        continue
    line=line.replace(',','')
    m=re.match(pattern_data,line)
    if m:
        i,k1,k2,value = m.group(1,2,3,4)
        i=int(i)
        value=float(value)
        try:
            DATA[k1][k2]+=value
        except KeyError:
            if k1 not in DATA: # Can't automaticaly create missing key and do the insert?
                DATA[k1]={}
            if k2 not in DATA[k1]:
                DATA[k1][k2]=value
            else:
                DATA[k1][k2]+=value
        print("{0},{1:.0f},{2},{3}".format(i,value,k2,k1))
    else:
        unknownline+=1

print("#DATADUMP")

keystat=0

for k1 in sorted(DATA):
    print(k1,':',sep='',end='')
    for k2 in sorted(DATA[k1]):
        keystat+=1
        print(' (',k2,':',int(DATA[k1][k2]),')',sep='',end='')
    print()

report="#{0}\n#{1}\nparsed line: {2}, commentary line: {3}, unknown line: {4}, keystat: {5}.".format(
               scripttitle, sys.version.replace("\n"," "), linecount, commentary, unknownline, keystat)

print("#REPORT\n"+report,file=sys.stdout)
print(report,file=sys.stderr)

In the benchmark output you can see that the python processor is three time slower than the perl processor.

To test you can run the benchmark and directly test your own modification. You can also add other script (in other language). Please, read the README at github.

Regards.

Fade.

P.S.: You may write a processor in your favorite language too, I'll be glad to put it in the suite.


texts: PreparedStatement for closable recordset and connection

texts:
Following approach uses more Functional approach (non OOP), each method is passed DataSource as dependency.

I've written this piece and I'm wondering if there's something that can be improved. I wish to add ResultSet to try block but not finding any option. Is there a way?

Also please review the class MySQL.

public static Iterator<StateEntity> findAllPrepared(DataSource dataSource, int page, int size) throws SQLException {
    List<StateEntity> list = new ArrayList<>();
    ResultSet rs = null;
    String sql = "SELECT * FROM states LIMIT ?, ?";
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ) {
        statement.setInt(1, page);
        statement.setInt(2, size);
        rs = statement.executeQuery();
        while(rs.next()) {
            list.add(new StateEntity(rs.getString("stateId"), rs.getString("stateName")));
        }
    } finally {
        if(rs != null) rs.close();
    }
    return list.iterator();
}

StateEntity

public class StateEntity {

    private String id;
    private String name;

    public StateEntity(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

SQL Connection

public class MySQL {

    public static MysqlDataSource dataSource = new MysqlDataSource();

    private static Map<String, String> parameters = new HashMap<String, String>(){
        {
            put("authReconnect", "true");
            put("useSSL", "false");
            put("allowMultiQueries", "true");
            put("useUnicode", "true");
            put("useJDBCCompliantTimezoneShift", "true");
            put("useLegacyDatetimeCode", "false");
            put("serverTimezone", "UTC");
        }
    };

    private static Map<String, String> credentials = new HashMap<String, String>(){
        {
            put("host", System.getenv("HOST") != null ? System.getenv("HOST") : "localhost");
            put("schema", System.getenv("SCHEMA") != null ? System.getenv("SCHEMA") : "usa");
            put("username", System.getenv("USERNAME") != null ? System.getenv("USERNAME") : "root");
            put("password", System.getenv("PASSWORD") != null ? System.getenv("PASSWORD") : "mypass");
        }
    };

    static {
        String query = parameters.entrySet().stream()
                .map(p -> p.getKey() + "=" + p.getValue())
                .reduce((p1, p2) -> p1 + "&" + p2)
                .orElse("");

        dataSource.setURL("jdbc:mysql://" + credentials.get("host")+":3306/" + credentials.get("schema") + "?" + query);
        dataSource.setUser(credentials.get("username"));
        dataSource.setPassword(credentials.get("password"));
    }
}

Test

@Test
public void testGetAllPrepared() throws SQLException {
    Iterator<StateEntity> states = State.findAllPrepared(MySQL.dataSource, 0, 5);
    long count = 0;
    while (states.hasNext()) {
        count++;
        StateEntity stateEntity = states.next();
        System.out.println(stateEntity.getId());
        assertNotNull(stateEntity);
        assertNotNull(stateEntity.getId());
        assertNotNull(stateEntity.getName());
        assertEquals(2, stateEntity.getId().length());
    }
    assertEquals(5, count);
}


texts:
I often face the problem of stacked if-statements that look repetitive, but usually can't find an easy way to simplify it.

    if (keyState[BOTTOM]){
        dig_direction = BOTTOM;
        startDig(SIZE / 2 - x % SIZE, DIG_DEPTH);
    } else if (keyState[RIGHT] && isTouching[RIGHT]){
        dig_direction = RIGHT;
        startDig(DIG_DEPTH, 0);
    } else if (keyState[LEFT] && isTouching[LEFT]){
        dig_direction = LEFT;
        startDig(-DIG_DEPTH, 0);
    }


texts:
I'd like some feedback on my implementation to get all the permutations of a set.

Eg:

@Test
public void test()
{
    def data = [["A","B"],["A","B","C","D"],["D","E","F"]]
    def expected = toResultSet("ABD,ABE,ABF,ACD,ACE,ACF,ADE,ADF,BAD,BAE,BAF,BCD,BCE,BCF,BDE,BDF");
    def result = SetPermutations.getSetPermutations(data);
    assert result.containsAll(expected);
    assert result.size() == expected.size();
}

Note that:

The input is a collection of collections
Each collection may have a different number of items
Each item may appear in more than 1 collection (in the input) (ie., data[0] and data[1] both contain "A")
Each resulting permutation must contain exactly 1 item from each of the input sets
Each item may only appear once in a given permutation (ie., 'AAB' is invalid)

Here is my implementation:
(Note, my test is in groovy, but the implementation is java)

public class SetPermutations<E> {

    private List<E> permutationSet;
    private final Collection<Collection<E>> input;
    private final int maxDepth;
    private final Set<List<E>> result;

    public static <E> Set<List<E>> getSetPermutations(Collection<Collection<E>> input)
    {
        SetPermutations<E> setPermutations = new SetPermutations<E>(input);
        return setPermutations.build();
    }

    private SetPermutations(Collection<Collection<E>> input)
    {
        this.input = input;
        maxDepth = input.size() - 1;
        result = new HashSet<List<E>>();
    }

    private Set<List<E>> build() {
        List<Collection<E>> list = new ArrayList<Collection<E>>(input);

        int currentDepth = 0;
        permutationSet = newPermutationSet();

        permute(list,currentDepth);

        return result;
    }
    private void permute(List<Collection<E>> list,
            int currentDepth) {
        Collection<E> collection = list.get(currentDepth);
        for (E object : collection) {
            if (permutationSet.contains(object))
                continue;

            permutationSet.add(object);

            if (currentDepth != maxDepth)
            {
                permute(list, currentDepth + 1);
                permutationSet.remove(object);
            } else {
                result.add(permutationSet);
                // Allow the recursion to continue on a new permutationSet,
                // but remove our item from it.
                permutationSet = clonedPermutationSet();
                permutationSet.remove(object);
            }
        }
    }

    private List<E> newPermutationSet() {
        return new ArrayList<E>();
    }
    private List<E> clonedPermutationSet() {
        return new ArrayList<E>(permutationSet);
    }
}

I have a few specific questions:

Am I reinventing the wheel here?  I searched, and couldn't find a suitable implementation for this problem anywhere, but I find it hard to believe that this hasn't been solved before (better than my solution)
Is there a better way for me to have implemented this?


texts: Extending kotlinx.html dsl to create functions that include bootstrap classes

texts:
I'm looking to create a library that extends kotlinx.html and will include functions that have default css classes.

The goal is to be able to use a function row{} instead of having to type div(classes = "row"){} each time. I would like to create these functions for a lot more commonly used Bootstrap classes.

In my example I use the DIV class to create a row function

The original div function:

@HtmlTagMarker
fun FlowContent.div(classes : String? = null, block : DIV.() -> Unit = {}) : Unit = DIV(attributesMapOf("class", classes), consumer).visit(block)

The first function I created has the row class set instead of `null.

@HtmlTagMarker
fun FlowContent.row(classes: String? = "row", block: DIV.() -> Unit = {}): Unit = DIV(attributesMapOf("class", classes), consumer).visit(block)

But this seems to be very restrictive, since the user of this function won't be able to add any additional css classes.

Therefore I put the row class in the DIV constructor as a string template. This way it can still be extended.

@HtmlTagMarker
fun FlowContent.row(classes: String? = "", block: DIV.() -> Unit = {}): Unit = DIV(attributesMapOf("class", "row $classes"), consumer).visit(block)

Does this seem like the right approach, or is it better to do this another way.

Update

From the kotlinx.html documentation, I also found this approach.

fun DIV.row(block: DIV.() -> Unit) = div(classes = "row") { block() }

I must say that it looks very clean.


texts:
This is one of tasks, which I had to do for the recruitment process at some company. Unfortunately they didn't like it so I've decided to share it here for discussion.

CircleArea.h

#ifndef CIRCLEAREA_H_
#define CIRCLEAREA_H_

//PI Number, with max precision for double (8 bytes)
const double PI = 3.141592653589793115997963468544185161590576171875;

double circleArea(double radius);

#endif

CircleArea.cpp

#include "CircleArea.h"
#include <stdexcept>

double circleArea(double radius)
{
    if(radius < 0)
    {
        throw std::invalid_argument("Radius cannot be less than zero");
    }

    return PI * radius * radius;
}

Why could the solution have been disliked by the recruiters?


texts: Print a array of size n*n, with borders as 1's and fill rest of element with 0's

texts:
Assessment Question: Print an array of size n*n, with border as 1's and rest of the element as 0's.
Sample Input: 5
Sample Output:
[[1 1 1 1 1]
 [1 0 0 0 1]
 [1 0 0 0 1]
 [1 0 0 0 1]
 [1 1 1 1 1]]

Here is my solution:
import numpy as np
n = int(input("Enter a number:"))
np_box = np.zeros([n, n], dtype='int')
np_box[:, 0] = np_box[:, -1] = np_box[0] = np_box[-1] = 1
print(np_box)

Can this code be still optimised (using numpy, considering space and time complexity)?


texts: Validate the inputs and perform actions accordingly

texts:
I have a consumer which is listening to Kafka and from which I am getting avro GenericRecord.

Now basis on GenericRecord payload, I am extracting lot of other things. clientId, deviceId, payId, crossId, appPayload.
And on all those things I have to do sanity check to make sure they are null/empty or not.
And if they are null/empty, then I want to increment the metric counter for that particular metric, log it and continue to the next record from the for loop.
And if they are not null/empty, then I am populating all those fields into a DataPacket builder. All the methods in DataPacket builder have a Preconditions.checkArgument check for null/empty string so I just cannot set them directly without checking them first. If I don't check before setting into DataPacket it will throw exception which will get caught in a catch block and then the whole program will get stopped and it won't move to next record from the for loop as you can see below.

try {
  GenericRecordDomainDataDecoder decoder = new GenericRecordDomainDataDecoder(config);
  while (true) {
    ConsumerRecords<byte[], byte[]> records = consumer.poll(1000);
    for (ConsumerRecord<byte[], byte[]> record : records) {
      DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
          MetricName.TOTAL_NUMBER);
      GenericRecord payload = decoder.decode(record.value());
      String clientId = (String) DataUtils.parseRecord(payload, "clientId");
      String deviceId = (String) DataUtils.parseRecord(payload, "deviceId");
      // can this be improved in any way? the whole if null check for all the below cases?
      if (clientId == null && deviceId == null) {
        DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
            MetricName.INVALID_ID);
        logger.logError("dropping records. invalid clientId and deviceId is coming.);
        continue;
      }
      String payId = (String) DataUtils.parseRecord(payload, "payId");
      if (payId == null) {
        DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
            MetricName.MISSING_PAY_ID);
        logger.logError("dropping records. invalid payId is coming.);
        continue;
      }
      String crossId = (String) DataUtils.parseRecord(payload, "crossId");
      Map<String, String> appPayload =
          (Map<String, String>) DataUtils.parseRecord(payload, "appPayload");
      if (MapUtils.isEmpty(appPayload)) {
        DataMetricHolder.getInstance().increment(DataUtils.EVENT_A,
            MetricName.INVALID_PAYLOAD);
        logger.logError("dropping records. invalid payload is coming.);
        continue;
      }
      DataMetricHolder.getInstance().increment(payId, MetricName.TOTAL_NUMBER);
      // can this be improved in any way?
      Builder packetBuilder = new DataPacket.Builder(payload);
      if (clientId != null) {
        packetBuilder.setClientId(clientId);
      }
      if (deviceId != null) {
        packetBuilder.setDeviceId(deviceId);
      }
      if (crossId != null) {
        packetBuilder.setCrossId(crossId);
      }
      DataPacket packet =
          packetBuilder.setPayId(payId).appPayload(appPayload).build();
      System.out.println(packet);
    }
  }
} catch (Exception ex) {
  // logging error
}

I wanted to see if there is any way to improve my code because right now it looks messy with the way I have all sorts of if null checks. Is there any better way to do the above things so that the code looks clean? I am on Java 7.


texts: Encrypt and backup folder to email daily, when online

texts:
I have a backup script which should backup a folder and send it to email. This should be done once a day. As this is on my laptop which is not online 24/7 I need to check that I am online and can send email. For this script I have an entry in crontab running every 2 hours.

Because the folder is a really important to me and I am quite new to BASH, I would like to ask you if there are any weak points in my code:

#!/usr/bin/env bash

cd ~/projects

DATE=`date +%Y%m%d`
PASS="mysecretpasswordiwontwritehere"
# lastbackup file stores date of last backup in YYYYMMDD format
LASTBACKUP=$(< ./personalwiki/lastbackup)

# Check if backup already exists for current date
# and exit if yes.

if [[ "$LASTBACKUP" == "$DATE" ]]; then
  echo "Do nothing, already backed up."
  exit 0
fi

# Check if we are online
# and exit if not.

ping -c 1 www.google.com

if [[ $? -ne 0 ]]; then
  echo "Offline, cannot do anything."
  exit 0
fi

echo "Online and not equal, need to start backup"

# Pack an encrypt folder
tar cz personalwiki | openssl enc -aes-256-cbc -e -pass pass:$PASS > $DATE.enc

# Send email
MTO="mybackupemail@gmail.com"
MSUB="PW backup as on $DATE"
MATT="$DATE.enc"
EMAIL="backuprobot@mymachine.com" mutt -s "$MSUB" -a $MATT -- $MTO < /dev/null

# Write date of backup to file
echo -n $DATE > ./personalwiki/lastbackup


texts: K&R 4-12 recursive converter int to string

texts:
The exercise is:

  Adapt the ideas of printd to write a recursive version of itoa; that
  is, convert an integer into a string by calling a recursive routine.

I wonder if I have correctly answered the question.

# include <stdio.h>
# define MAX 100

int itoa (char s[], int n)
{
    static int i = 0;

    if (n < 0) {
        s[i++] = '-';
        n = -n;
    }
    if (n / 10)
        itoa (s, n / 10);

    if (i < MAX-1)
        s[i++] = n % 10 + '0';
    else {
        s[i] = '\0';
        return 0;
    }
    return 1;
}

int main ()
{
    int number = -123456789;
    char string[MAX] = { 0 };

    if (itoa(string, number))
        printf("The string is : %s\n", string);
    else
        printf("Error : array limit reached\n");
}

I presented it in a way it's not directly a converter but mostly. I'm a beginner so I don't know if I write some strange things. Could you please review my code?


texts: Reading integers while break condition not met in C++

texts:
This is a drill from the Programming Principles and Practice Using C++. I managed to get it to work but somehow it doesn't feel right to me. I 'd appreciate any pointers on how to simplify/improve the solution.
Especially when it comes to best check if '|' was entered. I feel that creating two extra string variables and then converting them to int using std::stoi is very inefficient. I am new to C++ so please excuse the ignorance. Appreciate any feedback.
Question

Write a program that in a while loop reads 2 integers and prints them. Carry on until the user enters '|'.

#include<iostream>
#include<string>

int main(){
    int a, b;
    std::string _a, _b;
    while (true){
        std::cout << "Enter two numbers." << std::endl;
        std::cin >> _a >> _b;
        if (_a == "|" || _b == "|"){break;};
        a = std::stoi(_a);
        b = std::stoi(_b);
        std::cout << "You entered " << a << " and " << b << std::endl;
    }
    return 0;
}


texts: cleaning up and increasing performance of js code

texts:
I would like to increase my performance of js code write a clean code... can you tell me how to do it... providing my fiddle below with js code...

http://jsfiddle.net/YYg8U/

var myNumbersToSort = [-1, 2, -3, 4, 0.3, -0.001];

function getClosestToZero(numberSet) {
    var i = 0, positiveSet = [], positiveClosest = 0;
    for (i = 0; i < numberSet.length; i += 1) {
        positiveSet.push(numberSet[i] >= 0 ? numberSet[i] : numberSet[i] * -1);
    }
    positiveClosest = Math.min.apply(Math, positiveSet);
    return numberSet[positiveSet.indexOf(positiveClosest)];
}

alert(getClosestToZero(myNumbersToSort));


texts:
Write a function undef that will remove a name and a definition from the maintained by lookup and install.

Here is my solution:

void undef(char *name)
{
    struct Nlist *tmp  = hashtab[hash(name)];

    if(!strcmp(tmp->name, name)) { // delete the head node
        hashtab[hash(name)] = tmp->next;
        free(tmp->name);
        free(tmp);
        return;
    }

    for(; strcmp(tmp->next->name, name); tmp = tmp->next)
        ;

    struct Nlist *save = tmp->next; // save the desired node for deletion
    tmp->next          = tmp->next->next; // adjust the links
    free(save->name);
    free(save);
}

There are 2 main cases. The first is when we want to delete the head node, and when we want to delete a node from the rest of the list.

I will explain how my function works in the second case. The for loop will run until tmp will point to the node that precedes the desired node. Then I adjust the links and free the memory occupied by the desired node.

This approach is not good if the desired value is located at the head node, so I use a if-statement to check if the desired value is located at the head node. If it is, I adjust the head pointer and free the memory.

Here is the code for the entire program: http://ideone.com/t0bjiA.


texts: Getting a serial number from shared table

texts:
I have a table that keeps track of a global serial number shared between several tables. This is not the PK or unique id for each table. It is like a case identifier. Every time users create a new entity we need to give them a unique serial number from this row. My worries is what happens if 2 users hit the method for incrementing this counter at the exact same time. Would this solution be enough?

Also this code would be run from 2 servers using the same database.

public string GetIdentifier()
{
    int retries = 0;
    bool success = false;

    string newId;

    do
    {
        try
        {
            var tracker = Trackers.Find(1);
            newId = tracker.Increment();
            SaveChanges();
            success = true;

        }
        catch (DbUpdateConcurrencyException)
        {
            Thread.Sleep(500);
            if (++retries == 5)
                throw;
        }
        catch (Exception)
        {
            //do some logging
            throw;
        }

    } while (!success);

    return newId;
}


texts:
My task is to add the specified element to the linked list if it is not already present

/**
* Adds the specified element to this set if it is not already present.
* @param o element to be added to this set.
* @return  true if this set did not already contain the specified element.
* @throws NullPointerException - if the specified element is null and this set  does
  not support null elements
 */

This is my solution

public boolean add(E o)  {

    if (o == null)
        throw new NullPointerException();

    ListNode newNode = new ListNode(o, null);
    if (contains(o))
    {
     return false;
    }
    else {

    head.next=newNode;
    head=newNode;
    return true;
   }
}

Can please anybody check it and correct if there are mistakes, or give hints to correct it?


texts:
I have a java function that reads a csv and returns its content as a Vector<Vector<String>>.

The function seems to work as I need it, but my gut feeling says it could be better (never mind the fact that it is declared throws Exception).

So here it is:

private static Vector<Vector<String>> readTXTFile(String csvFileName) throws Exception {

  BufferedReader stream = new BufferedReader(
                          new InputStreamReader(
                          new FileInputStream(csvFileName)));

  Vector<Vector<String>> csvData = new Vector<Vector<String>>();

  String line;
  while ((line = stream.readLine()) != null) {

    csvData.add(new Vector<String>() );

    String[] values = line.split(",");

    for (int v=0; v<values.length; v++) {
       csvData.get(csvData.size()-1).add(values[v]);
    }
  }

  return csvData;
}

Background

Ultimately, the CSV Data will be used to fill a JTable. I could have used an String[][] for the data too, but it seemed that constructing a dynamic String[][] from a csv file would have been even more combersome (although I stand ready to be corrected on this, too).


texts: Credit card validator using Luhn Algorithm

texts:
I'm looking for feedback or tips to maybe make my code more readable or faster or just general tips to help get myself started with app making with Python.

import sys

# check for valid input
if len(sys.argv) == 2:
    try:
        int(sys.argv[1])
        if(len(str(sys.argv[1])) == 16):
            pass
        else:
            print("Not 16 digits!")
            sys.exit()
    except ValueError:
        print('Not an integer!')
        sys.exit()
else:
    print('Not enough or too many command line arguments! \n Proper use \"python Check.py <credit card number here> \" ')
    sys.exit()

def main():
    # put the digits into a list
    number = convertToList(sys.argv[1])
    sum = cardCheck(number)
    if (sum%10 == 0):
        print('Valid Card!')
    else:
        print('Invalid Card!')

#converts initial passed int variable to list
def convertToList(num):
    numStr = str(num)
    numList = []
    for digit in numStr:
        numList.append(int(digit))
    return (numList)

def cardCheck(digitList, count = 0):
    sum = 0
    #if digit is every second digit multiply by 2
    if(count%2 == 0 & count < 15):
        digitList[count] = (digitList[count] * 2)
        #if is 2 digit number after multiplication
        if(digitList[count] >= 10):
            digitList[count] = addDigits(digitList[count])
            cardCheck(digitList, count + 1)
        else:
            cardCheck(digitList, count + 1)
    #progresses program
    elif(count < 15):
        cardCheck(digitList, count + 1)
    else:
        return 0
    for digits in digitList:
        sum += int(digits)
    return sum

#resolve 2 digit number conflict by adding the digits of the number and returning it
def addDigits(num):
    list = str(num)
    sum = 0
    for digits in list:
        sum += int(digits)
    return sum

if __name__ == '__main__':
        main()


texts:
I have a much needed rewrite of an inherited application ahead of me and have started to sketch out some possible solutions / build some prototypes for different parts of the application.

I'd like to have some feedback if this is a good approach to provide application events.

Goals:

Loosely coupled
Strictly typed / refactor friendly
Declarative
Adhere to SRP (Single responsibility principle)
Lightweight

All events are classes derived from EventBase. An IoC Container will handle lifetimes of brokers and subscribers. Constructor injection is used. All types implementing IEventSubscriber<> (where T : EventBase) will be automatically registered in the container. My DefaultEventBroker implementation then has an optional IEnumerable<IEventSubscriber<>> dependency, which the container will resolve to all visible subscribers for a given event type. Under the hood a System.Reactive.Subjects.Subject<> (Microsoft Reactive Extensions) will do the heavy lifting.

Essentially I provide two ways to subscribe to events:

Subscribe by setting a dependency on (one or more) IEventBroker<>

public class MyEventListeningComponent
{
    public MyEventListeningComponent(IEventBroker<ProgramStartedEvent> eventBroker)
    {
        eventBroker.Subscribe(e =>
        {
            Console.WriteLine("[MyEventListeningComponent] Program Started: {0}", e.StartDate.ToString());
        });
    }
}

Subscribe by implementing (one or more) IEventSubscriber<>

public class MyEventSubscriber : IEventSubscriber<ProgramStartedEvent>, IEventSubscriber<ProgramEndedEvent>
{
    public void OnNext(ProgramStartedEvent value)
    {
        Console.WriteLine("[MyEventSubscriber] OnNext: Program Started: {0}", value.StartDate.ToString());
    }

    public void OnNext(ProgramEndedEvent value)
    {
        Console.WriteLine("[MyEventSubscriber] OnNext: Program Ended: {0}", value.EndDate.ToString());
    }
}

Any more or less obvious pitfalls? Suggestions?

Side note: IEventSubscriber<> is essentially an IObserver<> without the OnCompleted and OnError methods, because I can subscribe to multiple event types by implementing IEventSubscriber<> with different generic type arguments and I wouldn't be able to get an event type context in OnCompleted and OnError (because those methods do not have generic type arguments). I'm relatively sure I won't be needing those hooks in this scenario anyway.

Edit: Events are raised (or published) via IEventBroker<>

public class MyEventRaisingComponent
{
    public MyEventRaisingComponent(IEventBroker<ProgramStartedEvent> eventBroker)
    {
        eventBroker.Publish(new ProgramStartedEvent() { StartDate = DateTime.Now });
    }
}


texts: Create all possible character combinations of any size

texts:
I am trying to create all possible character combinations of a given word.  For example, “laptop” will include the following possible combinations:

l
la
lap
lapt
lapto
laptop
lp
lpa
lpat
lpato
lpatop

Here is what I have tried:

#!/usr/bin/env python
import argparse
import sys

def parse_args(argv):
    """parsing argument"""
    parser = argparse.ArgumentParser()
    parser.add_argument('-input', dest='input', type = str,
                         required = True,
                         help = "please provide string")
    args = parser.parse_args(argv)
    return args

def get_patt(patt, patt_index, new_pat):
    print new_pat
    for i in range(patt_index, len(patt), 1):
        new_pat = new_pat + patt[i]
        print new_pat
def main(args):
    f_pat = ""
    input = args.input
    for k in range(0, len(input), 1):
        for i in range(0, len(input), 1):
            f_pat =  input[i]
            for j in range(i+1, len(input), 1):
                f_pat = f_pat + input[j]
                get_patt(input, j+1, f_pat)
        input = args.input[k:] + args.input[:k]
        print "Input String", input

if __name__ == "__main__":
    args =parse_args(sys.argv[1:])
    main(args)


texts: Everything you might want to know about an element

texts:
I am working with a lot of DOM manipulation and need to know several values of an element to determine its position within the DOM and I have written the following to help scrape several of the bits of information I need to proceed.

To me this looks very heavy and there might be some room to help improve the speed / accuracy of returning this information.

Any help in speeding this up or helping with the redundancy issues would be most helpful.

jsFiddle

$.fn.info = function(){
    var $el = this,
        obj = {
            _css: {},
            $win: $(window),
            $doc: $(document),
            x: Math.floor($el.offset().left),
            y: Math.floor($el.offset().top),
            w: Math.floor($el.width()),
            h: Math.floor($el.height()),
            tag: $el.prop("tagName").toLowerCase(),
            computedCss: function(){
                var css = ["width", "height", "float", "color", "font-size", "position", "top", "right", "bottom", "left", "margin-top", "margin-right", "margin-bottom", "margin-left", "color", "display", "visibility"];
                for(var i = 0; i < css.length; i++){
                    if(css[i].indexOf("-") > -1){
                        var temp = css[i].replace("-", "_");
                        this._css[temp] = $el.css(css[i]);
                    }else{
                        this._css[css[i]] = $el.css(css[i]);
                    };

                };
                return this;
            },
            checkVisibility: function(){
                this.visible = (((this.y + this.h) <= (this.top + this.winH)) && (this.y >= this.top));
                this.partial = ((this.y <= (this.top + this.winH)) && ((this.y + this.h) >= this.top));
                return this;
            },
            init: function(){
                this.winH = Math.floor(this.$win.height());
                this.winW = Math.floor(this.$win.width());
                this.docH = Math.floor(this.$doc.height());
                this.docW = Math.floor(this.$doc.width());
                this.top = this.$win.scrollTop();

  /* :compute the box-modal a,b,c,d with {x,y} values: */
  /* a----b */  this.a = { x:this.x, y:this.y };
  /* |    | */  this.b = { x:this.x+this.w, y:this.y };
  /* |    | */  this.c = { x:this.x, y:this.y+this.h };
  /* c----d */  this.d = { x:this.x+this.w, y:this.y+this.h };

                this.computedCss();
                this.checkVisibility();
                return this;
            }
        }.init();

    return obj;
};


texts:
I've successfully solved the Alien Languages problem for Google Code Jam in Haskell:

The algorithm is trivial - turn the patterns into regular expressions and see how many of the known words match these expressions.

But - this has taken me far longer than I expected it to, and most of the time I was battling with getting my types correct. Which leaves me wondering whether there is something wrong with my understanding of functional programming.

module Main where

-- http://code.google.com/codejam/contest/90101/dashboard#s=p0
-- Input and output with standard redirection operators

-- Unless otherwise indicated, all modules used are either bundled with
-- the Haskell Platform (http://hackage.haskell.org/platform/) or available
-- as a separate download from Hackage (http://hackage.haskell.org/).

import Data.List
import Text.Regex.Posix
import Data.String.Utils

numberOfMatches :: String -> [String] -> Int
numberOfMatches pattern = foldl' matches 0
  where
    matches acc word = if word =~ pattern' :: Bool
                           then acc + 1
                           else acc
    pattern' = replace "(" "[" $ replace ")" "]" pattern

getResult :: String -> ([String], Int, [String]) -> ([String], Int, [String])
getResult pattern (w, count, accum) = (w, count - 1, res : accum)
    where res = "Case #" ++ show count ++ ": " ++ show (numberOfMatches pattern w)

main :: IO ()
main = do
  (header:xs) <- fmap lines getContents -- IO is a Functor.
  let [_, d, n] = map read $ words header
  let knownWords = take d xs
  let patterns = drop d xs
  let (_, _, results) = foldr getResult (knownWords, n, []) patterns
  mapM_ putStrLn results

Which, for a test input of:

3 5 4
abc
bca
dac
dbc
cba
(ab)(bc)(ca)
abc
(abc)(abc)(abc)
(zyx)bc

Yields the results:

Case #1: 2
Case #2: 1
Case #3: 3
Case #4: 0


texts:
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem

Given an Iterator class interface with methods: next() and
hasNext(), design and implement a PeekingIterator that support the
peek() operation -- it essentially peek() at the element that will
be returned by the next call to next().
Example:
list: [1,2,3].

Call next() gets you 1, the first element in the list. Now you call
peek() and it returns 2, the next element. Calling next() after that
still return 2.  You call next() the final time and it returns 3, the
last element.  Calling hasNext() after that should return false.

Follow up: How would you extend your design to be generic and work
with all types, not just integer?

Code
#include <vector>

class PeekingIterator : public Iterator {
    int next_num;
    bool num_has_next;

public:
    PeekingIterator(const std::vector<int> &nums) : Iterator(nums) {
        num_has_next = Iterator::hasNext();

        if (num_has_next) {
            next_num = Iterator::next();
        }
    }

    int peek() const {
        return next_num;
    }

    int next() {
        int curr_next = next_num;
        num_has_next = Iterator::hasNext();

        if (num_has_next) {
            next_num = Iterator::next();
        }

        return curr_next;
    }

    bool hasNext() const {
        return num_has_next;
    }
};

Reference
LeetCode has a template for answering questions. There is usually a class named Solution with one or more public functions which we are not allowed to rename. For this question, the template is:
/*
 * Below is the interface for Iterator, which is already defined for you.
 * **DO NOT** modify the interface for Iterator.
 *
 *  class Iterator {
 *      struct Data;
 *      Data* data;
 *      Iterator(const vector<int>& nums);
 *      Iterator(const Iterator& iter);
 *
 *      // Returns the next element in the iteration.
 *      int next();
 *
 *      // Returns true if the iteration has more elements.
 *      bool hasNext() const;
 *  };
 */

class PeekingIterator : public Iterator {
public:
    PeekingIterator(const vector<int>& nums) : Iterator(nums) {
        // Initialize any member here.
        // **DO NOT** save a copy of nums and manipulate it directly.
        // You should only use the Iterator interface methods.

    }

    // Returns the next element in the iteration without advancing the iterator.
    int peek() {

    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    int next() {

    }

    bool hasNext() const {

    }
};

Problem

Solution

Discuss


texts: When given 7 letters, find all possible words with length 3 to 7

texts:
I am writing a program in JavaScript to find all possible words given 7 letters. The words have to be 3 or more characters, and for right now I am limiting it to 7 characters long. The code below works, but takes forever to complete and I would like to speed it up. Would recursion help?

Thanks for any suggestions.

The variable wordList is an array of 60,000 words.

    function isWord(word){
        var found = wordList.indexOf(word);
        if(wordList[found]===word) return true;
            else return false;
    }
    for(var i=0; i<letters.length; i++) {
        for(var j=0; j<letters.length; j++) {
            for(var k=0;k<letters.length; k++) {
                if(isWord(letters[i]+letters[j]+letters[k]))
                    w.push(letters[i]+letters[j]+letters[k])
            }
        }
    }
    for(var i=0; i<letters.length; i++) {
        for(var j=0; j<letters.length; j++) {
            for(var k=0; k<letters.length; k++) {
                for(var l=0; l<letters.length; l++) {
                    if(isWord(letters[i]+letters[j]+letters[k]+letters[l]))
                    w.push(letters[i]+letters[j]+letters[k]+letters[l])
                }
            }
        }
    }
    for(var i=0; i<letters.length; i++) {
        for(var j=0; j<letters.length; j++) {
            for(var k=0; k<letters.length; k++) {
                for(var l=0; l<letters.length; l++) {
                    for(var m=0; m<letters.length; m++) {
                        if(isWord(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]))
                        w.push(letters[i]+letters[j]+letters[k]+letters[l]+letters[m])
                    }
                }
            }
        }
    }
    for(var i=0; i<letters.length; i++) {
        for(var j=0; j<letters.length; j++) {
            for(var k=0; k<letters.length; k++) {
                for(var l=0; l<letters.length; l++) {
                    for(var m=0; m<letters.length; m++) {
                        for(var n=0; n<letters.length; n++) {
                            if(isWord(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]+letters[n]))
                            w.push(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]+letters[n])
                        }
                    }
                }
            }
        }
    }
    for(var i=0; i<letters.length; i++) {
        for(var j=0; j<letters.length; j++) {
            for(var k=0; k<letters.length; k++) {
                for(var l=0; l<letters.length; l++) {
                    for(var m=0; m<letters.length; m++) {
                        for(var n=0; n<letters.length; n++) {
                            for(var o=0; o<letters.length; o++) {
                                if(isWord(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]+letters[n]+letters[o]))
                            w.push(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]+letters[n]+letters[o])
                            }
                        }
                    }
                }
            }
        }
    }


texts: Function to check whether a path is valid or not needs your critique

texts:
Here is my code, I use it to verify whether an input path is correct or not. I assume that the input path is encoded in UTF8. Is there any way to make it better?

#define MAX_PATH_LEN MAX_PATH

#define IN
#define OUT

typedef int Bool_T;

static
int GetCharsNumInPath( IN const char * path )
{
    int cnt;

    int i;
    int n = strlen( path );

    for( i = 0; i < n; i++ )
    {
        if( ( path[i] < 0x80 ) || ( path[i] > 0xbf ) )
            cnt++;
    }

    return cnt;
}

Bool_T PathValid( IN const char * path )
{
    if( path != NULL )
    {
        if( GetCharsNumInPath( IN path ) <= MAX_PATH_LEN )
        {
            int i;
            int n = strlen( path );

            for( i = 0; i < n; i++ )
            {
                switch( path[i] )
                {
                    // ? " / < > * |
                    // these characters can not be used in file or folder names
                    //
                    case '?':
                    case '\"':
                    case '/':
                    case '<':
                    case '>':
                    case '*':
                    case '|':
                        return false;

                    // Can meet only between a local disk letter and full path
                    // for example D:\folder\file.txt
                    //
                    case ':':
                    {
                        if( i != 1 )
                        {
                            return false;

                        }else{

                            break;
                        }
                    }

                    // Space and point can not be the last character of a file or folder names
                    //
                    case ' ':
                    case '.':
                    {
                        if( ( i + 1 == n ) || ( path[i+1] == PATH_SEPERATOR_CHAR ) )
                        {
                            return false;

                        }else{

                            break;
                        }
                    }

                    // two backslashes can not go straight
                    //
                    case PATH_SEPERATOR_CHAR:
                    {
                        if( i > 0 && path[i - 1] == PATH_SEPERATOR_CHAR )
                        {
                            return false;

                        }else{

                            break;
                        }
                    }
                }
            }

            return true;

        }else{ // if( GetCharsNumInPath( IN path ) <= MAX_PATH_LEN )

            LOG_ERROR( "PathValid FAILURE --> path is too long" );
            return false;
        }

    }else{ // if( path != NULL )

        // wrong argument
        //
        return false;
    }
}


texts: Displaying items of a list in a text window

texts:
In a game that I am making, I have a look in my game which goes through an array, and lists the things in the array

public void listOpen() {
    ArrayList<String> open = main.getOpenable();
    for(int i = 0; i < open.size(); i++) {
        String value = open.get(i);
        textWindow.append(value + "\n");
        error.setScroll();
    }
}

Sometimes when I'm running the program I notice that it lags slightly. Is there anyway I can make it more efficient?


texts:
I have the following CRC 16 code.  Is it possible to improve the performance of the code with unsafe constructs?  My knowledge about pointer arithmetic is rather limited.

public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }

public class Crc16Ccitt
{
    static ushort[] table = new ushort[256];

    public ushort ComputeChecksum(params byte[] bytes)
    {
        ushort crc = 0;
        for (int i = 0; i < bytes.Length; ++i)
        {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }

    public Crc16Ccitt(Crc16Mode mode)
    {
        ushort polynomial = (ushort)mode;
        ushort value;
        ushort temp;
        for (ushort i = 0; i < table.Length; ++i)
        {
            value = 0;
            temp = i;
            for (byte j = 0; j < 8; ++j)
            {
                if (((value ^ temp) & 0x0001) != 0)
                {
                    value = (ushort)((value >> 1) ^ polynomial);
                }
                else
                {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
}