texts: Subset sum simple iterative implementation

texts:
Here is the simplest iterative implementation of Subset sum problem that I could come up with1, as a follow up to this recursive implementation of the same problem:

using System;
using System.Linq;

namespace Exercise
{
class SubsetSumBinaryNumber
{
    static void Main(string[] args)
    {
        int[] arr = { 2, 3, 1, -1 };
        PrintSet(arr, "Initial Set:");

        int wantedSum = 4;
        Console.WriteLine("Wanted sum = {0}", wantedSum);

        FindSubsetSum(arr, wantedSum);
    }
    //-----------------------------------------------------------------------
    /* Method: FindSubsetSum(int[] arr, int sum) */
    private static void FindSubsetSum(int[] arr, int targetSum)
    {
        // convert to base
        int toBase = 2;
        // length of binary number
        int length = arr.Length;
        // max value of binary number with "arr.Length" digits
        int iEnd = (int) Math.Pow(length, 2);

        for (int number = 0; number < iEnd; number++)
        {
            // convert current number to binary array
            bool[] binaryNumber = Enumerable.Range(1, length).Select(i => number / (1 << (length - i)) % 2 == 1).ToArray();

            // sum all elements with "true" indexes
            int currentSum = 0;
            for (int j = 0; j < binaryNumber.Length; j++)
            {
                if(binaryNumber[j] == true)
                {
                    currentSum += arr[j];
                }
            }

            // check for sum and print if equal
            if (currentSum == targetSum)
            {
                PrintSubSet(arr, binaryNumber);
            }
        }
    }
}
}

Input:

  -

Output:

  Initial Set.
                      {2 ,3 ,1 ,-1}
                      Wanted sum = 4
                      (1 ,3,)
                      (-1 ,3 ,2)

The algorithm is based on viewing all the combination of indexes of the initial set as a binary number (0's and 1's), then in order to go through all the combinations we simply increment through all the consecutive binary values from 0 to 2set cardinality and sum the set elements that match the 1's in the binary value, check the sum and print them if sum matches the wanted value.

Could the for loop be reduced in half if both current binary and its complement are checked simultaneously?

What is the complexity of this algorithm?

Any remarks regarding style and optimization will be appreciated.

Helper functions:

    /* Method: PrintSubSet(int[] arr, bool[] subSet) */
    private static void PrintSubSet(int[] arr, bool[] subSet)
    {
        Console.Write("(");
        for (int i = 0; i < arr.Length; i++)
        {
            if (subSet[i] == true)
            {
                Console.Write(arr[i]);

                if (i < arr.Length - 1)
                {
                    Console.Write(" ,");
                }
            }
        }
        Console.WriteLine(")");
    }
    //----------------------------------------------------------------------
    /* Method: PrintSet(int[] arr, string label = "") */
    private static void PrintSet(int[] arr, string label = "")
    {
        Console.WriteLine(label);

        Console.Write("{");
        for (int i = 0; i < arr.Length; i++)
        {
            Console.Write(arr[i]);

            if (i < arr.Length - 1)
            {
                Console.Write(" ,");
            }
        }
        Console.WriteLine("}");
    }

1. The most of the algorithms (that I could find) use recursion, dynamic programming and other fairly complex iterative approaches.


texts: Placement of success code in a conditional

texts:
I'm not sure if there's a standard view where the placement of a success result should be in a conditional that can return multiple statuses. The success condition of this function is in the middle of the conditional block:

def redeem(pin)
  success = false
  message = nil
  if !self.date_claimed.nil?
    message = 'Reward already claimed'
  elsif self.reward.redemption_pin == pin
    success = true
    self.date_claimed = Time.zone.now
    self.save
  else
    message = "Wrong pin"
  end
  return {:success => success, :message => message}
end

I could rewrite it to be at the end:

def redeem(pin)
  success = false
  message = nil
  if !self.date_claimed.nil?
    message = 'Reward already claimed'
  elsif self.reward.redemption_pin != pin
    message = "Wrong pin"
  else
    success = true
    self.date_claimed = Time.zone.now
    self.save
  end
  return {:success => success, :message => message}
end

or I could rewrite it to be at the top but conditions become slightly more complex:

def redeem(pin)
  success = false
  message = nil
  if self.reward.redemption_pin == pin && self.date_claimed.nil?
    success = true
    self.date_claimed = Time.zone.now
    self.save
  elsif date_claimed
    message = 'Reward already claimed'
  else
    message = "Wrong pin"
  end
  return {:success => success, :message => message}
end

I personally think I prefer it to be at the beginning or the end, but in this function the end seems to be the best place.


texts: Get all the PDF files from FTP server in different folders

texts:
Well, quite a biggie with all the foreach's. It works, it gets me 981 results, but there must be a way to shorten this code. Right?

<?php

$class = new FTPcleanup();
echo $class->index();

class FTPcleanup {

    private $server = "1.1.1.1";
    private $user   = "ftpuser";
    private $passwd = "ftppassword";
    private $path   = "/Folder/Productthingfolderthing/";

    private function connect_ftp() {
        $connection = ftp_connect($this->server);

        ftp_login($connection, $this->user, $this->passwd);
        ftp_chdir($connection, $this->path);

        return $connection;
    }

    private function connect_sql() {

    }

    private function get_files_from_ftp() {
        $FinalObjectList = array();

        $connection = $this->connect_ftp();

        $folders = ftp_nlist($connection, ".");

        foreach($folders as $folder) {
            ftp_chdir($connection, $this->path.$folder);

            $subfolders = ftp_nlist($connection, ".");
            if (count($subfolders !== 0)) {
                foreach ($subfolders as $subfolder) {

                    if (ftp_size($connection, $subfolder) == "-1") {
                        //Folder, open and go on to child folders
                        if(ftp_chdir($connection, $this->path.$folder."/".$subfolder)){
                            $childfolders = ftp_nlist($connection, ".");

                            if (count($childfolders !== 0)) {
                                foreach ($childfolders as $childfolder) {
                                    if (ftp_size($connection, $childfolder) == "-1") {
                                        //Folder, open and then add files to array.
                                        if(ftp_chdir($connection, $this->path.$folder."/".$subfolder."/".$childfolder)) {
                                            $folderobjects = ftp_nlist($connection, ".");

                                            foreach ($folderobjects as $folderobject) {
                                                $FinalObjectList[] = $this->path.$folder."/".$subfolder."/".$childfolder."/".$folderobject;
                                            }
                                        }

                                        else {
                                            print_r($this->path.$folder."/".$subfolder."/".$childfolder);
                                            echo "
";
                                        }

                                    }
                                    else {
                                        $FinalObjectList[] = $FinalObjectList[] = $this->path.$folder."/".$subfolder."/".$childfolder;
                                    }
                                }
                            }
                        }
                        else{
                            print_r($this->path.$folder."/".$subfolder);
                            echo "
";
                        }
                    }
                    else {
                        $FinalObjectList[] = $FinalObjectList[] = $this->path.$folder."/".$subfolder;
                    }
                }
            }
        }
        return $FinalObjectList;
    }

    public function index () {
        $SortedObjectList = array();

        $objectlist = $this->get_files_from_ftp();
        foreach($objectlist as $object) {
            $chunks = explode("_", $object);
            $strippath = explode("/", $chunks[0]);

            $SortedObjectList[end($strippath)] = $object;

            unset($chunks);
            unset($strippath);
        }

        var_dump(count($SortedObjectList));

    }
}


texts:
I'm using linear algebra as my basis. One very specific change I'd like to make is to allow for equality tests between points and vectors with an unequal number of components by assuming that all undefined components are zero (all points and vectors have infinite components; equality tests stop testing once a check for both components return 'undefined'). Mostly I'd like to do this just because it seems kind of cool to do, so it is not remarkably important.

But in essence, I really just want someone to rip this code apart and tell me why I'm doing everything wrong (or tell me that I'm doing things pretty alright). The goal is just to have a nice, sane Point and Vector system that is very flexible and can be understood by anyone--and used by anyone--for any purpose they'd like. Everything I'm building will rely on the following code, so I want to make sure that my design patterns are reasonable and flexible.

import math, sys, os

TOLERANCE = 0.00001

class SizeError(Exception):
    def __init__(self, *args):
        self.args = args
        print "Size Error between " + str(args)

class P(object):
    def __init__(self, *args):
        if len(args) == 1:
            try:
                self.components = tuple(args[0])
                self.size = len(args[0])
            except TypeError:
                self.components = tuple(args)
                self.size = len(args)
        else:
            self.components = args
            self.size = len(args)
    def __getitem__(self, key):
        return self.components[key]
    def __repr__(self):
        result = ""
        for i in range(0, self.size):
            result += str(self[i]) + ", "
        return "<Point (" + str(self.size) + ") : "  + result[:-2] + ">"
    def __eq__(self, other):
        if self.size != other.size:
            raise SizeError(self, other)
        for i in range(0, self.size):
            result = self[i] - other[i]
            if math.fabs(result) > TOLERANCE:
                return False
        return True
    def __add__(self, other):
        if other.size != self.size:
            raise SizeError(self, other)
        result = []
        for i in range(0, self.size):
            result.append(self[i] + other[i])
        return P(result)
    def __sub__(self, other):
        if other.size != self.size:
            raise SizeError(self, other)
        result = []
        for i in range(0, self.size):
            result.append(self[i] - other[i])
        return V(result)

class V(P):
    def __repr__(self):
        result = ""
        for i in range(0, self.size):
            result += str(self[i]) + ", "
        return "<Vector (" + str(self.size) + ") : "  + result[:-2] + ">"
    def __add__(self, other):
        if other.size != self.size:
            raise SizeError(self, other)
        result = []
        for i in range(0, self.size):
            result.append(self[i] + other[i])
        return V(result)
    def __mul__(self, scalar):
        result = []
        for i in range(0, self.size):
            result.append(self[i] * scalar)
        return V(result)
    def __neg__(self):
        return self * -1
    def dotProduct(self, other):
        result = 0
        if self.size != other.size:
            raise SizeError(self, other)
        for i in range(0, self.size):
            result += self[i] * other[i]
        return result
    def normalize(self):
        result = []
        length = self.getLength()
        if math.fabs(length) < TOLERANCE: return self.getZero()
        for i in range(0, self.size):
            result.append(self[i] / length)
        return V(result)
    def getLength(self):
        result = 0
        for i in range(0, self.size):
            result += self[i]**2
        return math.sqrt(result)
    def getZero(self):
        return self * 0
    def isZero(self):
        zero = self.getZero()
        return self == zero


texts:
In our latest Veracode scan for an application, I have come across the issue of Improper Resource Shutdown or Release.  It is pointing at a function.  Here's  what the code looks like:

Imports System.Data.SqlClient
Public Class DAL
    Public Shared ConnString As String = ConfigurationManager.ConnectionStrings("connection").ConnectionString

Public Shared Function CheckSecurity(ByVal strUserID As String, ByVal strOperation As String, ByVal strAppID As String) As Boolean
    Dim sbSQL As New StringBuilder
    Dim MyConnection As SqlConnection = New SqlConnection()
    Dim sqlCmd As SqlCommand = New SqlCommand

    MyConnection.ConnectionString = ConnString

    sbSQL.Clear()

    sbSQL.AppendLine("EXEC dbo.CheckSecurity @UserID, @AppID, @Operation")

    sqlCmd.CommandText = sbSQL.ToString
    sqlCmd.Connection = MyConnection

    With sqlCmd.Parameters
        .Clear()
        .Add("@UserID", SqlDbType.VarChar, 15).Value = strUserID
        .Add("@AppID", SqlDbType.VarChar, 50).Value = strAppID
        .Add("@Operation", SqlDbType.VarChar, 50).Value = strOperation
    End With

    Try
        If getDataTableFromSqlCmd(sqlCmd).Rows.Count > 0 Then
            CheckSecurity = True
        Else
            CheckSecurity = False
        End If

    Catch ex As Exception
        Throw New ApplicationException("SECURITY ACCESS ERROR")
    Finally
        If MyConnection.State = ConnectionState.Open Then
            MyConnection.Close()
        End If

        MyConnection.Dispose()
        sqlCmd.Dispose()

    End Try
End Function

Code for getDataTableFromSqlCMD:

Public Shared Function getDataTableFromSqlCmd(ByVal sqlCmd As SqlCommand) As DataTable
    Dim dt As New DataTable
    Dim MyAdapter As New SqlDataAdapter(sqlCmd)

    Try
        sqlCmd.CommandTimeout = m_iSQLTimeOut
        MyAdapter.Fill(dt)
        getDataTableFromSqlCmd = dt

    Catch ex As Exception
        Throw New ApplicationException("GET DATA TABLE ERROR")
    Finally
        sqlCmd.Dispose()
        MyAdapter.Dispose()
        dt.Dispose()
    End Try
End Function

As far as I can tell the resources in this code are being properly deallocated.  Am I missing something?


texts:
I read many times about controller code mustn't be too complicated and so on. I was developing new features in my simple project. I added a function, which allow users to get access to news only in one specified category. Now, if a user writes some of this URL:

/news/common
/news/sport
/news/finance

only news from specified category would be shown.

I was thinking about how to do this through another actions, but realized that I can do it in index action. I need just to check if user entered category, but not id (id can
contain only digits), which I've done.

Controller:

public function indexAction() {
    $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');

    $options = array();

    $categoryUrl = (string)$this->params('category');

    if($categoryUrl) { // add category to the 'where'
        $category = $objectManager
            ->getRepository('\News\Entity\Category')
            ->findOneByUrl($categoryUrl);
        if(!$category) {
            return $this->redirect()->toRoute('news');
        }
        $options['category'] = $category->getId();
        $categoryName = $category->getName();
    }

    $news = $objectManager
        ->getRepository('\News\Entity\Item')
        ->findBy($options, array('created'=>'DESC'));

    $items = array();
    foreach ($news as $item) {
        $buffer = $item->getArrayCopy();
        $buffer['category'] = $item->getCategory()->getName();
        $buffer['user'] = $item->getUser()->getDisplayName();
        $items[] = $buffer;
    }

    $view = new ViewModel(array(
        'news' => $items,
        'categoryName' => $categoryName,
    ));

    return $view;
}

What I am doing here?

receive category from URL

if category specified I add clause to the $options array and set $categoryName as category name
if category is not specified I don't do anything with $options (so it will be blank after this part) and don't set flag (so it is not set, undefined)

get news items (function pass $options array)
return $categoryName and news array to the view

View:

<?
    if($categoryName) {
        $title = $categoryName;
    } else {
        $title = "News list";
    }
    $this->headTitle($title);
?>
// html code, some conditions etc

There is an if condition. If $categoryName is specified, $title will have the same contents as $categoryName. If $categoryName is not specified, $title will be just News list.

Questions

Is this the correct approach at all? Should I create new actions and handle this case in it?
Is it correct to set flags, as I did, send to the view, handle it etc?
Is my controller "fat" now?
How can I improve this code?

In addition, you can find the full code of files on GitHub:

NewsController.php (controller)
index.phtml (view)

Note: Some words in files are in Russian.


texts: Calculate query coverage from BLAST output

texts:
I have a BLAST output file and want to calculate query coverage, appending the query lengths as an additional column to the output.  Let's say I have

2 7 15

f=open('file.txt', 'r')
lines=f.readlines()
import re
for line in lines:
    new_list=re.split(r'\t+',line.strip())
    q_start=new_list[0]
    q_end=new_list[1]
    q_len=new_list[3]
    q_cov=((float(q_end)-float(q_start))/float(q_len))*100
    q_cov=round(q_cov,1)
    q_cov=str(q_cov)
    new_list.append(q_cov)
    r=open('results.txt', 'a')
    x='\t'.join(new_list)
    x=x+'\n'
    r.writelines(x)
f.close()
r.close()


texts:
What I was trying to do here was create a Python script that would generate passwords with 16 characters with uppercase and lowercase letters, and numbers. The generated password would then write itself to a file.

Let me know what you think because I know they say the point of Python is to be able to write powerful scripts that can do what other languages can do in a few lines. I feel like this is probably way more then it should be for what it's doing.

import random
import string

print "Welcome to PassBook!"

def genPasswd():
    global route
    global password
    global username
    global account
    global entry
    account = raw_input("Account: ")
    username = raw_input("Username: ")
    key1 = random.randrange(10,100)
    key2 = random.randrange(10,100)
    key3 = random.randrange(10,100)
    key4 = random.randrange(10,100)
    keya = str(random.choice(string.letters) + random.choice(string.letters))
    keyb = str(random.choice(string.letters) + random.choice(string.letters))
    keyc = str(random.choice(string.letters) + random.choice(string.letters))
    keyd = str(random.choice(string.letters) + random.choice(string.letters))
    key1a = str(key1) + str(keya)
    key2b = str(key2) + str(keyb)
    key3c = str(key3) + str(keyc)
    key4d = str(key4) + str(keyd)
    password = str(key1a + key2b + key3c + key4d)
    entry = "Account: " + account + " - Username: " + username + " - Password: " + password
    file = open("/home/meta/Desktop/Python2/passbook/passbook.txt", "a")
    file.write("\n" + entry + "\n")
    print entry
    return key1
    return key2
    return key3
    return key4
    return keya
    return keyb
    return keyc
    return keyd
    return key1a
    return key2b
    return key3c
    return key4d
    return password
    return username
    return account
    return entry

def queryPb():
    search = raw_input("For which account are you searching: ")
    read = open("/home/meta/Desktop/Python2/passbook/passbook.txt", "r")
    for line in read:
        if search in line:
            print line
            return line
        else:
            print "I'm sorry we could not find any account related to " + search

def takeRoute():
    global route
    route = raw_input("Press 1 to generate a password, Press 2 to search for an existing account:  ")
    if int(route) ==1:
        genPasswd()
    elif int(route) == 2:
        queryPb()
    else:
        print "I'm sorry that is not an option!"
        exit()

takeRoute()


texts:
iteritems on a dict can useful.

Occasionally iteritems is useful for a slice of a list and this effect can be (crudely) implemented as follows:

class List(list):
  def iteritems(self, slice=None):
    if slice is None: return enumerate(self)
    else: return itertools.izip(range(*slice.indices(len(self))), self[slice])

if __name__ == "__main__":
  l=List("hAnGtEn")
  print l
  print list(l.iteritems())
  print list(l.iteritems(slice(1,None,2)))

Output:

['h', 'A', 'n', 'G', 't', 'E', 'n']
[(0, 'h'), (1, 'A'), (2, 'n'), (3, 'G'), (4, 't'), (5, 'E'), (6, 'n')]
[(1, 'A'), (3, 'G'), (5, 'E')]

Is there a more "pythonic" list slicing syntax that should be used?

This:

range(slice.start,slice.stop,slice.step)

does not handle certain special cases very well: e.g. where stop=-1, start=None or step=None. How can the example range/slice implementation be also improved?

edit:

range(slice.start,slice.stop,slice.step)

is better handled with:

range(*slice.indices(len(self)))


texts: Flaten array to 1D and assigning 'associative' keynames recursively

texts:
I would like to convert ($data):

Array
(
    [login] => Log in
    [logout] => Log out

    [label] => Array
        (
            [email] => test@test.com
            [name] => Some name
        )

    [controllers] => Array
        (
            [page] => Array
                (
                    [title_new] => New page
                    [title_edit] => Edit page
                    [submit_button] => Submit page
                )
        )
)

To ($result):

Array
(
    [login] => Log in
    [logout] => Log out
    [label[email]] => test@test.com
    [label[name]] => Some name
    [controllers[page][title_new]] => New page
    [controllers[page][title_edit]] => Edit page
    [controllers[page][submit_button]] => Submit page
 )

The following code works "fine":

$data = some_data;
$result = array();

foreach ($data as $k => $v) {
  if (is_array($v))
    foreach ($v as $_k => $_v)
      if (is_array($_v))
        foreach ($_v as $__k => $__v)
          if (is_array($__v))
            foreach ($__v as $___k => $___v)
              $result[$k.'['.$_k.']['.$__k.']['.$___k.']'] = $___v;
          else
            $result[$k.'['.$_k.']['.$__k.']'] = $__v;
      else
        $result[$k.'['.$_k.']'] = $_v;
  else
    $result[$k] = $v;
}

The code work nicely for four levels, and after that it returns "Array" as the value. I think I need recursion, but I would like for you to review my current code, and optionally present me with a solution to go even deeper.


texts:
I have made CSV file slicer. This is my first and biggest piece of code on Python. It takes one .csv file from current folder and then slices it to n parts and adds a first column, if provided.

import csv
import math
import os
import re
import sys

# Reading and returning files in current directory
def read_files():
    __location__ = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    return [f for f in os.listdir(__location__) if os.path.isfile(f)]

# Removing files which match certain pattern
def remove_old_files():
    for f in read_files():
        if re.search("^[0-9]+\.csv$", str(f)) is not None:
            os.remove(f)

# Getting file to split in current directory
def get_file_to_split():
    for f in read_files():
        if re.search(".*\.csv$", str(f)) is not None:
            split(f, int(sys.argv[1]))

# Split file into n pieces
def split(csv_file, pieces):
    first_col = None
    if len(sys.argv) > 2:
        first_col = sys.argv[2]

    with open(csv_file, 'r') as c:
        reader = csv.reader(c)
        data = list(reader)

    cols_to_write = math.ceil(data.__len__() / pieces)
    chunks = [data[x:x + cols_to_write] for x in range(0, len(data), cols_to_write)]

    for num_file in range(pieces):
        filename = str(num_file) + ".csv"

        with open(filename, 'w') as f:
            w = csv.writer(f)
            for i in range(cols_to_write):
                try:
                    if first_col is not None and i == 0:
                        w.writerow([first_col])
                    w.writerow(chunks[num_file][i])
                except IndexError:
                    pass

    print("Done")

if __name__ == "__main__":
    if int(sys.argv[1]) <= 0:
        raise SystemExit("Piece count must be natural number greater than zero.")

    remove_old_files()
    get_file_to_split()


texts:
I'm making a script that generates imgur.com URLs which contain only .png images bigger than 256 bytes, but smaller than 1200 bytes.

Problem: the script is as slow as a snail, any more than one image and it takes more than ten seconds.

What can I do to improve it, like code-wise?  I want to make it faster also.

$GLOBALS[0] = array(); //store valid getimagesize ARRAY
$GLOBALS[1] = array(); //store invalid links ARRAY STRING
$GLOBALS[2] = 0; //store attempts INTEGER
function guess()
{
    $possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    $result = array();
    for ($i=0; $i<=4; $i++)
    {
        $num = round(mt_rand(0,99999)%strlen($possible));
        $word = $word . substr($possible,$num,1);
    }
    $url = "http://i.imgur.com/".$word.".png";
    $result = getimagesize($url);
    if($result['mime'] AND $result['mime'] == "image/png" AND $result[0]>256 AND $result[1]>256 AND $result[0]<1200 AND $result[1]<1200)
        {
            //echo($result['mime']. "
");
            $result['url'] = $url;
            array_push($GLOBALS[0],$result);
            echo("Result " . count($GLOBALS[0]) . ": ".$GLOBALS[0][count($GLOBALS[0])-1]['url'] . "
");
        }
    else
        {
            array_push($GLOBALS[1],$url);
            //echo("Invalid image, OR image is not png, OR image too small, OR image too large
");
        }
    return($result['mime']);
}

function attempt()
{
    $GLOBALS[2]++;
    $bord = guess();
    if($bord!=='image/png')
    {
        attempt();
    }
}
function getlinks($num)
{
echo("Fetching ".$num." images...
");
attempt();

    if($num>($GLOBALS[2] - count($GLOBALS[1])))
        {
            echo("Attempt failed, trying again...
");
            $amount = $num;
            getlinks($amount);
        }
        else
        {
            echo("Done. ". $GLOBALS[2] . " attempts, of which ". count($GLOBALS[1]) . " are failures.
");
        }

}

getlinks(1);


texts: Using an Angular factory to run data through logic across controllers

texts:
My service:

myApp.factory("MediaService", ['$http',
function($http) {

    return {
        all: function() {
            return $http.get('/media');
        },
        save: function( data ) {
            return $http.post('/media', data);
        }
    }
}
]);

My controller:

myApp.controller("MediaController", ['$http', '$scope', '$routeParams', 'Upload', 'MediaService', 'messageService',
function( $http, $scope, $routeParams, Upload, MediaService, messageService) {
    var media = this;

    MediaService.all().success( function (data) {
        media.versioning = []
        media.files = []
        for(i = 0, len = data[0].file.length; i< len; i++)
            if(!media.versioning[data[0].file[i].key[0]] || media.versioning[data[0].file[i].key[0]].version[0] < data[0].file[i].version[0])
                media.versioning[data[0].file[i].key[0]] = data[0].file[i]
        for(var value in media.versioning)
            media.files.push( media.versioning[value] )
    });

I want to move the code within .success() into the MediaService factory so I can re-use it in another controller.

Obviously I do not want to simply copy and paste this into the other controller, although that would work.

I tried to $q.defer/resolve within the service but it did not work (I believe that practice is deprecated).

What is the best way to move this logic into the service? Ideally I would like to be able to use media.files = MediaService.files().


texts:
This piece of code is to get random samples from two String lists, pos and neg. Based on a specified sampleSize, it writes an equal number of strings into 4 files. This codes seems slow, perhaps due to the file creating operation, since each file is created for a single string. Is there a better way to do this?

// pos and neg are ArrayList<String>
        Collections.shuffle(pos);
        Collections.shuffle(neg);

        int i = 0;
        int j =0;
        while(i < sampleSize ){
            if(i<sampleSize/2) {
                BufferedWriter bw1 = new BufferedWriter(new FileWriter(("test/neg/" + i + ".txt")));
                bw1.write(neg.get(i));
                bw1.close();

                BufferedWriter bw2 = new BufferedWriter(new FileWriter(("test/pos/" + i + ".txt")));
                bw2.write(pos.get(i));
                bw2.close();

            }else{
                BufferedWriter bw1 = new BufferedWriter(new FileWriter(("train/neg/" + j + ".txt")));
                bw1.write(neg.get(j));
                bw1.close();

                BufferedWriter bw2 = new BufferedWriter(new FileWriter(("train/pos/" + j + ".txt")));
                bw2.write(pos.get(j++));
                bw2.close();
            }
            i++;
            System.out.println(i);
        }


texts:
I have written a solution to the blood-type matching problem, as described at https://projectlovelace.net/problems/blood-types/.  The problem is to determine whether a given recipient (in this case, argv[1]) will find a match for a blood transfusion in an array of available donors (argv + 2).

Input blood type: B+
Input list of available blood types: A- B+ AB+ O+ B+ B-
Output: match

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

typedef struct {
    enum { O, A, B, AB } abo;
    enum { P, M } rh;
} Blood;

const int abo[4][4] = {
    { O, O, O, O }, // O
    { O, A, O, A }, // A // *
    { O, B, O, B }, // B // *
    { O, A, B, AB }, // AB
};

const int rh[2][2] = {
    { P, M }, // P
    { M, M }, // M // *
};

Blood
parse(char *s){
    char rh0 = s[strlen(s)-1];
    char *abo0 = strdup(s);
    abo0[strlen(s)-1] = '\0';
    Blood b = {
        !strncmp(abo0, "O", 1) ? O
            : !strncmp(abo0, "A", 1) ? A
            : !strncmp(abo0, "B", 1) ? B
            : !strncmp(abo0, "AB", 2) ? AB
            : -1,
        rh0 == '+' ? P
            : rh0 == '-' ? M
            : -1,
    };
    return b;
}

int
main(int argc, char *argv[]) {
    if(argc < 3)
        err(1, "no arguments given\n");
    int n = argc - 2;
    char *a0 = argv[1];
    char **as = argv + 2;

    Blood b0 = parse(a0);
    Blood *bs = malloc(sizeof(Blood) * n);
    for(int i = 0; i < n; i++)
        bs[i] = parse(as[i]);

    for(int i = 0; i < 4; i++) {
        for(int j = 0; j < 2; j++) {
            for(int k = 0; k < n; k++) {
                if(abo[b0.abo][i] == bs[k].abo && rh[b0.rh][j] == bs[k].rh) {
                    printf("match\n");
                    return 0;
                }
            }
        }
    }
    printf("no match\n");
    return 1;
}

which works correctly in my tests, but uses some hacks.  Specifically, lines marked with // * have repeated values of enums, since I couldn't find a way to make loop sizes conditional on blood types.

What would be a better way, without forcing the blood type enums to be the same size?  And more generally, is there a simpler version of the blood-type matching algorithm?


texts: Looking for a more condensed method of assigning values by using arrays and fixed ranges

texts:
I currently have a Template Workbook set up that has charts and graphs updating when new data is plugged into the Data Tables.
The Data Tables are fixed ranges, and won't change.
The Macro is within the Template Workbook, which is why the below code doesn't set variables for each of the worksheets within the Template Workbook, and Code Names are used for each Worksheet name.
I know the below code is a very basic array code, and works.  However, Is there a more condensed way to perform this array macro?
I have researched, but can't seem to find an example of multiple ranges and assigning values from the Source Workbook - Multiple Worksheets to the Template Workbook - Multiple Worksheets.
Sub Main()

'Turn off screen updates and automatic calculations
    Application.ScreenUpdating = False
    Application.Calculation = xlManual
    Application.DisplayAlerts = False

    Dim wbDataSource As Workbook
    Dim ws As Worksheet

    Set wbDataSource = Workbooks("Segment Trends Data.xlsx")

    For Each ws In wbDataSource.Worksheets
        With ws
            If .Index <> 1 Then
                Dim Data(13) As Variant
                Data(0) = Worksheets("Report1").Range("A1").Value2
                Data(1) = Worksheets("Report1").Range("A5:H11").Value2
                Data(2) = Worksheets("Report2").Range("A1").Value2
                Data(3) = Worksheets("Report2").Range("A5:H11").Value2
                Data(4) = Worksheets("Report3").Range("A1").Value2
                Data(5) = Worksheets("Report3").Range("A5:H11").Value2
                Data(6) = Worksheets("Report4").Range("A1").Value2
                Data(7) = Worksheets("Report4").Range("A5:H11").Value2
                Data(8) = Worksheets("Report5").Range("A1").Value2
                Data(9) = Worksheets("Report5").Range("A5:H11").Value2
                Data(10) = Worksheets("Report6").Range("A1").Value2
                Data(11) = Worksheets("Report6").Range("A5:H11").Value2
                Data(12) = Worksheets("Report7").Range("A1").Value2
                Data(13) = Worksheets("Report7").Range("A5:H11").Value2
            End If
        End With
    Next ws

    wbDataSource.Close SaveChanges:=False

    With wsTTLUSCYTD
        .Range("A1").Value2 = Data(0)
        .Range("A5:H11").Value2 = Data(1)
    End With

    With wsCintiCYTD
        .Range("A1").Value2 = Data(2)
        .Range("A5:H11").Value2 = Data(3)
    End With

    With wsCOLCYTD
        .Range("A1").Value2 = Data(4)
        .Range("A5:H11").Value2 = Data(5)
    End With

    With wsDaytonCYTD
        .Range("A1").Value2 = Data(6)
        .Range("A5:H11").Value2 = Data(7)
    End With

    With wsIndyCYTD
        .Range("A1").Value2 = Data(8)
        .Range("A5:H11").Value2 = Data(9)
    End With

    With wsLouisCYTD
        .Range("A1").Value2 = Data(10)
        .Range("A5:H11").Value2 = Data(11)
    End With

    With wsCoreMktCYTD
        .Range("A1").Value2 = Data(12)
        .Range("A5:H11").Value2 = Data(13)
    End With

    Calculate

    Dim TemplatePath As String
        TemplatePath = "C:\Users\cday\OneDrive - udfinc.com\Budgeting Presentation_Working Files\"
        ActiveWorkbook.SaveAs Filename:=TemplatePath & "Segment Trends - CYTD - Budget Template" & ".xlsm", FileFormat:=52

'Turn screen updates and automatic calculations back on
    Application.ScreenUpdating = True
    Application.Calculation = xlAutomatic
    Application.DisplayAlerts = True

End Sub

Using Debug.Print, the data is pulling from the wbDataSource worksheets within the Loop.


texts: Parsing displayed month/year for calendar

texts:
I have a 6 x 7 grid for a calendar = 42 DateTimes. I'm trying to display the displayed month/year at the top of the calendar.

If there are 3 months displayed, I only want to show the name for the middle month (October 2018, for instance). If 2 months are displayed, split the name (October - November 2018). If 2 months are displayed and have different years, append with year on both sides (December 2018 - January 2019).

This is what I have, and it works, but it's in a property that may be "getted" often and I want this to be as efficient as possible. Here's the code:

public string ViewedMonthYearStr
{
    get
    {
        if (_grid != null)
        {
            string first;
            string middle = string.Empty;
            string last = string.Empty;
            HashSet<int> months = new HashSet<int> { _grid[0].Month, _grid[21].Month, _grid[41].Month };
            if (months.Count == 3) first = _grid[21].ToString("MMMM yyyy");
            else
            {
                first = _grid[0].ToString("MMMM");
                middle = " - ";
                last = _grid[41].ToString("MMMM yyyy");
            }
            if (_grid[0].Year != _grid[41].Year && months.Count != 3)
            {
                middle = $" {_grid[0].ToString("yyyy")} - ";
            }
            _viewedMonthYearStr = $"{first}{middle}{last}";
        }
        return _viewedMonthYearStr;
    }
}

Is there a more efficient way to do this? My gut tells me that if/else's aren't the most efficient way.


texts: Design - prevent multiple nesting in function

texts:
I have a function written in Groovy which needs to save a record and also return response from the server.
Function is working fine, but I am not happy with the design because I have a problem with multiple nesting.

This is the function:

Map scanAccessRecord(GrailsParameterMap params){

    Map response
    Date currentTime = new Date()
    String readerEthernetAddress = params.readerMac
    Reader reader = Reader.findByDeletedAndEthernetAddress(false, readerEthernetAddress)
    Boolean isAccessIn = (params.isAccessIn == "True")

    if(reader)
    {
        UserSettings userSettings = UserSettings.findByRfidCode(params.rfid.toString())

        if(userSettings)
        {
            if(userSettings.user.company.id == reader.companyId)
            {
                AccessRecord accessRecord = new AccessRecord(reader:reader, userId:userSettings.userId, specificDate:currentTime, isAccessIn: isAccessIn)

                if(accessRecord.save(flush: true))
                {
                    response = [
                            status: '00',
                            message: 'OK',
                            recordId: accessRecord.id,
                    ]
                }
                else
                {
                    response = [
                            status: '60',
                            message: 'error'
                    ]
                }
            }
            else
            {
                response = [status: '40', message: 'USER AND READER ARE NOT FROM SAME COMPANY']
            }
        }
        else
        {
            response = [status: '10', message: 'UNKNOWN USER']
        }
    }
    else
    {
        response = [status: '50', message: 'READER NOT FOUND']
    }

    return response
}

What can I do to make this function "cleaner"?


texts:
For one of my cases in algorithms I am required to create a model of a load balancer model for multiple processors. Lately I became interested in Scala so I decided that it would be great to create this program in Scala. I'm not really familiar with the concept of functional programming so any feedback will be welcome. Please note that I am not asking about the correctness of my algorithm as this is my homework.

object HelloWorld {
  def randomElements(arg: Integer): Double = {
    val r = scala.util.Random
    return r.nextDouble()
  }
  // used for debugging
  def return1Elements(arg: Integer): Double ={
    return 1
  }

  def fillJobs(size: Integer, fillingFunction: (Integer) => Double): Array[Double] = {
    val array = new Array[Double](size);
    for (el <- 0 to size -1) {
      array(el) = fillingFunction(el);
    }
    return array
  }

  def fillProcessors(size: Integer): Array[Double] = {
    val array = new Array[Double](size);
    for (el <- 0 to size -1) {
      array(el) = 0
    }
    return array
  }
  def result(processors: Array[Double]): Double = {
    return processors.max
  }

  def findMaxSolver(processorsArray: Array[Double], jobsArray: Array[Double]): Double = {
    val sortedJobs = jobsArray.sortWith(_ > _)
    var sortedProcessors = processorsArray

    for(processorIndex <- 0 to processorsArray.size -1){
      sortedProcessors(processorIndex) += sortedJobs(processorIndex)
    }

    for(job <- sortedJobs.slice(sortedProcessors.size, sortedJobs.size)){
      sortedProcessors = sortedProcessors.sortWith(_<_)
      sortedProcessors(0) += job
    }
    return result(sortedProcessors)
  }

  def solve(processorsArray: Array[Double], jobsArray: Array[Double],
            solvingFunction: (Array[Double], Array[Double]) => Double): Double = {
    val processors = processorsArray.clone()
    val jobs = jobsArray.clone()

    return solvingFunction(processors, jobs)
  }

  def main(args: Array[String]) {
    val JOB_NUMBER = 1024
    val PROCESSOR_NUMBER = 8
    val jobs = fillJobs(JOB_NUMBER, randomElements)
    val processors = fillProcessors(PROCESSOR_NUMBER)

    println("Job times")
    println("============================")
    for (element <- jobs) {
      println(element)
    }
    println("============================")
    println("Results")
    println("Find max solver " + solve(processors, jobs, findMaxSolver))
  }
}


texts: Keras: Using Autoencoders for prediction

texts:
I have a dataset which I divided into two sections horizontally. Column A of first section is the input variable and Column A of second section is the target variable. I am trying to build a Denoising Autoencoder that is trained using the target variable. Column A consists of string values which are one-hot encoded before giving it into the autoencoder. This is what I have done:
# Import Libraries
import pandas as pd
import numpy as np
from numpy import array
from numpy import argmax
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from keras.models import Model
from keras.layers import Dense, Input
from keras.optimizers import Adam

# Load Dataset
df = pd.read_csv('dataset.csv', index_col=0)

# Divide dataset into sections
section_1 = df[df['D'] == 'Safe']
section_1 = section_1.head(100)

section_2 = df[df['D'] == 'Unsafe']
section_2 = section_2.head(100)

# One-Hot Encode values of Column A
target_values = array(section_2['A'])
input_values = array(section_1['A'])

# integer encode
label_encoder = LabelEncoder()
target_integer_encoded = label_encoder.fit_transform(target_values)
input_integer_encoded = label_encoder.fit_transform(input_values)

# binary encode
onehot_encoder = OneHotEncoder(sparse=False)
target_integer_encoded = target_integer_encoded.reshape(len(target_integer_encoded), 1)
input_integer_encoded = input_integer_encoded.reshape(len(input_integer_encoded), 1)
onehot_encoded_target = onehot_encoder.fit_transform(target_integer_encoded)
onehot_encoded_input = onehot_encoder.fit_transform(input_integer_encoded)

# Setup train and test sets
x_train, y_train = train_test_split(onehot_encoded_target, train_size=0.50)
x_test, y_test = train_test_split(onehot_encoded_input, test_size=0.50)
x_test = np.hstack((x_test, np.tile(x_test[:, [-1]], 3))) # Replicated the last column of x_test so it will be in same shape as x_train and y_train
print(x_train.shape, y_train.shape, x_test.shape) # (50, 95), (50, 95), (50, 95)

# Setup the Autoencoder
input_size = 95
hidden_size = 128
code_size = 32

input_values = Input(shape=(input_size,))
hidden_1 = Dense(hidden_size, activation='relu')(input_values)
code = Dense(code_size, activation='relu')(hidden_1)
hidden_2 = Dense(hidden_size, activation='relu')(code)
output_values = Dense(input_size, activation='sigmoid')(hidden_2)

autoencoder = Model(input_values, output_values)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
autoencoder.fit(x_train, y_train, epochs=100)

# Predict the values
ypred = autoencoder.predict(x_test)

# Evaluate the model
print("MAE test score:", mean_absolute_error(y_test, ypred)) # MAE test score: 0.026
print("RMSE test score:", sqrt(mean_squared_error(y_test, ypred))) # RMSE test score: 0.103

I am very new to machine learning and I would like to know whether the logic I have written above is correct or not. Any feedback is appreciated.


texts:
Lately I have been trying to extract till I drop. Well not necessarily till I drop, but I've been trying to be more strict and look at some metrics of my code.

I have now come along an old class of mine which has a rather large switch case. Metrics say the method lines of code are beyond evil. It goes something like this:

private void startProcessing(Map<MyKeyEnum, String> map) {
    Processor myProcessor = new Processor();
    for (Entry entry : map.entrySet()) {
        switch(entry.getKey()) {
            case KEY1:
                myProcessor.processStuffAboutKey1(entry.getValue());
                break;
            case KEY2:
                myProcessor.processStuffAboutKey2(entry.getValue());
                break;
            case KEY3:
                myProcessor.processStuffAboutKey3(entry.getValue());
                break;
            case KEY4:
                myProcessor.processStuffAboutKey4(entry.getValue());
                break;
            ...
            ...
        }
    }
}

So basically you can gather that it is necessary for me to invoke very different things for each key IF it is in the map. I have therefore already created the Processor class and mind you this is already the absolute shortest and most compact that I was able to come up with. Basically this method does already do only one thing.

But isn't it possible to build this differently so that it is shorter? I currently have 25+ cases to handle

Edit: made clear what Key,Value-Pair is and what they're used for


texts: Multilingual command handler using inheritance

texts:
My problem is that you have a lot of ifconditions to be checked and inside that if condition you have multiple lines of code. I want to eliminate it and use inheritance instead. For every if statement I will be using a separate class to handle it. This is more like a derivative of the command pattern but not command pattern itself.

I have an interface which contains only one method which defines the task I want it to be implemented. I have an abstract class implementing that interface and contains a static map and static methods to add values and retrieves the task. The classes I specified will be extending this Handler class.

This is my scenario:

I am sending a string as parameter to get a specific translator. Let's say Sinhala or Tamil or English. On each implementation of those translators, I will be adding the necessary values to the map in the Handler class in a static block. Basically adding them in the class load time.

Command Interface

public interface Command {
    LanguageTranslator getLangTranslator();
}

Handler Abstract class

public abstract class Handler implements Command {

    private static Map<String, Command> map = new HashMap<>();

    public static void AddToMap(String key, Command command){

        map.put(key,command);
    }
    public static LanguageTranslator getTranslator(String value) throws Exception {
        if (!(map.containsKey(value))){
            throw new LanguageNotFoundException("Translator not found");
        }else {
            return map.get(value).getLangTranslator();
        }
    }

 }

Sinhala Translator

public class SiCommand extends Handler {
    static {
        Handler.AddToMap("1",new SiCommand());
    }

    @Override
    public LanguageTranslator getLangTranslator() {
        return new SiTranslator();
    }
}

Tamil Translator

public class TiCommand extends Handler {
    static {
        Handler.AddToMap("2",new TiCommand());
    }

    @Override
    public LanguageTranslator getLangTranslator() {
        return new TiTranslator();
    }
}

English Translator

public class EnCommand extends Handler {
    static {
        Handler.AddToMap("3",new EnCommand());
    }

@Override
    public LanguageTranslator getLangTranslator() {
        return new EnTranslator();
    }
}

Demo

 RowTranslator rowTranslator = Handler.getTranslator("2");

Questions

Since all values are assigned to the map during the class loading time these are my questions:

Is using static blocks like this a good practice?
I want to eliminate the use of if conditions as I mentioned before. By using this method, whenever someone wants to add a new if condition, you just only have to create a new class extending handler and implement it. Therefore the outside user doesn't need to know the internal handling of the Command's subclasses. The output is just gonna be a translator. Is this a good way of doing it? What are the better alternatives? What should be adjusted?

Note: I will also be focusing strictly on Open/Close principle as well.


texts:
Edit 1: changed a few portions of the code to hopefully make it runnable code and more understandable. If something is still incorrect please let me know.

Edit 2: just remembered I am doing this in python 2.7 because I am required to. If that causes any issues again please let me know.

I am trying to create 4 symbolic equations that correspond to the 4 elements of a normalized quaternion. The equation is for quaternion multiplication

\$\dot q = 0.5*q*[0, \omega]^T\$

\$\omega = [\omega_x, \omega_y, \omega_z]\$

\$q = [q_r, q_i, q_j, q_k]\$
and then I normalize the output. My solution is:

import sympy as sy

def quat_equ(q_l, q_w, renorm=1):
    # quaternion multiplication using equation: q_dot = 0.5 * q * [0, omega)^T
    # multiplication broken up into individual quaternion states
    q_r_d = 0.5 * (q_l[0] * q_w[0] - q_l[1] * q_w[1] + q_l[2] * q_w[2] +
                   q_l[3] * q_w[3])
    q_i_d = 0.5 * (q_l[0] * q_w[1] + q_l[1] * q_w[0] + q_l[2] * q_w[3] -
                   q_l[3] * q_w[2])
    q_j_d = 0.5 * (q_l[0] * q_w[2] + q_l[2] * q_w[0] + q_l[3] * q_w[1] -
                   q_l[1] * q_w[3])
    q_k_d = 0.5 * (q_l[0] * q_w[3] + q_l[3] * q_w[0] + q_l[1] * q_w[2] -
                   q_l[2] * q_w[1])
    # Re-normalizing the quaternion multiple times (heuristic I was taught/required to use)
    # The for loop is causing the slowdown of the code due to re-normalizing
    for i in range(renorm):
        q_r_d *= 1 / sy.sqrt(q_r_d ** 2 + q_i_d ** 2 + q_j_d ** 2 + q_k_d ** 2)
        q_i_d *= 1 / sy.sqrt(q_r_d ** 2 + q_i_d ** 2 + q_j_d ** 2 + q_k_d ** 2)
        q_j_d *= 1 / sy.sqrt(q_r_d ** 2 + q_i_d ** 2 + q_j_d ** 2 + q_k_d ** 2)
        q_k_d *= 1 / sy.sqrt(q_r_d ** 2 + q_i_d ** 2 + q_j_d ** 2 + q_k_d ** 2)
    return [q_r_d, q_i_d, q_j_d, q_k_d]

# setting up symbolics
q_r, q_i, q_j, q_k, w_ib_l, w_ib_m, w_ib_n = sy.symbols("q_r q_i q_j q_k w_ib_l w_ib_m w_ib_n")
q1 = [q_r, q_i, q_j, q_k]
q2 = [0, w_ib_l, w_ib_m, w_ib_n]

# separation of symbolic equations for each state in q_dot (this is a requirement for the code)
quat0 = quat_equ(q1, q2, 3)[0]
quat1 = quat_equ(q1, q2, 3)[1]
quat2 = quat_equ(q1, q2, 3)[2]
quat3 = quat_equ(q1, q2, 3)[3]

# testing of the symbolic equations using substitution
qq = [1., 0., 0., 0., 1., 1., 1.]
var = [q_r, q_i, q_j, q_k, w_ib_l, w_ib_m, w_ib_n]

q0 = sy.Subs(quat0, var, qq).doit()
q1 = sy.Subs(quat1, var, qq).doit()
q2 = sy.Subs(quat2, var, qq).doit()
q3 = sy.Subs(quat3, var, qq).doit()

When I try to re-normalize the quaternion more than 2 times this method becomes very slow. The symbolic equation also becomes massive because the re-normalization adds on basically 4 extra symbolic equations, which slows down later processes a lot. I couldn't think of a better method to create a normalized quaternion that 1) initializes faster and 2) is a smaller symbolic equation. I don't use symbolics in python much so most of Sympy is new to me.


texts: Search for rows in a 2D array that contain a given sequence

texts:
I have a 2d array of m * n dimension (m and n can vary from 1 to 100000). The following snippet of code checks if the sequence exists in the row and stores the index if it exists. The time taken by the following code on 10000*10000 matrix is 650 milliseconds. The sequential version of the code also takes the same time.

This on Intel Core i7-7560U CPU @ 2.40GHz × 4

#include <iostream>
#include <vector>
#include <future>

std::vector<int> lps;

void ComputeLPSArray(std::vector<int> const &pattern) {

    std::vector<int> lps(pattern.size());
    int len = 0;

    lps[0] = 0;

    int i = 1;
    while (i < (int) pattern.size()) {
        if (pattern[i] == pattern[len]) {
            len++;
            lps[i] = len;
            i++;
        } else {
            if (len != 0) {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
}

int SearchPattern(std::vector<int> const &pattern, std::vector<int> const &row) {
    auto M = (int) pattern.size();
    auto N = (int) row.size();

    int i = 0;
    int j = 0;
    while (i < N) {

        if (pattern[j] == row[i]) {
            j++;
            i++;
        }
        if (j == M) {
            return 1;
        } else if (i < N && pattern[j] != row[i]) {
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
    return -1;
}

std::vector<int> SearchSequence(std::vector<std::vector<int>> const &matrix, std::vector<int> const &sequence) {

    ComputeLPSArray(sequence);
    std::vector<int> result(matrix.size());
    unsigned int length = 0;
    std::vector<std::future<int>> f(matrix.size());

    for (unsigned int i = 0; i < matrix.size(); i++) {
        std::vector<int> row = matrix[i];
        f[i] = async(std::launch::async, [sequence, row] { return SearchPattern(sequence, row); });
    }

    for (unsigned int i = 0; i < f.size(); ++i) {
        if (f[i].get() == 1)
            result[length++] = i;
    }

    result.resize(length);

    return result;
}

int main() {

    int m = 25, n = 20; // assume `m` and `n` can vary.
    std::vector<std::vector<int >> matrix(m, std::vector<int>(n));

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            matrix[i][j] = rand() % 1000;
        }

    }

    std::vector<int> sequence = matrix[24]; // This is purely for testing purpose, actual input(matrix&sequence) is read from files.

    std::vector<int> result;
    result = SearchSequence(matrix, sequence); // This is the ONLY function which needs to be optimised.

    return 0;
}

How do I speed up the search time in this scenario?


texts: Finding number of number pairs with given difference

texts:
pairs() is a function which returns the total number of combinations whose difference is k.

     static int pairs(int[] a,int k) {
        int counter=0;
         for (int i : a.length ) {
           for(int j=i+1;j<a.length;j++){
                 if(a[i]-a[j]==k||a[i]-a[j]==-k){
                   counter++;
                 }
                }
           }

 return counter;
}

a is an array of numbers and k is the difference of numbers that are given by user.  I have to find the total number of combinations with a difference of k.  I have done this code, but I want a more optimized code.


texts: Py3 ebay-scraper - Project I need cheap GPU

texts:
I need cheap GPU's and decided to make a little ebay-scraper to make sure I can buy it at cheap prices. It works and I can search for (any) product to scrape the Title, Price and Shipping cost of that product.

But I feel like I haven't done it in a generic way, hence the need to post it here. Thus my question is, could this have been done more generic?

Code

from bs4 import BeautifulSoup
from urllib.request import urlopen

def find_next_page(soup):
    '''
    Finds next page

    Returns:
        Next page link if exists
        None if next page does not exists
    '''
    next_page = soup.find('a', {'class': 'gspr next'})
    try:
        return next_page['href']
    except:
        return None

def scrape_page(soup, idx):
    '''
    Scrape page for products and save them as a dictionary

    Returns:
        A dictionary of products
    '''
    products = {}
    prod_idx = idx

    for ultag in soup.find_all('ul', {'id': 'ListViewInner'}):

        for litag in ultag.find_all('li'):
            title = litag.find('a', {'class': 'vip'})
            if not title is None:
                products[prod_idx] = {}
                title_text = title.text
                if 'New listing' in title_text:
                    title_text = title_text.replace('New listing', '').lstrip()
                title_text.strip()
                products[prod_idx]['Title'] = title_text

            ul = litag.find('ul', {'class': 'lvprices left space-zero'})
            if not ul is None:
                for li in ul.find_all('li'):
                    if '$' in li.text and not 'shipping' in li.text.lower():
                        products[prod_idx]['Price'] = li.text.split()[0]
                    if 'shipping' in li.text.lower():
                        products[prod_idx]['Shipping'] = li.text.strip()

                prod_idx += 1
    return products, prod_idx

def table_print(products):
    '''
    Prints products in nice human-readable format
    '''
    print ("{:<8} {:<100} {:<15} {:<30}".format('Key', 'Product', 'Price', 'Shipping'))
    for k, v in products.items():
        try:
            t, p, s = v
            print ('{:<8} {:<100} {:<15} {:<30}'.format(k, products[k][t], products[k][p], products[k][s]))
        except ValueError:
            continue

def scrape_product(ebay_page):
    '''
    Main scraper
    '''
    products = {}
    idx = 0

    while not ebay_page is None:
        html_doc = urlopen(ebay_page)
        soup = BeautifulSoup(html_doc, 'html.parser')
        prod, idx = scrape_page(soup, idx)
        products.update(prod)
        ebay_page = find_next_page(soup)

    return products

def make_search_string(keywords):
    '''
    Make ebay search products string
    '''
    base = 'https://www.ebay.com/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw='
    end = '&_sacat=0'
    return '{0}{1}{2}'.format(base, '+'.join(keywords), end)

if __name__ == '__main__':
    print ('Project I Need a Cheap GPU (Ebay-Scraper in Python3) \n@Ludisposed \n')
    keywords = input('What do you want to search ebay for? ').split()

    # Make search string
    ebay_page = make_search_string(keywords)

    # Find all products
    products = scrape_product(ebay_page)

    # Print all products
    table_print(products)

Example

Project I Need a Cheap GPU (Ebay-Scraper in Python3)
@Ludisposed

What do you want to search ebay for? amd 580
Key      Product                                                                                Price           Shipping
0        XFX AMD Radeon RX 580 8GB GDDR5 GTR Black Edition PCI Express 3.0 New Sealed                         $305.00         +$37.83 shipping
1        MSI AMD Radeon RX 580 GAMING X 4G GDDR5 DVI/2HDMI/2Displayport PCI-Express Video                     $336.99         +$46.19 shipping
etc....


texts:
This is an iterative review.
The previous iteration can be found here.
The next iteration can be found here

I've now been programming in python for all of 4 hours.

At 70 lines it's rather verbose for a FizzBuzz. If you can suggest a more pythonic way to structure it, that would be awesome.

FizzBuzz.py

def print_fizz_buzz_output(start_end_pair, pair_list):

    start_num, end_num = start_end_pair
    for num in range(start_num, end_num + 1):
        has_divisor = False
        for divisor, text in pair_list:
            if num % divisor == 0:
                has_divisor = True
                print(text, end='')
        if has_divisor:
            print() # New Line
        else:
            print(str(num))

def ask_divisor_text_pairs():
    exit_flag = False
    while not exit_flag:
        divisor_is_valid = False
        while not divisor_is_valid:
            divisor = input('Divisor? ')
            try:
                divisor = int(divisor)
                divisor_is_valid = True
            except ValueError:
                print('Invalid input for divisor. Divisor must be a whole number. Please try again.')

        text = input('Text? ')
        yield (divisor, text)

        while True:
            continue_response = input('Input Another Divisor (y/n)? ')
            if continue_response in ('N', 'n'):
                exit_flag = True
                break
            elif continue_response in ('Y', 'y'):
                exit_flag = False
                break
            else:
                print('Invalid response. Please input "y" or "n"')

def ask_iteration_range() -> tuple:

    start_num_is_valid = False
    while not start_num_is_valid:
        start_num = input('Start Number? ')
        try:
            start_num = int(start_num)
            start_num_is_valid = True
        except ValueError:
            print('Invalid input for start number. Must be a whole number. Please try again.')

    end_num_is_valid = False
    while not end_num_is_valid:
        end_num = input('End Number? ')
        try:
            end_num = int(end_num)
            if end_num >= start_num:
                end_num_is_valid = True
            else:
                raise ValueError
        except ValueError:
            print('Invalid input for end number. Must be a whole number greater than or equal to the start number.'
                  ' Please try again.')

    return start_num, end_num

print_fizz_buzz_output(ask_iteration_range(),list(ask_divisor_text_pairs()))

Example Input/Output

Start Number? 1
End Number? 20
Divisor? 3
Text? Rattle
Input Another Divisor (y/n)? y
Divisor? 5
Text? Hiss
Input Another Divisor (y/n)? n
1
2
Rattle
4
Hiss
Rattle
7
8
Rattle
Hiss
11
Rattle
13
14
RattleHiss
16
17
Rattle
19
Hiss


texts: List of TV show episodes, with next/previous episode links for each entry

texts:
I'm a beginner yet, and currently I'm making a site about The Flash (just to practice), and yesterday I figured out this code to make my next/previous (episode) buttons work correctly. I'm glad I found a way after hours, but unfortunatelly it's pretty long.

So I'm wondering if someone could offer me a shorter code for this? How could I simplify it?

HTML code

I have 23 of these divs

<button id="episode1none">-</button>
<button id="episode1next" onclick="S1E2()">Next episode</button>

<button id="episode2previous" onclick="S1E1()">Previous episode</button>
<button id="episode2next" onclick="S1E3()">Next episode</button>

<button id="episode3previous" onclick="S1E2()">Previous episode</button>
<button id="episode3next" onclick="S1E4()">Next episode</button>

Css is not important, all I did there, that I set a default display:none; for these divs

and the JS

function S1E1(){
    document.getElementById("episode1buttons").style.display="block";
    document.getElementById("episode2buttons").style.display="none";
    document.getElementById("episode3buttons").style.display="none";
    document.getElementById("episode4buttons").style.display="none";
    document.getElementById("episode5buttons").style.display="none";

function S1E2(){
    document.getElementById("episode2buttons").style.display="block";
    document.getElementById("episode1buttons").style.display="none";
    document.getElementById("episode3buttons").style.display="none";
    document.getElementById("episode4buttons").style.display="none";
    document.getElementById("episode5buttons").style.display="none";

and there are more, but unecessary codes to them yet

I'm not sharing much code, because I don't want to make it too long

There are 23 functions like this, and in each of them, I set display:none; for 22 div-s, and display:block; for the one that contains the proper buttons that belong to the episode

And it's working, but it's pretty long(overall:529 lines of codes)

Feel free to ask if I missed something or you don't understand something!


texts: I am gathering all the Azure subnets for Central US and trying to filter out the smaller subnets that are part of the larger... Very slow

texts:
The goal of this code is to remove subnets from the list that are redundant (included in the larger ones)
It is VERY slow.  Wondering how it can be sped up.

At present, I’m not looking to optimize the “CheckSubnet()” function, which isn’t my code... It MAY be slow (or not) but I’m hoping that a critical analysis of the code that I HAVE presented can expose something obvious that I might have missed.

CheckSubnet Function taken from here: http://www.gi-architects.co.uk/2016/02/powershell-check-if-ip-or-subnet-matchesfits/

The function takes two CIDR notated subnets and returns an object that has two parts:

bool Condition which is TRUE if one of the subnets contains the other
string SomeotherMemeberThatIDontCareAbout

My code is as follows:

if ((Get-Module az.network) -eq $null)
{
    Import-Module az.network -Prefix AN
}
$Ranges = (Get-ANAzNetworkServiceTag -Location CentralUS).Values.Properties.AddressPrefixes | Sort-Object -Unique
#
#I think you need to be logged into your Azure Subscription for this to gather the results
#$Ranges returns over 8100 unique subnets
#
[System.Collections.ArrayList]$15 = $Ranges | ?{$_ -like "*/15"}
[System.Collections.ArrayList]$16 = $Ranges | ?{$_ -like "*/16"}
[System.Collections.ArrayList]$17 = $Ranges | ?{$_ -like "*/17"}
[System.Collections.ArrayList]$18 = $Ranges | ?{$_ -like "*/18"}
[System.Collections.ArrayList]$19 = $Ranges | ?{$_ -like "*/19"}
[System.Collections.ArrayList]$20 = $Ranges | ?{$_ -like "*/20"}
[System.Collections.ArrayList]$21 = $Ranges | ?{$_ -like "*/21"}
[System.Collections.ArrayList]$22 = $Ranges | ?{$_ -like "*/22"}
[System.Collections.ArrayList]$23 = $Ranges | ?{$_ -like "*/23"}
[System.Collections.ArrayList]$24 = $Ranges | ?{$_ -like "*/24"}
[System.Collections.ArrayList]$25 = $Ranges | ?{$_ -like "*/25"}
[System.Collections.ArrayList]$26 = $Ranges | ?{$_ -like "*/26"}
[System.Collections.ArrayList]$27 = $Ranges | ?{$_ -like "*/27"}
[System.Collections.ArrayList]$28 = $Ranges | ?{$_ -like "*/28"}
[System.Collections.ArrayList]$29 = $Ranges | ?{$_ -like "*/29"}
[System.Collections.ArrayList]$30 = $Ranges | ?{$_ -like "*/30"}
[System.Collections.ArrayList]$31 = $Ranges | ?{$_ -like "*/31"}
[System.Collections.ArrayList]$32 = $Ranges | ?{$_ -like "*/32"}

[System.Collections.ArrayList]$arrays= $15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32

for ($j =0;$j -le $arrays.Count-1;$j++)
{

    [System.Collections.ArrayList]$target = $arrays[$j+1]
    $target.Count
    $counter =1

    [System.Collections.ArrayList]$ArraySubset=$arrays
    [System.Collections.ArrayList]$arraySubset.RemoveRange($j+1,$arrays.Count-($j+1))
    foreach ($Big in $arraySubset)
    {
        $iteration=0
        $thecount=$target.Count
        Write-host "Array number: $counter  Remaining: $thecount"

        foreach ($largecidr in $Big)
        {
            for($i=$target.count-1;$i -ge 0;$i--)
            {
                $iteration++
                $checkval=CheckSubnet $largecidr $target[$i]
                if ($checkval.Condition -eq $true)
                {
                    Write-Host "Removing $($target[$i])"
                    $target[$i]
                    $target.RemoveAt($i)
                }
                if ($iteration % 100 -eq 0)
                {
                    Write-Host "Iteration $iteration"
                }
            }
        }
        $counter++
    }
    [System.Collections.ArrayList]$arrays= $15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32
}
$target.Count


texts: Print total number of vowel and consonant in an entered sentence

texts:
After asking my first question got a nice review on that. So, this is my solution for a different question checking edge cases and incorporating ideas given in that review.

  Question: Write a program to count total number of vowel and consonant characters present in an user entered sentence?

  Expected Output: If user inputs,

  1CHELSEA. 1FOOTBALL. 1CLUB. -> Vowel: 7, Consonant: 12
  a1?3e5i6!@o7^&*8)u -> Vowel: 5, Consonant: 0
  q1?32536!@47^&*8)p -> Vowel: 0, Consonant: 2

My solution works for all expected cases and from previous review suggestion I tried docstring, doctest, etc. So from this review I would like to know whether I am using those correctly or not, and if there's easier and better way to do this.

My solution:

from sys import exit

def counter(sentence):
    """Removes whitespaces, punctuation and capitalize every words.

    >>> counter("1CHELSEA. 1FOOTBALL. 1CLUB.")
    Vowel: 7, Consonant: 12

    >>> counter("a1?3e5i6!@o7^&*8)u")
    Vowel: 5, Consonant: 0

    >>> counter("q1?32536!@47^&*8)p")
    Vowel: 0, Consonant: 2

    """
    count_sentence = "".join(ch for ch in sentence if ch.isalpha()).upper()  # removes punctuation and numbers

    def find_total(count):
        """Check if character is present in vowel_list if present ++ in total"""
        vowel_list = ["A", "E", "I", "O", "U"]
        total = 0
        for character in count:
            if character in vowel_list:
                total += 1
        return total

    find_total(count_sentence)
    vowel_total = find_total(count_sentence)
    consonant_total = len(count_sentence) - vowel_total
    print("Vowel: {0}, Consonant: {1}".format(vowel_total, consonant_total))
    return

def main():
    """Checks for blank input."""
    entered_sentence = input("Please enter a sentence?\n>")
    if entered_sentence.strip() == "":
        exit("Program Terminated. (No input)")
    else:
        counter(entered_sentence)
    return

if __name__ == '__main__':
    import doctest
    doctest.testmod(main())

Lastly, please help me on returning from a function and separating printing part not been able to understand that.


texts: Convert float price to integer price without commas

texts:
My payment gateway wants the prices this way: "1050" instead of 10.50.
So I created this function:

https://repl.it/HgHI/3

def price_format_gateway(price):
    price = "{0:.2f}".format(price)
    price = price.split(".")
    try:
      if len(price[1]) > 2:
        decimals = str(price[1][0:2])
      else:
        decimals = price[1]
    except IndexError:
      pass

    return str(price[0]) + str(decimals)

price_format_gateway(10) # Expected -> 1000
price_format_gateway(10.1) # Expected -> 1010
price_format_gateway(10.15765) # Expected -> 1016

Is there another way more elegant, or cleaner? I just want to improve.


texts: Classifying top and bottom navigation links

texts:
The current code I have runs fine, but I'm curious about some other approaches to making this more DRY.

var topLinks = document.querySelectorAll('.navUtility-listItem a');

for(var i=0; i<topLinks.length; i++){
    if((topLinks[i].getAttribute('href').indexOf('a') > -1)){
        topLinks[i].className += ' top-nav-a';
    } else if (topLinks[i].getAttribute('href').indexOf('b') > -1){
        topLinks[i].className += ' top-nav-b';
    }
}

var bottomLinks = document.querySelectorAll('.footerMain-listPlatformItem a');

for(var i=0; i<bottomLinks.length; i++){
    if((bottomLinks[i].getAttribute('href').indexOf('a') > -1)){
        bottomLinks[i].className += ' bottom-nav-a';
    } else if (bottomLinks[i].getAttribute('href').indexOf('b') > -1){
        bottomLinks[i].className += ' bottom-nav-b';
    }
}


texts:
This weekend I've been having one heck of a time getting WPF Ribbon v4 working with MVVM and Prism (using unity). After much trial and error, I believe I have it working. I was hoping someone could take a look at it and give me some feedback.

RibbonRegionAdapter.cs

public class RibbonRegionAdapter : RegionAdapterBase<Ribbon>
{
    private Ribbon _ribbonTarget;

    public RibbonRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
        : base(regionBehaviorFactory)
    {

    }

    protected override void Adapt(IRegion region, Ribbon regionTarget)
    {
        _ribbonTarget = regionTarget;

        region.Views.CollectionChanged += delegate {
            foreach (RibbonTab tab in region.Views.Cast<RibbonTab>())
            {
                if (!_ribbonTarget.Items.Contains(tab))
                {
                    _ribbonTarget.Items.Add(tab);
                }
            }
        };
    }

    protected override IRegion CreateRegion()
    {
        return new SingleActiveRegion();
    }
}

BootStrapper.cs - To register our regionAdapter

    protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
    {
        RegionAdapterMappings mappings = base.ConfigureRegionAdapterMappings();

        if (mappings != null)
        {
            mappings.RegisterMapping(typeof(Ribbon), this.Container.Resolve<RibbonRegionAdapter>());
        }

        return mappings;
    }

CarRibbonTab.xaml

<ribbon:RibbonTab x:Class="CarManager.Modules.CarModule.Views.CarRibbonTab"
               xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             Header="Officers">
    <ribbon:RibbonGroup Header="New">

    </ribbon:RibbonGroup>
    <ribbon:RibbonGroup Header="Manage">
        <ribbon:RibbonButton Label="Make"
                                LargeImageSource="..\Resources\make.png" />
        <ribbon:RibbonButton Label="Inventory"
                                LargeImageSource="..\Resources\Inventory.png" />
        <ribbon:RibbonButton Label="Assignments" />
    </ribbon:RibbonGroup>
</ribbon:RibbonTab>

CarRibbonTab.cs - Code behind for the View

public partial class CarRibbonTab: RibbonTab
{
    public CarRibbonTab()
    {
        InitializeComponent();
    }
}

Shell.xaml - Just showing the ribbon control

<ribbon:Ribbon DockPanel.Dock="Top" Title="CarManager" prism:RegionManager.RegionName="RibbonRegion">
    <ribbon:Ribbon.ApplicationMenu>
        <ribbon:RibbonApplicationMenu SmallImageSource="Images\Icon.png">
            <ribbon:RibbonApplicationMenuItem Header="Exit"
                                              ImageSource="Images\ExitIcon.png"/>
        </ribbon:RibbonApplicationMenu>
    </ribbon:Ribbon.ApplicationMenu>

</ribbon:Ribbon>

CarModule.cs - registering the view with the region

    public class CarModule: IModule
    {
        private readonly IRegionManager  _regionManager;
        private readonly IUnityContainer _container;
        public MenuItemViewModel MenuItem;

        public CarModule(IUnityContainer container, IRegionManager regionManager)
        {
            _container     = container;
            _regionManager = regionManager;
        }

        public void Initialize()
        {
            //Ribbon
            _container.RegisterType<Object, CarRibbonTab>("CarRibbonTab");

            _regionManager.AddToRegion("RibbonRegion", _container.Resolve<CarRibbonTab>());
        }
    }


texts:
I have two inputs (TextBox) on my front end.

The following code parses them from their string representation to aDateTime object.  If it fails, it then sets default values.

DateTime dateFrom;
DateTime dateTo;
if (!DateTime.TryParse(txtDateFrom.Text, out dateFrom)) { dateFrom = DateTime.Today.AddDays(-7); }
if (!DateTime.TryParse(txtDateTo.Text, out dateTo)) { dateTo = DateTime.Now; }

However, the code looks bulky. Is there a better way to write it?


texts:
Project Euler #1:

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

Here is my solution:
public class MultipleFinder {

    private static final int MAX_NUMBER = 1000;
    private static final int[] MULTIPLES = new int[] { 3, 5 };

    public static void main(String[] args) {
        long time = System.nanoTime();
        int sum = 0;
        for(int multiple : MULTIPLES) {
            sum += triangle((MAX_NUMBER - 1) / multiple) * multiple;
        }
        sum -= triangle((MAX_NUMBER - 1) / (MULTIPLES[0] * MULTIPLES[1])) * (MULTIPLES[0] * MULTIPLES[1]);
        System.out.println("Result: " + sum + "\nTime used for calculation in nanoseconds: " + (System.nanoTime() - time));
    }

    private static int triangle(int i) {
        return (i + 1) * i / 2;
    }

}

Output:

 Result: 233168
 Time used for calculation in nanoseconds: 51764

Questions:

Is there a way to increase efficiency?
Is there a way to change the code so that I get the correct solution when I add a multiple?


texts: Python Solution for Project Euler #2 (Fibonacci Sums)

texts:
I'm a fairly new programmer (just started yesterday!). I decided to tackle Project Euler #2 today, as I did #1 yesterday without many problems. I came up with what seems to me to be a working solution, but I feel like I did it in an exceedingly ugly way. Could anyone suggest improvements to my code and/or logic?

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

fib = 1
fib2 = 2
temp = 0
total = 0

while temp <=4000000:
    temp = fib2
    if temp % 2 == 0:
        total += temp
    temp = fib + fib2
    fib = fib2
    fib2 = temp

print total

I just sort of used my temp variable as a holding ground for the results, and then juggled some variables around to make it do what I wanted... Seems like quite a mess. But it does result in 4613732, which seems to be correct!


texts:
Please comment on the same. How can it be improved?

Specific improvements I am looking for:

Memory leaks
C++ style
Making code run faster
RAII

#include<iostream>
#include<algorithm>

template <typename T>
class Stack {
private:
    T* array_;
    int length_;
    T* last_;
    void expandArray();

public:
    Stack(int length = 8) :
        array_(new T[length]),
        length_(length),
        last_(array_)
    {}

    Stack<T>& push(const T&);
    Stack<T>& pop();
};

template<typename T>
void Stack<T>::expandArray() {
    T* array_temp = new T[length_ << 1];
    std::copy(array_, array_ + length_, array_temp);
    std::swap(array_, array_temp);
    delete[] array_temp;
    last_ = array_ + length_ - 1;
    length_ <<= 1;
}

template<typename T>
Stack<T>& Stack<T>::push(const T& data) {
    if (last_ == (array_ + length_ - 1)) {
        expandArray();
    }
    last_[0] = data;
    last_++;
    std::cout << "[" << data << "] pushed." << std::endl;
    return *this;
}

template<typename T>
Stack<T>& Stack<T>::pop() {
    if(array_ != last_) {
        last_--;
        std::cout << "[" << last_[0] << "] popped." << std::endl;
    } else {
        std::cout << "Nothing to pop." << std::endl;
    }
    return *this;
}

int main() {
    Stack<std::string> s;
    s.push(std::string("a"))
     .push(std::string("b"))
     .push(std::string("c"))
     .push(std::string("d"));
    s.pop().pop().pop().pop().pop();
}


texts:
I am trying to build a REST API with express router, which contains of nested sub routes. I have mounted these sub routes in my index.js file.

I have defined it as follows:

// Mounted routes
app.use('/api/v1/Project', new ProjectRouter().routes);
app.use('/api/v1/Project/:projectId/Context', new ContextRouter().routes);
app.use('/api/v1/Project/:projectId/Context/:contextId/Question', new QuestionRouter().routes);
app.use('/api/v1/Project/:projectId/Context/:contextId/Question/:questionId/Answer', new AnswerRouter().routes);

I want to arrange my routes revolved around the functionality and being more complaint towards REST standards.

In the case the route prefix /api/v1/Project/ is being repeated over and over again.

Is there some best practice to minimize the redundant routes by prefixing?


texts:
I have a List<string> being stored in my cache with about 600K members.  I want this to act as the backend for an Ajax autocomplete box.  It's accessible through my model:

public static List<string> GetProducts()
{
    var cached = HttpContext.Current.Cache["MyApp-Products"];
    if (cached == null)
    {
        UpdateCache();
        return GetProducts();
    }
    return ((List<string>)cached);
}

My ajax call uses this method to get it's data:

[HttpPost]
public JsonResult ProductSearch(string term)
{
    return Json(MyModel.GetProducts()
        .Where(s => s.ToUpper().StartsWith(term.ToUpper()))
        .OrderBy(s => s)
        .Take(5)
        .ToList<string>()
    );
}

The problem is, this Ajax call to ProductSearch() is waiting 2.09 seconds for a response. I'm doing the same with other objects in my model that have smaller list sizes and they respond in 35-125ms (which is acceptable).

So, I believe my performance issue is somewhere in accessing the list.  Is there a faster way to access this list besides the Linq code that I'm using, or just a better way to use Linq?


texts: Reading 8 divs across the screen depending on assignment time

texts:
This code takes 8 divs and races them across the screen depending on which time value the div was assigned. How can I have coded this better so my code doesn't look so amateurish?

I know I should have used something other than a hard coded 8 in my for-loop, but timeArray.length is unavailable since I am removing items from the array with splice.

$(document).ready(function() {
var timeArray = new Array(3,4,5,6,7,8,9,10);
var shortestTime = timeArray[7];
var fastestPony = {};
var index;

var pony = {
    name: "pony",
    raceTime: -1,
    selected: ""
};

//change the color of the pony when the user clicks on it
$('.pony').bind('click', function() {
    $('.pony').removeClass('selectedPony');
    $(this).addClass('selectedPony');

    //get the pony that the user selected
    pony.selected = $(this);
});

$('#startButton').click(function() {
    if (pony.selected == "") {
        alert("Please click the pony you think will win the race.");
    }
    else {
        for (i = 1; i <= 8; i++) {
           //get a random number from the timeArray
            index = Math.floor(Math.random() * timeArray.length);
            pony.raceTime = timeArray[index];

            //pull the random race time number out of the array
            //so it can't be assigned to another horse
            timeArray.splice(index, 1);

            //get the fastest pony
            if (pony.raceTime < shortestTime) {
                shortestTime = pony.raceTime;
                fastestPony = $('#pony' + i);
            }

            //award the winner after the ponies have reached the finish line
            if (i == 8) {
                fastestPony.addClass('winner').append(' - Winner!');
            }

            //send the horses on their way to race!
            $('#pony' + i).animate({left: '320px'}, pony.raceTime * 1000);
        }
    }
});

//reset the ponies back to the starting line by reloading the page
$('#resetButton').click(function() {
    document.location.reload(true);
});
});


texts: Handling thread interruptions in a directory iterator

texts:
This code is code written on a whim to help $someindividual asking for such a thing on $somechatmedium; what is needed is a way, in Java, to provide an Iterator over Path objects which must only be directories, recursively, and where the number of returned instance number in some sufficient quantities to trigger an OutOfMemoryError if eagerly populated.

So, I came up with this (imports omitted for "brevity"):

public final class LazyDirectoryIterator
    implements Iterator<Path>, Closeable
{
    private static final int QUEUE_SIZE = 5;
    private static final long TIMEOUT_QUANTITY = 100L;
    private static final TimeUnit TIMEOUT_UNIT = TimeUnit.MILLISECONDS;

    private final ExecutorService executor
        = Executors.newSingleThreadExecutor();
    private final BlockingQueue<Path> queue
        = new ArrayBlockingQueue<>(QUEUE_SIZE);

    private Path nextPath;
    private boolean needNext = true;

    public LazyDirectoryIterator(final Path baseDir)
    {
        executor.submit(new Runnable()
        {
            @Override
            public void run()
            {
                try {
                    Files.walkFileTree(baseDir, new CustomVisitor());
                } catch (IOException ignored) {
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

    @Override
    public boolean hasNext()
    {
        try {
            if (needNext) {
                nextPath = queue.poll(TIMEOUT_QUANTITY, TIMEOUT_UNIT);
                needNext = false;
            }
            return nextPath != null;
        } catch (InterruptedException ignored) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public Path next()
    {
        if (!hasNext())
            throw new NoSuchElementException();
        needNext = true;
        return nextPath;
    }

    @Override
    public void remove()
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public void close()
        throws IOException
    {
        executor.shutdownNow();
    }

    private final class CustomVisitor
        extends SimpleFileVisitor<Path>
    {
        @Override
        public FileVisitResult preVisitDirectory(final Path dir,
            final BasicFileAttributes attrs)
            throws IOException
        {
            try {
                queue.put(dir);
                return FileVisitResult.CONTINUE;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IOException("timeout", e);
            }
        }
    }
}

There are three places here where I purposely choose to set the interrupt flag:

in the Runnable walking the file tree, if I encounter an I/O exception (I'm really not sure about this one; but a Runnable can't throw);
in the FileVisitor itself, if I can't push onto the queue;
in .hasNext() if trying and retrieving an element from the queue times out.

It is expected that this Iterator will never run in more than one thread, which is why needNext and nextPath are not volatile. Note that in the three usages above, the two first are in another thread which is spawned from the constructor.

Note: up to Java 7, cannot use Java 8.

So, is my handling of InterruptedExceptions, and my uses of Thread.currentThread().interrupt() correct?


texts: Tidying scaffolded Rails controller spec with subject/let

texts:
I was just looking at a standard scaffolded Rails controller spec, and tried to get it to use subject or let blocks, and failed miserably ... can subject or let tidy controller specs the same as it would a model spec?

require 'spec_helper'

describe ProjectsController do

  def valid_attributes
    {}
  end

  def valid_session
    {}
  end

  before(:each) do
    @project = Project.create! valid_attributes
  end

  describe "GET index" do
    it "assigns all projects as @projects" do
      get :index, {}, valid_session
      assigns(:projects).should eq([@project])
    end
  end

  describe "GET show" do
    it "assigns the requested project as @project" do
      get :show, {:id => @project.to_param}, valid_session
      assigns(:project).should eq(@project)
    end
  end

  #etc
end


texts: Any side effects from this Python logging code?

texts:
def _getCallerLogger():
    caller = inspect.currentframe().f_back.f_back
    name = "{}-{}".format(caller.f_globals['__name__'], caller.f_code.co_name )
    logger = logging.getLogger(name)
    return logger

log = lambda msg : _getCallerLogger().debug(msg)
info = lambda msg: _getCallerLogger().info(msg)
warning = lambda msg: _getCallerLogger().warning(msg)
error = lambda msg: _getCallerLogger().error(msg)
critical = lambda msg: _getCallerLogger().critical(msg)

I have the above logging code in my application so I can just call log from anywhere and it will print the file and where the log method was called from.

Would there be anything wrong with this in the long run?


texts: Accessing deep properties and methods of an object with using a path

texts:
I have a code snippet that I have been using and works. It is used a lot in my application and I need to speed it up. Is there a faster better way of deep accessing objects using a string path. It needs to able to access properties and methods, see my examples below:

     function get(obj, path) {
        var paths = path.split('.'),
        curProp = obj;
        for(var i=0;i<paths.length;i++){
            if (!curProp[paths[i]]) return
            curProp = (typeof curProp[paths[i]] !== "function") ? curProp[paths[i]] : curProp[paths[i]]() ;
        }
        return curProp;
    }

The snippet gets the property via the path for the object passed

var obj = {contact:{name:"john"}};
console.log(get(obj, "contact.name"));

If the object has a method that returns an object it can return that too

var obj = {contact:function(){return {name:"john"}}};
console.log(get(obj, "contact.name"));


texts: LINQ query using StartsWith and Contains to limit the results for an autocomplete field

texts:
As a source for a jquery-ui autocomplete field, I've written this action:

public ActionResult Autocomplete(string term)
{
    List<Relation> relations =
        db.Relation
            .Where(l => l.AdministrationId == Helpers.Session.AdministrationId &&
                        l.IsSupplier == true)
            .ToList();

    term = term.ToLowerInvariant();

    List<string> results = new List<string>();

    foreach (Relation r in relations) {
        string name = r.Name.ToLowerInvariant();

        if (name.StartsWith(term) || name.Contains(term)) {
            results.Add(name);
        }
    }

    results = results.OrderBy(l => l).Take(5).ToList();

    return Json(results, JsonRequestBehavior.AllowGet);
}

Since this is very verbose and probably far from optimized, I'd like to know what I can improve.

I've tried to put it all in a single LINQ query, like the code below. However, LINQ will try to interpret everything as extension methods and throw an error (ToLowerInvariant() and StartsWith()).

term = term.ToLowerInvariant();

IEnumerable<string> suppliers =
    db.Relations
        .Where(l => l.AdministrationId == Helpers.Session.AdministrationId &&
                    l.IsSupplier== true &&
                    (l.Name.ToLowerInvariant().StartsWith(term) ||
                     l.Name.ToLowerInvariant().Contains(term)))
        .Select(l => l.Name)
        .OrderBy(l => l)
        .Take(5);

What I'm looking for is a way to improve the first code snippet. It looks very verbose now and I'm pretty sure it's far from optimized when handling a lot of requests and when I have lots of rows in my database.


texts:
This is the first time I've tried this. I'd like some feedback on how I did, including any bad practice warnings. For example is it a really bad idea to allow the code to recreate the table if it doesn't "think" it exists? Would it be better to simply create the table once in a different file?

<?php

/*
Database and mail functionality
*/

// get user credentials
$config = parse_ini_file('../config.ini'); // path may vary depending on setup

// Create connection
$conn = new mysqli('localhost', $config['username'], $config['password'],$config['dbname']);

// Check connection
if ($conn->connect_error){
    die('Connection failed. ' . $conn->connect_error);
}

// if table not made yet, create it
if(!$conn->query ("DESCRIBE visitors")) {
    // sql to create table
    $sql = 'CREATE TABLE visitors(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(30) NOT NULL,
        email VARCHAR(50) NOT NULL,
        message VARCHAR(500),
        reg_date TIMESTAMP
    )';

    if (!$conn->query($sql)){
        die ('Sorry there was an error. Please try again later.');
    }

}

//insert data into table
//clean data for SQL query
$name = mysqli_real_escape_string($conn, $data['name']);
$email = mysqli_real_escape_string($conn, $data['email']);
$message = mysqli_real_escape_string($conn, $data['message']);

$sql = "INSERT INTO visitors (name, email, message)
    VALUES ('$name', '$email', '$message')";

if ($conn->query($sql) === TRUE) {
    $usrMsg = 'Thank you we\'ll be in touch when we have some news';
} else {
    die ("Sorry, there was an Error. Please try again later.");
}

// close connection
$conn->close();

// email
// addresses and default subject
$to = ''; // add details
$from = ''; // add details
$subject = 'New form entry on website';

// prepare message variables - !not sure how to make quotes etc. display properly in email body
$message = wordwrap($data['message']);
$body = <<<_END
Name: {$data['name']}
Email: {$data['email']}
Message: $message
_END;

// send
mail($to, $subject, $body, $from);

?>


texts: Supplying parameterless callback to function expecting void * param

texts:
I have to register different callback functions to a scheduler. The callback signature defines a void * parameter. Some callbacks don't use a parameter. This works, but is it clean?
I expected at least an incompatible pointer type warning for the missing cast on the parameterless call which I actually get when using a function to register the callback but the compiler doesn't complain about this example.
#include <stdio.h>

typedef void (* cb)(void *);

void noparams(void) {
    printf("noparams\n");
}

void params(void * param) {
    char * s = param;
    printf(s);
}

void call(cb cbk, void * ctx) {
    cbk(ctx);
}

int main(void) {
    void * context = 0;
    call(noparams, context); // warning expected

    char str[] = "params\n";
    call(params, str);

    return 0;
}

ideone


texts:
As an exercise in learning Haskell, I implemented a simple key value store, where you can put and get values (as ByteStrings). (For reference this is inspired by this short note describing bitcask's design). I'd appreciate feedback on any aspect (style, 'haskellyness', library usage etc.) of my implementation:

{-# LANGUAGE OverloadedStrings #-}

module KV (
    evalKV,
    putKV,
    getKV,
    liftIO
) where

import Prelude hiding (mapM)
import Data.Traversable (mapM)
import Control.Monad (liftM, liftM2)
import Control.Monad.State (StateT, evalStateT, get, put, liftIO)
import qualified System.IO as IO
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as L
import qualified Data.Binary as B
import qualified Data.Binary.Get as G
import qualified Data.Map as M

type Header    = (Integer, Integer)
               -- keysize  valuesize

type ValueInfo = (Integer, Integer)
               -- offset valuesize

type Key       = ByteString

type Pair      = (Key, ValueInfo)

type Index     = M.Map Key ValueInfo

data KVState = KVState
    { kvHandle :: IO.Handle
    , kvIndex  :: Index
    } deriving (Show)

type KV a = StateT KVState IO a

evalKV :: FilePath -> KV a -> IO a
evalKV p s = IO.withBinaryFile p IO.ReadWriteMode $ \h -> do
    i <- readIndex h
    evalStateT s $ KVState h i

putKV :: ByteString -> ByteString -> KV ()
putKV k v = do
    (KVState h i) <- get
    vi <- liftIO $ writePair h k v
    let i' = M.insert k vi i
    put $ KVState h i'

getKV :: ByteString -> KV (Maybe ByteString)
getKV k = do
    (KVState h i) <- get
    liftIO $ lookupKV h i k

readHeader :: ByteString -> (Header, Integer)
readHeader c = (h, fromIntegral o)
    where (h, _, o) = G.runGetState B.get c 0

readAt :: IO.Handle -> Integer -> Integer -> IO ByteString
readAt h o sz = do
    IO.hSeek h IO.AbsoluteSeek o
    L.hGet h $ fromIntegral sz

readPair :: IO.Handle -> Integer -> IO (Maybe Pair)
readPair h o = do
    IO.hSeek h IO.AbsoluteSeek o
    b <- L.hGet h 10 -- TODO: qualify this arbitrary number
    if L.null b
        then return Nothing
        else do
            let ((ksz, vsz), l) = readHeader b
            k <- readAt h (o + l) ksz
            return $ Just (k, (o + l + ksz, vsz))

writePair :: IO.Handle -> ByteString -> ByteString -> IO ValueInfo
writePair h k v = do
    IO.hSeek h IO.SeekFromEnd 0
    let l = fromIntegral . L.length
    let vsz = l v
    let t = (l k, vsz) :: Header
    L.hPut h (B.encode t)
    L.hPut h k
    p <- IO.hTell h
    L.hPut h v
    return (p, vsz)

readIndex :: IO.Handle -> IO Index
readIndex h = liftM M.fromList $ ri 0
    where ri o = do
            mp <- readPair h o
            case mp of
                Just p@(k, (vo, vsz)) -> do
                    t <- ri (vo + vsz)
                    return $ p : t
                Nothing -> return []

lookupKV :: IO.Handle -> Index -> ByteString -> IO (Maybe ByteString)
lookupKV h i k = mapM r mv
    where r = uncurry $ readAt h
          mv = M.lookup k i

And usage would look like:

{-# LANGUAGE OverloadedStrings #-}

import KV
import Data.ByteString.Lazy.Char8

main = evalKV "test" $ do
    u <- getKV "asdf"
    liftIO $ print u
    putKV "asdf" "qwer"
    v <- getKV "asdf"
    liftIO $ print v

Which would result in the following output:

Nothing
Just (Chunk "qwer" Empty)

One concern I have, in particular, is that I've currently made no consideration for allowing concurrent access to the store, if people have opinions on the best approach for this I'd be really interested to hear them. I have this concern as, if I get time to work on this some more, my intention is to create a way to access the store over HTTP/TCP.


texts:
I have this method that lists database objects:

public List<Person> getPersons(int offset, int limit) {
    return jdbcTemplate.query("SELECT * FROM `Person`" + (limit > 0 ? " LIMIT " + (offset > 0 ? offset + "," : "") + limit : "")+" ORDER BY `created` DESC");
}

It looks confusing, so how do I clean up the method?