texts:
My program is complete and running, but I would like second opinions on how I can make it more efficient. The program prompts the user for the message and the amount s/he would like to shift the letters. For the implementation part, is there another "faster" way to do it instead of having the if else if statements to run through and test my characters?

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

string encodeCaesarCipher(string str, int shift);

int main()
{
    string str, encoded_string;
    int shift;

    cout << "This program encodes a message in Caesar Cipher. \n\n";

    cout << "Please enter a message: ";
    getline(cin, str);

    cout << "\nHow many times do you want to shift the letter(s) in the message? ";
    cin >> shift;

    while (shift < 1)
    {
        cout << "You have entered an invalid number. \n";
        cout << "Please try again. \n";
        cout << "Enter a proper number for the amount of letter shifting: ";
        cin >> shift;
    }

    encoded_string = encodeCaesarCipher(str, shift);

    cout << "\nEncoded message: " << encoded_string << "\n\n";

    system("PAUSE");

    return 0;
}

string encodeCaesarCipher(string str, int shift)
{
    string temp = str;
    int length;

    length = (int)temp.length();

    for (int i = 0; i < length; i++)
    {
        if (isalpha(temp[i]))
        {
            for (int j = 0; j < shift; j++)
            {
                if (temp[i] == 'z')
                {
                    temp[i] = 'a';
                }
                else if (temp[i] == 'Z')
                {
                    temp[i] = 'A';
                }
                else
                {
                    temp[i]++;
                }
            }
        }
    }

    return temp;
}


texts: Redux actions inside a container for a calculator

texts:
I used to import all the actions in the container's argument which looks messy (I put a comment below where I do it in that way). I want to know if there is a better approach when using actions with react-redux. Should I use alias, and if I use alias is there any impact on the performance?

import React from 'react';
import Proptypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import {
  selectNumber,
  selectOperator,
  solverOperator,
  initialize,
  addDecimal,
  clearEntry,
  changeSign,
} from '../actions/index';

const ButtonsContainer = ({ selectNumber, selectOperator, solverOperator, initialize, addDecimal, clearEntry, changeSign, }) => (  // HERE I PUT ALL THE ACTIONS AS ARGUMENT
  <React.Fragment>
    <button value="AC" onClick={() => initialize()} className="buttonStyle ac" type="submit">AC</button>
    <button value="CE" onClick={() => clearEntry()} className="buttonStyle ce" type="submit">CE</button>
    <button value="CHANGE" onClick={e => changeSign(e.target)} className="buttonStyle posneg" type="submit">+/-</button>
    <button value="/" onClick={e => selectOperator(e.target)} className="buttonStyle divide" type="submit">/</button>
    <button value="7" onClick={e => selectNumber(e.target)} className="buttonStyle seven" type="submit">7</button>
    <button value="8" onClick={e => selectNumber(e.target)} className="buttonStyle eight" type="submit">8</button>
    <button value="9" onClick={e => selectNumber(e.target)} className="buttonStyle nine" type="submit">9</button>
    <button value="*" onClick={e => selectOperator(e.target)} className="buttonStyle multiply" type="submit">X</button>
    <button value="4" onClick={e => selectNumber(e.target)} className="buttonStyle four" type="submit">4</button>
    <button value="5" onClick={e => selectNumber(e.target)} className="buttonStyle five" type="submit">5</button>
    <button value="6" onClick={e => selectNumber(e.target)} className="buttonStyle six" type="submit">6</button>
    <button value="-" onClick={e => selectOperator(e.target)} className="buttonStyle minus" type="submit">-</button>
    <button value="1" onClick={e => selectNumber(e.target)} className="buttonStyle one" type="submit">1</button>
    <button value="2" onClick={e => selectNumber(e.target)} className="buttonStyle two" type="submit">2</button>
    <button value="3" onClick={e => selectNumber(e.target)} className="buttonStyle three" type="submit">3</button>
    <button value="+" onClick={e => selectOperator(e.target)} className="buttonStyle plus" type="submit">+</button>
    <button value="0" onClick={e => selectNumber(e.target)} className="buttonStyle zero" type="submit">0</button>
    <button value="." onClick={e => addDecimal(e.target)} className="buttonStyle dot" dangerouslySetInnerHTML={{ __html: '&middot' }} type="submit" />
    <button value="=" onClick={e => solverOperator(e.target)} className="buttonStyle equal" type="submit">=</button>
  </React.Fragment>
);

ButtonsContainer.propTypes = {
  selectNumber: Proptypes.func.isRequired,
  selectOperator: Proptypes.func.isRequired,
  solverOperator: Proptypes.func.isRequired,
  initialize: Proptypes.func.isRequired,
  addDecimal: Proptypes.func.isRequired,
  clearEntry: Proptypes.func.isRequired,
  changeSign: Proptypes.func.isRequired,
};

const mapDispatchToProps = dispatch => bindActionCreators({
  selectNumber,
  selectOperator,
  solverOperator,
  initialize,
  addDecimal,
  clearEntry,
  changeSign,
}, dispatch);


texts: Updating the UI without leaking the context after an Android AsyncTask finishes

texts:
In the past I always did AsyncTasks as private inner classes. The tutorials I found still recommend this (see here, here, here, and here). However, this has the potential to leak the context. Now Android Studio even warns about this and recommends making the class static.

I followed this advice. Here is my code for a sample project I made that updates the UI after a long running task finishes. Since the AsyncTask is static, I pass in a weak reference to the Activity and get the particular UI view that I need to update.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new MyTask(this).execute();
    }

    private static class MyTask extends AsyncTask<Void, Void, Void> {

        private WeakReference<Context> contextReference;

        MyTask(Context context) {
            contextReference = new WeakReference<>(context);
        }

        @Override
        protected Void doInBackground(Void... params) {

            try {
                Thread.sleep(2000);
                // in the future I will do other long running tasks here,
                // like updating a database. I hope it is acceptable to
                // to use sleep for now. This was an actual project that
                // I made and tested myself.
            } catch (InterruptedException e) {
                Log.e("TAG", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            AppCompatActivity context = (AppCompatActivity) contextReference.get();
            if(context != null) {
                TextView textView = context.findViewById(R.id.textview);
                textView.setText("task finished");
            }
        }
    }
}

Concerns

The above code works fine, even though it is a pain to not just update an Activity member variable directly. Also, since I don't see any tutorials or the documentation showing AsyncTask working like this, I don't know if this is the pattern I should follow from now on.


texts: Whiten black contours around a skewed image

texts:
I have this image:

I want to whiten the black contours (borders) around it without affecting the image content.
Here is the code I used:

import cv2
import numpy as np
import shapely.geometry as shageo

img = cv2.imread('filename.jpg')

# get the gray image and do binaryzation
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray[gray < 20] = 0
gray[gray > 0] = 255

# get the largest boundry of the binary image to locate the target
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours[0])
box = cv2.boxPoints(rect)
box = np.int0(box)

poly = shageo.Polygon(box)
h, w = img.shape[:2]
ind = np.zeros((h, w), np.bool)

# check if the point is inside the target or not
for i in range(h):
    for j in range(w):
        p = shageo.Point(j, i)
        if not p.within(poly):
            ind[i, j] = True

# whiten the outside points
img[ind] = (255, 255, 255)
cv2.imwrite('result.jpg', img)

Here is the result:

The code works fine, but it's very slow because of the for loops.

Any suggestions how to avoid the for loops or to make them faster?


texts: Filter to block duplicate POST submission on server side

texts:
I am working on a JSF 1.1 webapp. Lots of POST request take some time and users have the bad habit of clicking again when it takes too long. I am planning to target all the long running processes and add an overlay to prevent this, but it will take some time. Before it is finished, I am asked to setup a quickwin on server side do block double submission of the same POST request.

My comprehension of the mechanisms is that when the users clicks on the submit button a second time, the browser aborts the first post submission (as I can see it in Firebug), but on server side both are processed in parallel. So in order to avoid to process two times the same request while sending the expected response to the client, I am planning to set up a Filter on incoming POST request with the following process:

Suppose someone sends for example 3 exact same POST requests Rq1, Rq2, Rq3 with the corresponding responses being Rs1, Rs2, Rs3. We want to block Rq2 and Rq3 while Rq1 is processing. When Rs1 is ready we will block everything while we are copying Rs1 into Rs3. Then we send Rs3 back to the client and once this is done, we terminate Rs1 and Rs2 by sending back a 200 (they should have already been aborted on client side anyway)

Here is the implementation I thought about. The synchronization stuff has purposely been skipped as the filter is quite heavy already. I need reviews about this because I really feel like having imagined a really dirty thing.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession(false);
    if (session == null || notAPost(request)) {
        chain.doFilter(request, response);
        return;
    }

    Map<String, String> hashTokenMap = (Map<String, String>) session.getAttribute("HASH_TOKEN_MAP");
    Map<String, HttpServletResponse> hashResponseMap = (Map<String, HttpServletResponse>) session
            .getAttribute("HASHS_RESPONSE_MAP");
    String requestHash = makeCheckSumString(request);
    String token = generateUniqueToken();

    // double POST case
    if (hashTokenMap.containsKey(requestHash)) {
        hashTokenMap.put(requestHash, token); // this will allow the previous POST to understand that it has been overriden
        // wait until we detect that either the response is available or has already been processed
        while (hashResponseMap.get(requestHash) == null && hashTokenMap.get(requestHash) != null) {
            sleep(1000);
        }

        // this is the last submitted post => we copy the response and return it
        if (token.equals(hashTokenMap.get(requestHash))) {
            HttpServletResponse realResponse = hashResponseMap.remove(requestHash);
            copyResponses(realResponse, res);
            hashTokenMap.remove(requestHash);
            return;
        }
        // there was another post submitted inbetween
        else {
            // since we have been overriden, lets wait till other business is finished
            while (hashTokenMap.get(requestHash) != null) {
                sleep(1000);
            }
            res.sendError(HttpServletResponse.SC_OK, "Already replied");
            return;
        }
    }
    // first POST case
    else {
        hashTokenMap.put(requestHash, token);
        chain.doFilter(request, response);

        // there was no double POST
        if (token.equals(hashTokenMap.get(requestHash))) {
            return;
        }
        // some other POST has been submitted during processing
        else {
            hashResponseMap.put(requestHash, res);
            while (hashResponseMap.get(requestHash) != null) {
                sleep(1000);
            }
            res.sendError(HttpServletResponse.SC_OK, "Already replied");
            return;
        }
    }
}


texts:
This is my first "useful" Haskell program. It's invoked with filenames as arguments where the last filename is the destination to which the content of all other files will be concatenated. As far as I can tell it's working but I don't like the two returns in the main function and would like to know how I can get rid of the do in the concatFiles function.

import System.Environment (getArgs)
import System.IO (hClose, hPutStr, openFile, IOMode(WriteMode))

concatFiles :: FilePath -> [FilePath] -> IO ()
concatFiles destination files = do
    writeHandle <- openFile destination WriteMode
    mapM (writeToDestination writeHandle) files
    hClose writeHandle
    where
        writeToDestination writeHandle file =
            hPutStr writeHandle =<< readFile file

main = do
    args <- getArgs
    argc <- return $ length args
    destination <- return $ last args
    concatFiles destination $ take (argc-1) args


texts: VBA, Transferring of Data from one File to another

texts:
I have this code that:

Clears my worksheet from row 12 and onward in Workbook A
Opens a new file Workbook B
Copys the sheet to my Workbook A. and Close Workbook B
Renames sheet in Workbook A
Transfers data from New Sheet to another Tab.

This seems to take me 10 minutes+, it is roughly 35k Rows.
Is there a faster way of doing this?
Thanks.
    Sub Mainsub()

    Worksheets("Main Data").Rows("12:" & Rows.Count).ClearContents

    'Copy data from the CM File to Template
    Application.ScreenUpdating = False

    'Open CM file
    Set MainDataCM = Workbooks.Open(Sheets("Input").Range("B16") & Sheets("Input").Range("B19"))
    'Copy main data tab to EPM file workbook
    MainDataCM.Sheets("Main Data").Copy After:=ThisWorkbook.Sheets(1)
    'Close CM Comm file
    MainDataCM.Close SaveChanges:=False
    Application.ScreenUpdating = True

    Sheets("Main Data (2)").Name = "CM_MainData"

    Worksheets("CM_MainData").Visible = False

    'Read the CM_MainData tab and copy the required columns in the MainData tab
    Dim k As Long
    k = Sheets("CM_MainData").Range("A1", Sheets("CM_MainData").Range("A1").End(xlDown)).Rows.Count
    Debug.Print (k)

    i = 12
    j = 2

    While j <= k
        Sheets("Main Data").Range("A" & i) = Sheets("CM_MainData").Range("A" & j)
        Sheets("Main Data").Range("B" & i) = Sheets("CM_MainData").Range("B" & j)
        Sheets("Main Data").Range("C" & i) = Sheets("CM_MainData").Range("C" & j)
        Sheets("Main Data").Range("D" & i) = Sheets("CM_MainData").Range("D" & j)
        Sheets("Main Data").Range("E" & i) = Sheets("CM_MainData").Range("E" & j)
        Sheets("Main Data").Range("F" & i) = Sheets("CM_MainData").Range("F" & j)
        Sheets("Main Data").Range("G" & i) = Sheets("CM_MainData").Range("G" & j)
        Sheets("Main Data").Range("H" & i) = Sheets("CM_MainData").Range("H" & j)
        Sheets("Main Data").Range("I" & i) = Sheets("CM_MainData").Range("I" & j)
        Sheets("Main Data").Range("J" & i) = Sheets("CM_MainData").Range("J" & j)
        Sheets("Main Data").Range("K" & i) = Sheets("CM_MainData").Range("K" & j)
        Sheets("Main Data").Range("L" & i) = Sheets("CM_MainData").Range("L" & j)
        Sheets("Main Data").Range("M" & i) = Sheets("CM_MainData").Range("M" & j)
        Sheets("Main Data").Range("N" & i) = Sheets("CM_MainData").Range("N" & j)
        Sheets("Main Data").Range("O" & i) = Sheets("CM_MainData").Range("O" & j)
        Sheets("Main Data").Range("P" & i) = Sheets("CM_MainData").Range("P" & j)

        i = i + 1
        j = j + 1
    Wend

    Worksheets("Input").Activate
    Worksheets("Input").Select

    MsgBox "Step 1 Completed"

End Sub


texts: Initializing a std::array from a recursive template computation

texts:
I wrote this code for an answer over on SO.  I suspect it's possible to clean it up a bit, particularly the base-case specialization for FactorialArray, which is repetitive and contains odd bits (for instance: why double curly braces? because clang complains about un-braced subobject initializers otherwise...)

Any and all suggestions are appreciated.  Note that Factorial is separate from FactorialArray for pedagogical clarity; I realize this makes the compile-time calculation O(N2) unless the compiler is clever enough to memoize it.

#include <iostream>
#include <cinttypes>
#include <array>

using std::uint64_t;

// Helper template that computes the factorial of one integer
template<uint64_t I> struct Factorial
{ static constexpr uint64_t value = I * Factorial<I-1>::value; };

template<> struct Factorial<0> { static constexpr uint64_t value = 1; };

// FactorialArray recursively assembles the desired array as a variadic
// template argument pack from a series of invocations of Factorial
template<uint64_t I, uint64_t... Values> struct FactorialArray
  : FactorialArray<I-1, Factorial<I>::value, Values...>
{};

// and in the base case, initializes a std::array with that pack
template<uint64_t... Values> struct FactorialArray<uint64_t(-1), Values...>
  : std::array<uint64_t, sizeof...(Values)>
{
  constexpr FactorialArray()
    : std::array<uint64_t, sizeof...(Values)> ({{Values...}})
  {}
};

int main()
{
  static FactorialArray<10> f;
  for (std::size_t i = 0; i < f.size(); i++)
    std::cout << i << "! = " << f[i] << '\n';
  return 0;
}


texts:
This program takes the first number you input and divides by 2, then takes the result and multiplies by 4. I decided to use classes and file writing because I just learned it yesterday. Please critique.

# Write a program with two functions.
# The first function should take an integer as a parameter and return the result of the
# integer divided by 2.
# The second function should take an integer as a parameter and return the result of
# the integer multiplied by 4. Call the first function, save the result as a variable,
# and pass it as a parameter to the second function

myList = []

class Math:
    def __init__(self, x):
        self.number1 = x

#The try and excepts were created just in case I change the input to be mine instead of users's
#Divide the input

    def divide(self):
        try:
            self.division = self.number1 // 2
            return self.division
        except (TypeError, NameError):
            print("Unsupported format")

#Multiply the returned input

    def multiply(self):
        try:
            self.multiplication = self.division * 4
            myList.append(self.multiplication)
        except (AttributeError, NameError):
            print("First variable was not recognized")

while True:
    try:
        myNumber = Math(int(input("What number do you choose?"
                              "\nThis number will be divided by 2"
                              "\nThen it will be multiplied by 4\n")))
        myNumber.divide()
        myNumber.multiply()
        print(myList)
        tryAgain = input("Would you like to try again? "
                         "Press any key to continue. Press N to exit\n")

        if tryAgain == "N".lower():
            with open("data.txt", "w") as myData:
                myData.write("My data is: " + str(myList))
            break

    except(NameError,ValueError):
        print("Invalid Input")


texts:
Running on Cygwin, I cannot easily use perl -pi -e because it will always produce .bak files even though I don't want them. I wrote this script below to emulate perl -pi -e behavior and unlink the backup files after processing.

Also I wanted to simplify the call of the script. Instead of:

$ git ls-files | xargs perl -pi -e s/foo/bar/

I rather prefer to write

$ git ls-files | pie s/foo/bar

Although this program is not aimed to be particularly used with Git, with this alias pie="!git ls-files | pie" it becomes

$ git pie s/foo/bar

I feel this script can be simplified and the performances could be slightly improved. The question is how.

#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use File::Copy;

my $re = shift @ARGV;
@ARGV  = split(/\n/, do {local $/; <stdin>}) if @ARGV eq 0;

for my $file (@ARGV) {
    next unless -f $file;
    if (-f "$file.bak") {
        warn "[Warning] Backup file already exists and is been used by pie";
    }
    open my $fh,  "<",  $file;
    open my $tmp, ">", "$file.bak";
    while (<$fh>) {
        eval($re);
    } continue { print $tmp $_ }
    close $tmp;
    close $fh;
    move "$file.bak", $file;
}


texts: Ruby on Rails Method ActiveRecord Query Optimizations

texts:
So I have three methods and I'm not sure how to optimize them. I will be working on this and updating this post while I do but basically running these three methods is central to some parts of my application and they are causing a great deal of slowdown. I just have too many queries being ran because of them. If I could get some optimization help, I would appreciate it!

def self.appropriate_users(current_user)
    unless current_user.organization.nil?
      if current_user.has_role? :director
        @users = User.where(organization: current_user.organization)
      elsif current_user.has_role? :supervisor
        @users = current_user.subordinates
      elsif current_user.has_role? :leader
        @users = []
        groups = current_user.leading_groups.each do |g|
          g.users.each do |u|
            @users << u
          end
        end

        @users.uniq
      else
        @users = User.none
      end
    else
      @users = User.all if current_user.has_role? :admin
    end
    @users ||= []

    @users
  end

  def expired_trainings(current_user)
    retval = []
    Organization.appropriate_users(current_user).each do |user|
      Expiration.where("user_id = #{user.id} and expire_on <= '#{Date.today}'").each do |expir|
        retval << expir
      end
    end
    ttypes = []
    if current_user.max_role.downcase == 'leader'
      current_user.leading_groups.each do |g|
        g.training_types.each do |tt|
          ttypes << tt
        end
      end
      ttypes.flatten.uniq!
      retval.delete_if { |expir| !ttypes.include?(expir.training_type) }
    end
    retval.flatten
  end

  def current_trainings(current_user)
    retval = []
    Organization.appropriate_users(current_user).each do |user|
      Expiration.where("user_id = #{user.id} and expire_on >= '#{Date.today}' and expire_on <= '#{Date.today + 30.days}'").each do |expir|
        retval << expir
      end
    end
    ttypes = []
    if current_user.max_role.downcase == 'leader'
      current_user.leading_groups.each do |g|
        g.training_types.each do |tt|
          ttypes << tt
        end
      end
      ttypes.flatten.uniq!
      retval.delete_if { |expir| !ttypes.include?(expir.training_type) }
    end
    retval.flatten
  end

  def future_trainings(current_user)
    retval = []
    Organization.appropriate_users(current_user).each do |user|
      Expiration.where("user_id = #{user.id} and expire_on >= '#{Date.today + 31.days}'").each do |expir|
        retval << expir
      end
    end
    ttypes = []
    if current_user.max_role.downcase == 'leader'
      current_user.leading_groups.each do |g|
        g.training_types.each do |tt|
          ttypes << tt
        end
      end
      ttypes.flatten.uniq!
      retval.delete_if { |expir| !ttypes.include?(expir.training_type) }
    end
    retval.flatten
  end


texts: Command line utility to output modified Markdown

texts:
What this command line utility does is to take a text file and update the content a bit before turning it into Markdown. For example, the first for loop searches all the straight quotes and replace them for curly quotes. The second loop searches for hr tags and replace them for * * *, then adds the noind class to the p that follows that hr tag.

#!/usr/bin/env node

var fs = require('fs')
var program = require('commander')
var markdown = require('markdown').markdown

program
  .version('0.0.1')
  .usage('<keywords>')
  .parse(process.argv)

if (!program.args.length)
  program.help()

var filename = program.args[0]

fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err

  var tree = markdown.parse(data)

  ;(function updateTree(jsonml) {

    // replace straight quotes for curly quotes
    for (i = 1; i < jsonml.length; i++) {
      if (typeof jsonml[i][1] === "string" && jsonml[i][1].match(/"/g)) {
        var p = jsonml[i]

        for (j = 1; j < p.length; j++) {
          if (typeof p[j] === "string" && p[j].match(/"/g)) {
            p[j] = p[j].replace(/"(?=\b)/g, "“")
                       .replace(/"(?!\b)/g, "”")
          }
        }
      }

      if (typeof jsonml[i][1] === "string" && jsonml[i][1].match(/'/g)) {
        var p = jsonml[i]

        for (j = 1; j < p.length; j++) {
          if (typeof p[j] === "string" && p[j].match(/'/g)) {
            p[j] = p[j].replace(/'(?=\b)/g, "‘")
                       .replace(/'(?!\b)/g, "’")
          }
        }
      }
    }

    // replace hr for * * * and add noind class to the p tag that follows it
    for (i = 1; i < jsonml.length; i++) {
      if (jsonml[i][0] === 'hr') {
        var hr = jsonml[i]
        var p = jsonml[i + 1]

        hr.splice(0, 1, 'para', '* * *')
        p.splice(1, 0, {'class': 'noind'})
      }
    }
  })(tree)

  var html = markdown.renderJsonML(markdown.toHTMLTree(tree))
  console.log(html)
})

So my question is, how can I reduce the indentation level?


texts: SQL Inserting up to 10'000 records from a table to a secondary table

texts:
I'm relatively new to ASP.net and working with larger data sets as a fresh graduate, and I am currently maintaining/developing for an ASP webform and T-SQL system at the moment where we have a database table with ~4000 records, but there is potential for multiple key differences leading up to 10,000 records as a rough estimate to be submitted at a time. This is used for printing to a thermal printer, so a separate standalone database table with duplicate data is necessary.

I'll rewrite the code for insertion to a similar enough format so it's a bit more readable. The query is pretty much as efficient as it can possibly be, it's 3 left joins on ID fields and 2 where clauses to sort to the record I want to copy.

INSERT INTO PRINT_TABLE(ID, KEYNAME1, KEYNAME2, KEYNAME3, KEYNAME4,
PRINTFORMATSTRING, PRINTQUANTITY, COLLECTION, COLLECTION_OWNER, MANAGER, LOCATIONID )
(SELECT
--parameters and joins necessary to copy data across
with parameters @quantity, @id, and @label
)

Now I made an efficiency change already in an attempt to speed it up, it currently runs a foreach loop on a set of data in a telerik radgrid table, and I moved it to start using selecteditems instead of all items and picking out items that are selected, and any that are selected are added to the queue to iterate through. My question is, is it best to run this query in the code behind, on a button submit, i.e.?

Protected Sub AddToPrintDatabaseOnButtonClick(sender As Object, e As System.EventArgs)
    Using connection As New SqlConnection(connectionString)
        Dim command = New SqlCommand()
        command.Connection = connection
        command.CommandText = "INSERT INTO PRINT_TABLE(ID, KEYNAME1,
        KEYNAME2, KEYNAME3, KEYNAME4,
        PRINTFORMATSTRING, PRINTQUANTITY, COLLECTION, COLLECTION_OWNER,
        MANAGER, LOCATIONID )
        (SELECT
            --parameters and joins necessary to copy data across
            with parameters @quantity, @id, and @label
        )"
        connection.Open()
        command.Parameters.AddWithValue("quantity", TextBox.Value)
        command.Parameters.AddWithValue("label", Dropdownlist.Value)
        command.Parameters.AddWithValue("id", 0)
        For Each GDI As GridDataItem In RadGrid.SelectedItems
            command.Parameters("id").Value = Integer.Parse(GDI("id").Text)
            command.ExecuteNonQuery()
        Next
    End Using
End Sub

Which is what I just implemented to speed up the page which would create a new connection string on every selected value. Or is there some other method such as using a procedure and parsing in a list of the ID's and doing it database side, or another method I'm not thinking about? I'm more interested in suggestions or ways of thinking and approach to the issue than being given a flat solution, I want to learn. If you have 1 or 2 snippets that will help me out as an alternative I'd be very thankful.


texts:
def printTrg(rows):
    r1 = [1]
    r2 = [1, 1]
    trg = [r1, r2]
    r = []
    if rows == 1:
        r1[0] = str(r1[0])
        print(' '.join(r1))
    elif rows == 2:
        for o in trg:
            for a in range(len(o)):
                o[a] = str(o[a])
            print((' ')*(2-(a+1)), (' '.join(o)))
    else:
        for i in range(2, rows):
            trg.append([1]*i)
            for n in range(1, i):
                trg[i][n] = (trg[i-1][n-1]+trg[i-1][n])
            trg[i].append(1)
        for x in range(len(trg)):
            for y in trg[x]:
                s = str(y)
                r.append(s)
            print((' ')*(rows-(x+1)), (' ' .join(r)))
            r = []

I've been learning Python for a month, and developed this program that prints out the Pascal triangle with the number of rows you want.  It works fine with 5 rows.

For example, it prints:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1

But with more rows, it begins to be a little unbalanced because you have more digits on each number.

For example, a 10 row triangle:`

          1
         1 1
        1 2 1
       1 3 3 1
      1 4 6 4 1
     1 5 10 10 5 1
    1 6 15 20 15 6 1
   1 7 21 35 35 21 7 1
  1 8 28 56 70 56 28 8 1
 1 9 36 84 126 126 84 36 9 1

If you could help me with the output, it would be great.

EDIT:

def generate_pascals_triangle(rows):
    """ Returns a list of rows of a Pascal's Triangle with how many rows you want """
    triangle = [[1], [1, 1]]
    if rows == 1:
        return triangle[0]
    else:
        for row_number in range(2, rows):
            triangle.append([1]*row_number)
            for number in range(1, row_number):
                triangle[row_number][number] = (triangle[row_number-1][number-1]+triangle[row_number-1][number])
            triangle[row_number].append(1)
        return triangle

def difference_between_rows(row, next_row):
    """ Returns the difference between two rows in the formatted way """
    row_len = 0
    next_row_len = 0
    for number in row:
        string_number = str(number)
        row_len += (len(string_number)+1)
    for number in next_row:
        string_number = str(number)
        next_row_len += (len(string_number)+1)
    return (next_row_len-1) - (row_len-1)

def print_pascals_triangle(triangle):
    """ Prints the Pascal's Triangle previously generated by generate_pascals_triangle in a formatted form """
    for row in triangle:
        difference = int((difference_between_rows(row, triangle[len(triangle)-1]))/2)
        for number in range(len(row)):
            row[number] = str(row[number])
        print ((' ')*(difference), ' '.join(row))

if __name__ == '__main__': #credit to @alexwlchan
    again = 'y'
    while again == 'y':
        rows = int(input('Enter the number of rows you want in your Pascal`s Triangle: '))
        print_pascals_triangle(generate_pascals_triangle(rows))
        again = input('Do it again ? <y/n> ')


texts: Build a stamp duty calculator for various types of buyers

texts:
I had a task where I had to build a stamp duty calculator, which calculates the tax or stamp duty first-time buyers(ftb) returning buyers (rtb), and second-home buyers (shb) had to pay when purchasing the home.
These were the tax bands, although I think some of the percentages may be slightly wrong.
First Time Buyers
0 to £300,000 - 0%
£300,001 to £925,000 - 5%
£925001 to £1,500,000 - 10%
£1,500,000 and above - 12%

Returning Buyers
0 to £125,000 - 0%
£125,001 to £250,000 - 2%
£250,001 to £925,000 - 5%
£925,001 to £1,500,000 - 10%
£1,500,000 and above - 12%

Second Home Buyers
0 to £125,000 - 3%
£125,001 to £250,000 - 5%
£250,001 to £925,000 - 8%
£925,001 to £1,500,000 - 13%
£1,500,000 and above - 15%

Here is my solution, I look forward to the feedback.
const stampDutyCalc = (price) => {
  let stampdutyObject = {
    ftb: 0,
    rtb: 0,
    shb: 0,
  };

  firstTimeBuyerCalc(price, stampdutyObject);
  returningBuyerCalc(price, stampdutyObject);
  secondHomeBuyerCalc(price, stampdutyObject);

  return stampdutyObject;
};

function firstTimeBuyerCalc(price, stampdutyObject) {
  if (price <= 300000) {
    stampdutyObject.ftb += 0;
  } else if (price > 300000 && price <= 925000) {
    stampdutyObject.ftb += price * 0.05;
  } else if (price > 925000 && price <= 1500000) {
    stampdutyObject.ftb += (price - 925000) * 0.1 + (925000 - 300000) * 0.05;
  } else {
    stampdutyObject.ftb +=
      (price - 1500000) * 0.12 +
      (1500000 - 925000) * 0.1 +
      (925000 - 300000) * 0.05;
  }
}

function returningBuyerCalc(price, stampdutyObject) {
  if (price <= 125000) {
    stampdutyObject.rtb += 0;
  } else if (price > 125000 && price <= 250000) {
    stampdutyObject.rtb += price * 0.02;
  } else if (price > 250000 && price <= 925000) {
    stampdutyObject.rtb += (price - 250000) * 0.05 + (250000 - 125000) * 0.02;
  } else if (price > 925000 && price <= 1500000) {
    stampdutyObject.rtb +=
      (price - 925000) * 0.1 +
      (925000 - 250000) * 0.05 +
      (250000 - 125000) * 0.02;
  } else {
    stampdutyObject.rtb +=
      (price - 1500000) * 0.12 +
      (1500000 - 925000) * 0.1 +
      (925000 - 250000) * 0.05 +
      (250000 - 125000) * 0.02;
  }
}

function secondHomeBuyerCalc(price, stampdutyObject) {
  if (price <= 125000) {
    stampdutyObject.shb = price * 0.03;
  } else if (price > 125000 && price <= 250000) {
    stampdutyObject.shb += (price - 125000) * 0.05 + 125000 * 0.03;
  } else if (price > 250000 && price <= 925000) {
    stampdutyObject.shb +=
      (price - 250000) * 0.08 + (250000 - 125000) * 0.05 + 125000 * 0.03;
  } else if (price > 925000 && price <= 1500000) {
    stampdutyObject.shb +=
      (price - 925000) * 0.13 +
      (925000 - 250000) * 0.08 +
      (250000 - 125000) * 0.05 +
      125000 * 0.03;
  } else {
    stampdutyObject.shb +=
      (price - 1500000) * 0.15 +
      (1500000 - 925000) * 0.13 +
      (925000 - 250000) * 0.08 +
      (250000 - 125000) * 0.0 +
      125000 * 0.03;
  }
}

function returningBuyerCalc(price, stampdutyObject) {
  if (price <= 125000) {
    stampdutyObject.rtb += 0;
  } else if (price > 125000 && price <= 250000) {
    stampdutyObject.rtb += price * 0.02;
  } else if (price > 250000 && price <= 925000) {
    stampdutyObject.rtb += (price - 250000) * 0.05 + (250000 - 125000) * 0.02;
  } else if (price > 925000 && price <= 1500000) {
    stampdutyObject.rtb +=
      (price - 925000) * 0.1 +
      (925000 - 250000) * 0.05 +
      (250000 - 125000) * 0.02;
  } else {
    stampdutyObject.rtb +=
      (price - 1500000) * 0.12 +
      (1500000 - 925000) * 0.1 +
      (925000 - 250000) * 0.05 +
      (250000 - 125000) * 0.02;
  }
}


texts: Given a sorted dictionary of an alien language, find order of characters

texts:
Given a sorted dictionary (array of words) of an alien language, find
  order of characters in the language.

Link:
The idea is to create a graph of characters and then find topological sorting of the created graph. Following are the detailed steps.

1) Create a graph g with number of vertices equal to the size of alphabet in the given alien language. For example, if the alphabet size is 5, then there can be 5 characters in words. Initially there are no edges in graph.

2) Do following for every pair of adjacent words in given sorted array.

a) Let the current pair of words be word1 and word2. One by one compare
   characters of both words and find the first mismatching characters.

b) Create an edge in g from mismatching character of word1 to that of
   word2.

3) Print topological sorting of the above created graph.

import collections

def topological_sort(nodes_map, nodes):
    def recursion(nodes_map, node, result, visited):
        if node in visited:
            return
        visited.append(node)
        if node in nodes_map:
            for c in nodes_map[node]:
                recursion(nodes_map, c, result, visited)
        result.append(node)

    visited, result = [], []
    for node in nodes.keys()[::-1]:
        recursion(nodes_map, node, result, visited)
    return reversed(result)

words = ["baa", "abcd", "abca", "cab", "cad"]
chars = collections.OrderedDict()
for word in words:
    for c in word:
        chars[c] = True

nodes_map = collections.defaultdict(list)
for i, word in enumerate(words[:-1]):
    nxt = words[i+1]
    for a, b in zip(word, nxt):
        if a != b:
            nodes_map[a] += [b]
            break
for i in topological_sort(nodes_map, chars):
    print i,


texts:
I have finished my code for Conway's Game of Life. I am looking for any advice on how to improve it. I am a C++ beginner, so I used only basic libraries. I am accepting all suggestions.

/*
Author: Stevan Milic
Date: April 2018
Class: COSC 1560
Description: Game Of Life
*/
#include <iostream>
#include <cstdlib>  // Library needed for CLS command
#include <iomanip>
using namespace std;

const int boardsize = 10;

void Display(bool board[boardsize + 1][boardsize + 1])
{
    for (int x = 1; x < boardsize; x++)
    {
        for (int y = 1; y < boardsize; y++)
        {
            if (board[x][y] == true)
            {
                cout << " * ";
            }
            else
            {
                cout << " - ";
            }
            if (y == boardsize - 1)
            {
                cout << endl;
            }
        }
    }
}
// Copying the board in order to compare the existing cells
void CopyBoard(bool board[boardsize + 1][boardsize + 1], bool board2[boardsize + 1][boardsize + 1])
{
    for (int x = 0; x < boardsize; x++)
    {
        for (int y = 0; y < boardsize; y++)
        {
            board2[x][y] = board[x][y];
        }
    }
}
//Calculates function to determine if the cell is alive or dead
void Calc(bool board[boardsize + 1][boardsize + 1])
{
    bool board2[boardsize + 1][boardsize + 1] = {};
    CopyBoard(board, board2);
    for (int x = 1; x < boardsize; x++)
    {
        for (int y = 1; y < boardsize; y++)
        {
            int alive = 0;
            for (int z = -1; z < 2; z++)
            {
                for (int t = -1; t < 2; t++)
                {
                    if (!(z == 0 && t == 0))
                    {
                        if (board2[x + z][y + t])
                        {
                            alive++;
                        }
                    }
                }
            }
            if (alive < 2)
            {
                board[x][y] = false;
            }
            else if (alive == 3)
            {
                board[x][y] = true;
            }
            else if (alive > 3)
            {
                board[x][y] = false;
            }
        }
    }
}

int main()
{

    //const int boardsize = 10;
    bool board[boardsize + 1][boardsize + 1] = {};

    // Starting cells
    board[5][4] = true;
    board[5][5] = true;
    board[5][6] = true;
    board[4][4] = true;
    board[4][5] = true;
    board[4][6] = true;
    board[3][4] = true;
    board[3][5] = true;
    board[3][6] = true;

    while (true)
    {
        Display(board);     // Displaying function
        Calc(board);        // Calculating function
        system("CLS");      // Clearing the Screen
    }
}


texts:
I want to use a simple implementation of the Karplus-Strong algorithm to generate pluck sounds and chords.

My existing code seems correct but is slow when more than a few plucks are being generated. Is there a way to improve the performance of this. In particular is there a better way to use numpy here, or would something like a collections.deque be faster.

import numpy as np

sample_rate = 44100
damping = 0.999

def generate(f, vol, nsamples):
    """Generate a Karplus-Strong pluck.

    Arguments:
    f -- the frequency, as an integer
    vol -- volume, a float in [0.0, 1.0]
    nsamples -- the number of samples to generate. To generate a pluck t
    seconds long, one needs t * sample_rate samples. nsamples is an int.

    Return value:
    A numpy array of floats with length nsamples.
    """

    N = sample_rate // f
    buf = np.random.rand(N) * 2 - 1
    samples = np.empty(nsamples, dtype=float)

    for i in range(nsamples):
        samples[i] = buf[i % N]
        avg = damping * 0.5 * (buf[i % N] + buf[(1 + i) % N])
        buf[i % N] = avg

    return samples * vol

def generate_chord(f, nsamples):
    """Generate a chord of several plucks

    Arguments:
    f -- a (usually short) list of integer frequencies
    nsamples -- the length of the chord, a chord of length t seconds needs
    t * sample_rate, an integer.

    Return value:
    A numpy array
    """
    samples = np.zeros(nsamples, dtype=float)
    for note in f:
        samples += generate(note, 0.5, nsamples)
    return samples

if __name__ == "__main__":
    import matplotlib.pyplot as plt
    from scipy.io.wavfile import write

    strum = generate_chord(  # A Major
        [220, 220 * 5 // 4, 220 * 6 // 4, 220 * 2], sample_rate * 5)
    plt.plot(strum)
    plt.show()

    write("pluck.wav", sample_rate, strum)

This produces a sound file in pluck.wav with a waveform like this:


texts: Calculating scores for predictions of football scores

texts:
I am writing a program which calculates the scores for participants of a small "Football Score Prediction" game.

Rules are:

if the match result(win/loss/draw) is predicted correctly: 1 point
if the match score is predicted correctly(exact score): 3 points (and +1 point because 1st rule is automatically satisfied)

Score is calculated after every round of matches (10 matches in a round).

The program I've written is as follows:

import numpy as np
import re
players = {0:'Alex',1:'Charlton',2:'Vineet'}
results = np.array(range(40),dtype='a20').reshape(4,10)
eachPrediction = np.array(range(20),dtype='a2').reshape(2,10)
score = np.zeros(3)
correctScore=3
correctResult=1
allPredictions = []
done = False

def takeFixtures():
    filename='bplinput.txt'
    file = open(filename)
    text = file.readlines()
    fixtures = [line.strip() for line in text]
    file.close()
    i=0
    for eachMatch in fixtures:
        x=re.match("(.*) ([0-9]+) ?- ?([0-9]+) (.*)", eachMatch)
        results[0,i]=x.group(1)
        results[1,i]=x.group(2)
        results[2,i]=x.group(3)
        results[3,i]=x.group(4)
        i+=1

def takePredictions(noOfParticipants):
    for i in range(0,noOfParticipants):
        print("Enter predictions by "+players[i]+" in x-y format")
        for i in range(0,10):
            eachFixturePrediction = raw_input("Enter prediction for "+results[0,i]+" vs "+results[3,i]+": ")
            x=eachFixturePrediction.split('-')
            eachPrediction[0,i]=str(x[0])
            eachPrediction[1,i]=str(x[1])
        allPredictions.append(eachPrediction)

def scoreEngine():
    for i in range(0,len(players)):
        for j in range(0,10):
            resultH=int(results[1,j])
            resultA=int(results[2,j])
            result=resultH-resultA
            predictionH=int(allPredictions[i][0][j])
            predictionA=int(allPredictions[i][1][j])
            pResult = predictionH-predictionA
            if result == pResult or (result<0 and pResult<0) or (result>0 and pResult>0):
                score[i]+=correctResult
                if resultH==predictionH and resultA==predictionA:
                    score[i]+=correctScore

noOfParticipants=len(players)
takeFixtures()
takePredictions(noOfParticipants)
scoreEngine()
print("Scores are:")
print(score)
for player in players:
    print(players[player]+" has scored "+ str(score[player])+" points" )

The file used to take list of fixtures looks like this:

West Bromwich Albion 0-1 Tottenham Hotspur
Manchester City 2-2 Liverpool
Queens Park Rangers 0-0 Norwich City
Arsenal 1-0 Stoke City
Everton 3-3 Aston Villa
Newcastle United 3-2 Chelsea
Reading 2-1 Sunderland
West Ham United 1-0 Swansea City
Wigan Athletic 2-2 Southampton
Fulham 0-1 Manchester United

I want advice on how this program can be improved in any way (decreasing the code/ making it efficient).


texts: Concatenating an array of optional NSAttributedStrings

texts:
Imagine you had to join together attributed strings with a separator in between them.  Which of the following methods would you use?

An extension on SequenceType with a function that takes in a separator.   Can't use any optionals in the array.

extension SequenceType where Generator.Element: NSAttributedString {
    func join(withSeparator separator: NSAttributedString) -> NSAttributedString {
        var shouldAddSeparator = true
        return self.reduce(NSMutableAttributedString()) {(element, sequence) in
            if shouldAddSeparator {
            shouldAddSeparator = false
            }
            else {
                element.appendAttributedString(separator)
            }
        element.appendAttributedString(sequence)
        return element
        }
    }
}

A private function that takes in an array of optional NSAttributedString and a separator.

private func join(attributedStrings strings: [NSAttributedString?], withSeparator separator: NSAttributedString) -> NSAttributedString? {
    let unwrappedStrings = strings.flatMap{$0} as [NSAttributedString]
    guard unwrappedStrings.count == strings.count else { return nil }
    let finalString = NSMutableAttributedString()
    for (index, string) in unwrappedStrings.enumerate() {
        if index == 0 {
            finalString.appendAttributedString(string)
        }
        else {
            finalString.appendAttributedString(separator)
            finalString.appendAttributedString(string)
        }
    }

    return finalString
}

Extension on _ArrayType that can take in an array of options NSAttributedString

extension _ArrayType where Generator.Element == NSAttributedString? {
    private func join(withSeparator separator: NSAttributedString) -> NSAttributedString? {
        let unwrappedStrings = flatMap{$0} as [NSAttributedString]

        var shouldAddSeparator = false
        return unwrappedStrings.reduce(NSMutableAttributedString(), combine: { (string, element) in
            if shouldAddSeparator {
                string.appendAttributedString(separator)
            }
            else {
                shouldAddSeparator = true
            }
            string.appendAttributedString(element)
            return string
        })
    }
}


texts:
This is on a job listing site and it has a Linkedin apply button plugin - this provides for a callback the someone has applied for a job.  I've written the callback function which extracts the Job ID (a primary key in my database) and makes an AJX call to indcate that this Job ID has been applied for.

The Linkedin plugin is described here.

It essentially passes this JSON object to the callback:

{
   "event":"success",
   "job":{
      "companyID":"12345",
      "jobID":"9876",
      "jobTitle":"Chief Cat Herder"
   }
}

This is the code placed within the head of the page:

<script type="text/javascript">
function linkedInApplySuccess(jsonReturnObj)
    {
    // no need to use any jquery json functions as already jabe a json object from linkedin (instead os a string)
    // see second answer here http://stackoverflow.com/questions/3569416/parsing-json-string-with-jquery-parsejson

    var job_id = jsonReturnObj.job.jobId;

    $.ajax({
        url: "/php/cv_db/ajax_log_linkedin_application.php",
        data: {job_id: job_id},
        type: "POST"
        });

    };
</script>

Regarding the AJAX, I am not looking for any return data and nor do I care about success or failure as should it fail.  I'm not going to ask someone to apply for the job again. I do have error logging in my PHP file, though.


texts:
I have coded a system where each 'Player' class requires 5 components (could be more in the future, up to 10, 20 maybe even 30, once we add more and more features). What I want some advice on is a better way of creating these components, I am not saying that my current way is bad, I am just looking for anyone who could throw a fresh idea my way, to give my application a much better feel component wise.

My current way:

_searchesComponent = new PlayerSearchComponent(_playerConnection);
_searchesComponent.InitializeComponent();

_ignoreComponent = new PlayerIgnoreComponent(_playerConnection);
_ignoreComponent.InitializeComponent();

_effectsComponent = new PlayerEffectComponent(_playerConnection);
_effectsComponent.InitializeComponent();

_itemComponent = new PlayerItemComponent(_playerConnection);
_itemComponent.InitializeComponent();

_logComponent = new PlayerLogComponent(_playerConnection);
_logComponent.InitializeComponent();

Here is the base layout of one of my component classes:

namespace MyApp.Players.Players.Effects
{
    using System;
    using System.Collections.Generic;
    using Components;
    using NLog;

    internal sealed class PlayerIgnoreComponent : IDisposable, IComponent
    {
        private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

        private readonly PlayerConnection _playerConnection;
        private List<int> _ignores;

        public PlayerIgnoreComponent(PlayerConnection playerConnection)
        {
            _playerConnection = playerConnection;
            _ignores = new List<int>();
        }

        public void InitializeComponent()
        {
            using (var databaseConnection = Server.Database.NewDatabaseConnection)
            {
                var playerId = _playerConnection.SelectColumnInt("id");

                databaseConnection.SetQuery("SELECT * FROM `user_ignores` WHERE `user_id` = @userId");
                databaseConnection.AppendParameter("userId", playerId);

                using (var reader = databaseConnection.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        _ignores.Add(reader.GetInt32("ignore_id"));
                    }
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }

        private void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            _ignores.Clear();
            _ignores = null;
        }
    }
}

Fields:

private PlayerConnection _playerConnection;
private PlayerEffectComponent _effectsComponent;
private PlayerSearchComponent _searchesComponent;
private PlayerIgnoreComponent _ignoreComponent;
private PlayerClothingComponent _clothingComponent;

Here is IComponent:

namespace MyApp.Players.Players.Components
{
    public interface IComponent
    {
        void InitializeComponent();
    }
}

Any performance enhancement comments, answers or anything just to overall improve the code is also welcome.


texts: A class for animating messages as feedback to the user

texts:
This class provides animation messages to the user.  Looking for general feedback.

I've posted the library I use as well if you have time to look that over.

/***************************************************************************************************
SMessenger - messaging system to provide feedback to the user
*/
    var SMessenger = $A.Class.create({
        Name: 'SMessenger',

        // static constants
        A: {
            DELAYTRANS:           1000,
            DELAY:                2000,
            GRANULARITY:          15,
            GRANULARITY_POSITION: 1,
            OFFSET:               40,
            RADIX:                10,
            UNITS:                'px'
        },

        // holds dome elements
        E: {

            // the dom holds the messages
            dynamic:      '#dynamic'
        },
        init: function () {

            // pull the elements dynamically at init time
            $A.eachChild(this.E.dynamic, function (val) {
                this.E[val.id] = $A.el('#' + val.id);
            }, this);
        },

        // s_ denotes server response
        populateMessage: function (element, type) {
            var period = '';

            // messages from the server will have a period
            // they are denoted by a preceding s_
            if (type.match("s_")) {
                type = type.replace('s_', '');
                period = '.';
            }
            element.innerHTML = this.E['dyn_' + type].innerHTML + period;
        },

        // creates a fading message for the user
        fadingMessage: function (obj) {
            this.populateMessage(obj.response_element[0], obj.state);
            obj.response_element.fade('down', this.A.DELAY);
        },

        // creates a message that fades up and then fades down.
        popMessage : function (obj) {
            var self = this;
            this.populateMessage(obj.response_element, obj.state);
            $A(obj.pane_element).fade('up', this.A.DELAYTRANS, function () {
                $A.setTimeout(function () {
                    $A(obj.pane_element).fade('down', self.A.DELAYTRANS, function () {
                        self.hideInput(false, obj);
                    });
                }, self.A.DELAY);
            });
        },

        // creates a sliding message
        slidingMessage : function (obj) {
            var self = this,
                el = obj.pane_element;
            this.populateMessage(obj.response_element, obj.state);
            el.style.display = 'inline';
            this.hideInput(true, obj);
            $A.peakOut(el, 40, 2000, function () {
                el.style.display = 'none';
                self.hideInput(false, obj);
            });

        },

        // hides or exposes input - enter, button - while the message is being displayed
        hideInput: function (hide, obj) {
            if (hide) {
                if (obj.input_element) {
                    obj.input_element.removeEventListener("keypress", obj.enter);
                }
                obj.cover_element.style.display = 'inline';
            } else {
                if (obj.input_element) {
                    obj.input_element.addEventListener("keypress", obj.enter);
                }
                obj.cover_element.style.display = 'none';
            }
        },

        // resets inputs
        // set the inputs to empty
        // a focus and a blur will trigger event handlers
        resetInput: function (array, checkbox) {
            $A.someIndex(array, function (val) {
                val.value = '';
                val.focus();
                val.blur();
            });
            if (checkbox) {
                checkbox.checked = true;
            }
        }
    }, true);


texts:
I've refactored the string calculator kata as much as I could and tried to maintain single responsibility. Is there anything I could factor differently? The specs can be reviewed here.

module StringCalculator
  def self.add(string)
    string.end_with?("\n") ? fail('ends in newline') : solve(string)
  end

  def self.solve(string)
    verify(string)
    custom = delimiter(string)
    numerics = string.gsub(/\n/, custom).split(custom).map(&:to_i)
    numerics.reject { |n| n > 1000 }.reduce(0, :+)
  end

  def self.delimiter(string)
    string[0, 2] == '//' ? string[2, 1] : ','
  end

  def self.verify(string)
    find = string.scan(/-\d+/)
    fail("negatives not allowed: #{find.join(', ')}") if find.any?
  end

  private_class_method :verify, :delimiter, :solve
end

More importantly, I've thought of a case that involves the delimiter of a string that begins with // to be a number (which is considered invalid). I've made a quick way of solving that issue like so. Any suggestions on that?

Invalid case:

def self.delimiter(string)
  string[0, 2] == '//' ? check(string) || string[2, 1] : ','
end

def self.check(string)
  fail("invalid delimiter: #{string[2, 1]}") if string[2, 1] =~ /[0-9]/
end


texts: Arabic numbers to Roman numerals conversion

texts:
The following converts Arabic numbers to Roman numerals.

I decided to factor each digit into its place value, then use a mapping to convert it to its Roman equivalent.

For example, 1997 is factored to:

\$(1 \times 10^3) + (9 \times 10^2) + (9 \times 10^1) + (7 \times 10^0) = 1000 + 900 + 90 + 7\$

The Roman numerals for those numbers are then retrieved from the mapping.

class Integer
  def to_roman
    mappings = {
         1 => 'I',
         2 => 'II',
         3 => 'III',
         4 => 'IV',
         5 => 'V',
         6 => 'VI',
         7 => 'VII',
         8 => 'VIII',
         9 => 'IX',
        10 => 'X',
        20 => 'XX',
        30 => 'XXX',
        40 => 'XL',
        50 => 'L',
        60 => 'LX',
        70 => 'LXX',
        80 => 'LXXX',
        90 => 'XC',
       100 => 'C',
       200 => 'CC',
       300 => 'CCC',
       400 => 'CD',
       500 => 'D',
       600 => 'DC',
       700 => 'DCC',
       800 => 'DCCC',
       900 => 'CM',
      1000 => 'M',
      2000 => 'MM',
      3000 => 'MMM'
    }

    roman = []
    to_s.chars.reverse.each.with_index(0) do |digit, i|
      roman.unshift(mappings[digit.to_i * 10**i])
    end

    roman.join
  end
end

I like using exponents to factor each digit into its value place. I don't like having to define a mapping for each number from 1 to 3 and 6 to 8, and repeat that for the 10s, 100s, and 1000s digits.


texts:
I wrote a python module that needs to  load a file parser to work. Initially it was just one text parsing module but I need to add more parsers for different cases.

parser_class1.py

parser_class2.py

parser_class3.py

Only one is required for every running instance. I'm thinking load it by  command line:

mmain.py -p parser_class1

I wrote this code in order to select the parser to load when the main module is called:

#!/usr/bin/env python

import argparse
aparser = argparse.ArgumentParser()
aparser.add_argument('-p',
            action='store',
            dest='module',
            help='-i module to import')
results = aparser.parse_args()

if not results.module:
    aparser.error('Error! no module')
try:
    exec("import %s" %(results.module))
    print '%s imported done!'%(results.module)
except ImportError, e:
    print e

But, I was reading that this way is dangerous, maybe not standard.

Then is this approach ok?

Or must I find another way to do it?

Why?


texts: Replacing accented letters with regular letters in a spreadsheet

texts:
I am using the following VBA code to replace accented letters with regular letters in a spreadsheet. This is necessary because these spreadsheets have to be uploaded to an import tool that does not allow foreign characters.

Function RemoveAccentsFromForeignLetters()

    StartNewTask ("Removing accents from foreign letters")

    Dim AccChars As String
    Dim RegChars As String

    AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
    RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
    Set MyRange = ActiveSheet.UsedRange

    Dim A As String * 1
    Dim B As String * 1
    Dim i As Integer

    For i = 1 To Len(AccChars)
        A = Mid(AccChars, i, 1)
        B = Mid(RegChars, i, 1)
        MyRange.Replace What:=A, Replacement:=B, LookAt:=xlPart, MatchCase:=True
        ' TODO: highlight changed cells yellow
    Next

End Function

I googled the code from somewhere and it works, but it is a bit slow. In a spreadsheet with 1.5 million cells (7000 rows, 200 columns), it takes 21 seconds to run.

I wanted to look into ways to optimize it, for example:

Maybe a RegEx would be faster?
Maybe I should pass the entire spreadsheet to a DLL using an array, have the DLL do the replace, then pass it back? One article I read suggested that this is up to 10x faster than using native Excel VBA.
Maybe I should use the same DLL trick as above, but add multi-threading?
Any other ideas?


texts:
I was working on Leet code design a Linked List problem. My solution with a @tail pointer, althought it added complexity it made adding to tail O(1), also having a variable size @size made it easier to counter edge cases. Here are some of the stats:

  Success Details Runtime: 100 ms, faster than 84.62% of Ruby online
  submissions for Design Linked List. Memory Usage: 9.6 MB, less than
  100.00% of Ruby online submissions for Design Linked List.

If there is any enhancements or feedback please share some. Could the Linked List be optimize? Are you able to understand how is design when reading the code?

class MyLinkedList
    attr_accessor :head, :size, :tail
=begin
    Initialize your data structure here.
=end
    def initialize()
      @head = nil
      @size = 0
      @tail = nil
    end

=begin
    Get the value of the index-th node in the linked list. If the index is invalid, return -1.
    :type index: Integer
    :rtype: Integer
=end
    def get(index)
      return -1 if @head == nil
      return -1 if index > @size - 1
      return @head.val if index == 0
      return @tail.val if index == @size - 1

      i = @head
      j = 0

      while i != nil
        if j == index
          return i.val
        end
        i = i.next
        j += 1
      end
      -1
    end

=begin
    Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
    :type val: Integer
    :rtype: Void
=end
    def add_at_head(val)
      new_node = Node.new(val)
      new_node.next = @head
      @tail = new_node if @head == nil
      @head = new_node
      @size += 1
    end

=begin
    Append a node of value val to the last element of the linked list.
    :type val: Integer
    :rtype: Void
=end
    def add_at_tail(val)
      return add_at_head(val) if @head == nil
      node = Node.new(val)
      @tail.next = node
      @tail = node
      @size += 1
    end

=begin
    Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
    :type index: Integer
    :type val: Integer
    :rtype: Void
=end
    def add_at_index(index, val)
      return add_at_head(val) if index == 0
      return add_at_tail(val) if @head == @tail
      return add_at_tail(val) if @size == index
      return if index > @size

      i = @head
      j = 0

      while i != nil
        if j == index - 1
          tmp = i.next
          node = Node.new(val)
          i.next = node
          node.next = tmp
          @size += 1
          return
        end
        i = i.next
        j += 1
      end

    end

=begin
    Delete the index-th node in the linked list, if the index is valid.
    :type index: Integer
    :rtype: Void
=end
    def delete_at_index(index)
      return if index < 0 || index > @size - 1
      return delete_at_head if index == 0
      return delete_at_tail if index == @size - 1

      i = @head
      j = 0

      while i != nil
        if j == index - 1
         i.next = i.next.next
         @size -= 1
         return
        end
        i = i.next
        j += 1
      end

    end

    def delete_at_head
      if @head == nil
        return nil
      elsif @head == @tail #one element in the linked list
        @head = nil
        @tail = nil
        @size -= 1
        return
      else
        @head = @head.next
        @size -= 1
      end
    end

    def delete_at_tail
      if @head == nil
        return nil
      elsif @head == @tail
        return delete_at_head
      end

      current = @head
      prev = nil

      while(current != tail)
        prev = current
        current = current.next
      end
      prev.next = nil
      @tail = prev
      @size -= 1
      return
    end

    private

    class Node
        attr_accessor :val, :next
        def initialize(val)
            @val = val
            @next = nil
        end
    end
end


texts:
This following code executes correctly.I was wondering if there are better ways to write this code instead of using while(true) and break.For example using expressions,flags, do-while,etc.

import java.util.ArrayList;
import java.util.Scanner;

public class Words {
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    ArrayList<String> words = new ArrayList<String>();

while(true){
    System.out.print("Type a word: ");
    String word = reader.nextLine();
    words.add(word);

if(word.isEmpty()){
    System.out.println("You typed the following words:");
    for(String result: words){
    System.out.println(result);
    }
    break;
    }
 }
}
}


texts: Using hashing to create a PRNG with seed

texts:
So I wanted to code a simple PRNG for generating terrain in a game. It has to have the following properties:

Computationally cheap
Generate semi random numbers between 0 and an positive integer.
I need to be able to go back and teleport anywhere in the world so random.Next doesn't cut it.
I basically want a noise function. One output for each input with repeatable results.
No seed will be used. If I need another series I'll just shift x value by a couple of millions

These are some outputs produced by my program:

1 as input (x) gives 2 as a pseudo random number

2 as input (x) gives 2 as a pseudo random number

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;
using System.Security.Cryptography;

namespace Hashing_Functions
{
    class Program
    {
        static void Main(string[] args)
        {
            int i0 = 0;

            while (true)
            {
                i0++;
                Console.WriteLine(RandomHashFunction(i0, 10));
                //returns random number between 0 and max based on input
            }
        }

        static int RandomHashFunction(int input, int max)
        {
            var SHA1 = new SHA1CryptoServiceProvider();
            StringBuilder sb = new StringBuilder();
            string hash2string;
            double output;
            byte[] hash;
            SHA1.ComputeHash(ASCIIEncoding.ASCII.GetBytes(input.ToString()));
            hash = SHA1.Hash;
            sb.Clear();

            foreach (byte b in hash)
            {
                sb.Append(b.ToString());
            }
            hash2string = sb.ToString();
            output = hash2string.GetHashCode();
            output = Math.IEEERemainder(output, max);
            output = Math.Abs(output);

            return Convert.ToInt16(output);
        }
    }
}


texts: Wrapping a non-unique handle with additional information

texts:
I have a situation where I'd like to wrap up some plain C handles into a class, with a destructor and other niceties, in C++. I would like the wrapper class to have the exact same size as the handle, so I can pass an array of the wrappers into the C api without having to allocate and translate them first.

The handle is not unique - it has some extra information, which is known at creation time - so I can't use the handle itself as a key in one big map. Instead, I'm trying to use the address of the handle as the key.

Details aren't really important on this one - it has data, savvy?

class InstanceMetadata { ... };

The header for the wrapper class:

class Instance
{
public:
    Instance(const Instance&) = delete;
    Instance(Instance&& other);
    Instance(InstanceHandle handle, InstanceMetadata metadata);
    ~Instance();

    Instance& operator=(Instance&) = delete;
    Instance& operator=(Instance&& other);

    InstanceHandle GetHandle() const;
    void ResetHandle();

private:
    InstanceHandle handle;
};

A thin wrapper around std::map, which handles synchronization and nullptrs

template<typename Handle, typename Metadata>
class MetadataCache
{
public:
    void Set(Handle& key, Metadata* value)
    {
        std::lock_guard<std::mutex> guard(mutex);
        data[&key] = value;
    }

    Metadata* Get(Handle& key)
    {
        std::lock_guard<std::mutex> guard(mutex);
        std::map<Handle*, Metadata*>::iterator it = data.find(&key);
        if (it == data.end())
            return nullptr;
        return it->second;
    }

    void Erase(Handle& key)
    {
        std::lock_guard<std::mutex> guard(mutex);
        std::map<Handle*, Metadata*>::iterator it = data.find(&key);
        if (it != data.end())
            data.erase(it);
    }

private:
    std::mutex mutex;
    std::map<Handle*, Metadata*> data;
};

The implementation for the wrapper class:

using namespace std;
using namespace vulkan;

MetadataCache<InstanceHandle, InstanceMetadata> cache;

Instance::Instance(Instance&& other) :
    handle(other.handle)
{
    other.handle = InstanceHandle();
    cache.Set(this->handle, cache.Get(other.handle));
    cache.Erase(other.handle);
}

Instance::Instance(InstanceHandle handle, InstanceMetadata metadata) :
    handle(handle)
{
    cache.Set(handle, new InstanceMetadata(metadata));
}

Instance::~Instance()
{
    delete cache.Get(handle);
    if (handle)
        vkDestroyInstance(handle, nullptr);
}

Instance& Instance::operator=(Instance&& other)
{
    delete cache.Get(handle);
    cache.Set(handle, cache.Get(other.handle));
    cache.Erase(other.handle);
    other.handle = InstanceHandle();
    return *this;
}

InstanceHandle Instance::GetHandle() const
{
    return handle;
}

void Instance::ResetHandle()
{
    delete cache.Get(handle);
    handle = InstanceHandle();
}

The default constructor for InstanceHandle creates a null handle.

I'm still fairly new to move-semantics, so the main things I would like to know are:

Is it safe to do this? (i.e. have I missed an operator or something?)
Is there another way to do this?
Is there any good reason not to do this?

Keep in mind I don't really care about performance, as these objects will not be created or destroyed very often.


texts: Replacing each string of one or more blanks by a single blank

texts:
K&R 1.9 exercise:

  Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

Is this correct and proper code? Could I have put c and inspace on a single line?

#include <stdio.h>

int main(void)
{
    /*initializes c and inspace. */
    int c;
    int inspace;

    /*sets inspace = 0*/
    inspace = 0;

    while((c = getchar()) != EOF)
    {
        if(c == ' ')
        {
            if(inspace ==0)
            {
                inspace = 1;
                putchar(c);
            }
        }

        if(c != ' ')
        {
            inspace = 0;
            putchar(c);
        }
    }

    return 0;
}

I am using the latest Ubuntu distro 64 bit.


texts:
I'm writing my first JavaScript application (no 3rd party libraries used) and looking for some high-level guidance on how to better organize the code into separate classes & files.

Here is a simplified/contrived example to illustrate my current organizational layout/problems:

game.js:

/* Lots of constants, enums, etc defined here.
   Can't define them inside Game function as
   they are used by Graphics and ui_player classes too.
*/

function Game(ui) {

    /* Lots of things defined here which are exclusive to Game class. */

    var graphics = new Graphics();
    graphics.load();
    ui.setCanvas(graphics.canvas);

    this.start = function() {
        mainLoop();
    };

    function mainLoop() {
        /* ... */
        ui.player.updateAbc(abc);
        /* ... */
        paint();
    }

    function paint() {
        graphics.renderAll()
    }

    /* ... */
}

graphics.js:

function Graphics() {

    /* Some constants defined here that are exclusive to Graphics class. */

    var canvas = this.canvas = ...;
    var ctx = canvas.getContext("2d");

    /* ... */

    this.renderAll = function() {
        ctx.drawImage(...);
    };

    /* ... */
}

ui.js:

/* Lots of constants related to UI classes here. */

function ui() {
    var div = this.div = ...;
    var canvas;

    /* ... */

    var player = this.player = new ui_player();
    div.appendChild(player.div);

    this.setCanvas(c) {
        if (canvas)
            div.removeChild(canvas);
        canvas = c;
        div.appendChild(canvas);
    };

    /* ... */
}

ui_player.js:

 function ui_player() {
     var div = this.div = ...;

     /* ... */

     this.updateAbc = function(abc) {
         div.innerHTML = abc;
     };
 }

main.js:

 ui = new ui();
 game = new Game(ui);
 game.start();

What I dislike about this:

I feel that my scopes are clumsy.
I dislike the fact that I have constants in global scope because they are shared across multiple classes.
I dislike the fact that I have to pass ui to Game and then to Graphics, but I'm not sure if this is bad or if allowing every class to access others would be worse.

How can I improve my code structure? How can/should I put it all into a namespace hierarchy where classes can access classes above (and maybe even below) them?

P.S. - I'm compiling with Google Closure Compiler (advanced) if that makes any difference. No 3rd party libraries are used.


texts:
My current code is kinda atrocious to switch fragments and everything, but I don't know a better way to check to see if the fragment I'm trying to switch to.

private void FragmentChange(Bundle Data) {
    SetActionBarButtons(new String[] { "SearchButtonOff", "SearchExtraButtonOff" });
    String[] data = Data.getStringArray(ACTIVITY_MAIN.DATA);
    String type = data[0];
    String fragment = data[1];
    if (fragment.equals(POST_MAIN)) {
        postmainFragment = new Fragment_PostMain();
        mainContainer = postmainFragment;
    } else if (fragment.equals(POST_ACCOUNT)) {
        postaccountFragment = new Fragment_PostAccount();
        mainContainer = postaccountFragment;
    } else if (fragment.equals(POST_ACCOUNTLOGIN)) {
        postaccountloginFragment = new Fragment_PostAccountLogin();
        mainContainer = postaccountloginFragment;
    } else if (fragment.equals(POST_LOCATION_MAIN)) {
        postlocationmainFragment = new Fragment_PostLocationMain();
        mainContainer = postlocationmainFragment;
    } else if (fragment.equals(POST_IMAGES)) {
        postimagesFragment = new Fragment_PostImages();
        mainContainer = postimagesFragment;
    } else if (fragment.equals(POST_TEMPLATE)) {
        posttemplateFragment = new Fragment_PostTemplate();
        mainContainer = posttemplateFragment;
    } else if (fragment.equals(POST_LOCATION)) {
        postlocationFragment = new Fragment_PostLocation();
        mainContainer = postlocationFragment;
    } else if (fragment.equals(POST_CATEGORY)) {
        postcategoryFragment = new Fragment_PostCategory();
        mainContainer = postcategoryFragment;
    } else if (fragment.equals(POST_CATEGORY_MAIN)) {
        postcategorymainFragment = new Fragment_PostCategoryMain();
        mainContainer = postcategorymainFragment;
    } else if (fragment.equals(POST_LOCATION_MAIN)) {
        postlocationmainFragment = new Fragment_PostLocationMain();
        mainContainer = postlocationmainFragment;
    } else if (fragment.equals(LOADING)) {
        loadingFragment = new Fragment_Loading();
        mainContainer = loadingFragment;
    } else if (fragment.equals(POST_RESULTS_IMAGEVIEW)) {
        postresultsimageviewFragment = new FRAGMENT_POST_RESULTS_IMAGEVIEW();
        mainContainer = postresultsimageviewFragment;
    } else if (fragment.equals(SEARCH_RESULTS_REPLY)) {
        postresultsreplyFragment = new FRAGMENT_SEARCH_RESULTS_REPLY();
        mainContainer = postresultsreplyFragment;
    }

    FragmentTransaction FT = getFragmentManager().beginTransaction();
    if (type.equals(FRAGMENTCHANGE_FADEIN)) {
        FT.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
    } else if (type.equals(FRAGMENTCHANGE_FLIP_FORWARD)) {
        FT.setCustomAnimations(R.animator.card_flip_right_in, R.animator.card_flip_right_out);
    } else if (type.equals(FRAGMENTCHANGE_FLIP_BACK)) {
        FT.setCustomAnimations(R.animator.card_flip_left_in, R.animator.card_flip_left_out);
    }
    if (mainContainer != null) {
        FT.replace(R.id.main_fragment, mainContainer).commit();
    }
}

Basically, I want to pass a Bundle down and I set the first part of the bundle as the "type" for the animation, and the fragment as the actual fragment that I'm trying to switch it.  Then of course since I have so many fragments it just gets really messy with the if statements.

Is there a better way to write this so it's not as "ugly"?


texts:
I have a fast growing table with logs that I frequently have to delete (the server doesn't have much resources). It grows by at least two million entries every day. The database is a SQL Server 2012.

Currently I use this script to delete entries older than 7 days:

set nocount on;
declare @r int = 1
while @r > 0
begin
    begin transaction;
        delete top(10000)
        from [Logs]
        where
            cast([Timestamp] as date) < cast(dateadd(day, -7, GETUTCDATE()) as date))
        set @r = @@ROWCOUNT;
    commit transaction;
end

When I don't do it daily then it runs for a couple of hours (3-5) blocking other tasks that usually exit with timeouts (they need it for reporting).

I use transactions because I sometimes need to stop it before it's finished and this is easier to do with smaller batches. Otherwise there is too much to rollback.

The table is a pretty normal log:

CREATE TABLE [dbo].[Log](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [Timestamp] [datetime2](7) NOT NULL,
    [Environment] [nvarchar](50) NOT NULL,
    [Logger] [nvarchar](50) NOT NULL,
    [Message] [nvarchar](max) NULL,
    [Exception] [nvarchar](max) NULL,
 CONSTRAINT [PK_Log_Id] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Is there a way to make this script faster? Am I doing anything terribly wrong here?


texts: Removing duplicate file references from history

texts:
I have some code that searches for duplicate files and then removes those files from a csv. To make the set of files I am searching over much smaller, I first group the files by size; if a file has a size that it is unique, it is safe to assume that it is unique and does not need to be included in the set of files I am checking for duplicates. Additionally, I must only consider files that are listed in the csv. Occasionally the csv has filenames of files that are not in the directory, which leaves me with several choices.

I can initially check my list of files for those which do not exist and remove them. This adds a loop over all the files and seems unnecessary/inefficient; it is very rare that a file does not exist.
Use the following code with exception handling when the file is not found and delete file from my list at this point. However this introduces a side effect to the grouping function. Clearly this function does more than its name suggests.

Code:

def group_by_size(self, files_to_group):
    grouped_by_size = dict()
    for fileid in files_to_group:
        full_path = os.path.join(self.folder, fileid)
        try:
            size = os.path.getsize(full_path)
        except WindowsError:
            print WindowsError
            print "The file wasn't found. Deleting row from PremsPhotos."
            del self.files[fileid]
            del self.spreadsheet_reader.main_row_dict[fileid]
        if grouped_by_size.get(size):
            grouped_by_size[size].append(fileid)
        else:
            grouped_by_size[size]=[]
            grouped_by_size[size].append(fileid)
    return grouped_by_size

Alternatively, eliminate duplicates beforehand:

    def remove_nonexistant_photos(self):
        for photo in self.files:
            os.path.exists(os.path.join(self.folder, photo))

The context of this code is in a script that will likely be run a lot, but will not likely be modified once it works. Looping over all the files in the directory takes about half a second when there are 15k files in the directory. With both of these in mind, I suppose the decision is not of huge importance, but I have been doing a lot of reading about best practices, and want to improve my coding intuition/style as I go forward.


texts: a function to partition images into patches

texts:
I wrote a function that partitions an image into multiple patches. Here is the function, are there any suggestions to make it better or more production ready in terms of the best software practice?

def cal_patches(img,num_colums):
   patch_list = []
   num_rows = num_colums
   x,y,w,h = 0,0, int(img.shape[1]/num_colums), int(img.shape[0]/ num_rows)
   ind = 0
   for i in range(num_colums):
     x= 0
     for j in range(num_rows):
       ind += 1
       y_end = min(y+h, img.shape[0])
       x_end = min(x+w, img.shape[1])
       patch = img[y: y_end, x: x_end]
       patch_list.append(patch)
       x += w
     y += h
   return patch_list


texts:
I would like some advice on improving/optimizing a small program I wrote. What it does is run a random walk on a torus manifold with 8 colors that loop around.
//RTM Test Using Random Walk Fractals, WIP
//Created by delta23
//This Code works on Minix, Unix, MacOSX, Linux
//This Code does not work on DOS or Windows (yet...)
//LICENSE OF CODE: CC0 - Public Domain

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TAPE_SIZE_X 672
#define TAPE_SIZE_Y 135
//Q!><^V became ><^V : move and add
char inst [ 4 ] = { '>', '<', '^', 'V' } ; //can be used for debugging, and for inputting code later on, when it starts in a conditional loop perhaps
unsigned char tape [ TAPE_SIZE_X ] [ TAPE_SIZE_Y ] ;
int x = 336 ;
int y = 67 ;

void main ( void ) {
    system ( "clear" ) ; //clear screen
    srand ( time ( NULL ) ) ; //initialize random generator; TODO: port to C++ and use TRNG instead
    printf ( "\e[?25l" ) ; //disable cursor
    //TODO: Implement program input and conditional commands
    while ( 1 ) {
        switch ( inst [ rand ( ) % 4 ] ) { //MOVE
        case '>' :
            x = x + 1 ;
        break ;
        case '<' :
            x = x - 1 ;
        break ;
        case '^' :
            y = y + 1 ;
        break ;
        case 'V' :
            y = y - 1 ;
        break ;
        }
        if ( x >= TAPE_SIZE_X ) x = 0 ; //TOROID CODES FOR OOB CURSOR
        else if ( x < 0 ) x = TAPE_SIZE_X - 1 ;
        if ( y >= TAPE_SIZE_Y ) y = 0 ;
        else if ( y < 0 ) y = TAPE_SIZE_Y - 1 ;
        tape [ x ] [ y ] = tape [ x ] [ y ] + 1 ; // ADD 1
        if ( tape [ x ] [ y ] == 8 ) tape [ x ] [ y ] = 0 ;
        usleep ( 16667 ) ; // CAP SPEED TO 60FPS : 1/60 seconds = 16666.666... microseconds
        printf ( "\33[%d;%dH", y, x ) ; //print @ cursor position
        switch ( tape [ x ] [ y ] ) { //Color Code for Mem
        case 0 :
            printf ( "\x1B[40m " ) ;
        break ;
        case 1 :
            printf ( "\x1B[41m " ) ;
        break ;
        case 2 :
            printf ( "\x1B[43m " ) ;
        break ;
        case 3 :
            printf ( "\x1B[42m " ) ;
        break ;
        case 4 :
            printf ( "\x1B[46m " ) ;
        break ;
        case 5 :
            printf ( "\x1B[44m " ) ;
        break ;
        case 6 :
            printf ( "\x1B[45m " ) ;
        break ;
        case 7 :
            printf ( "\x1B[47m " ) ;
        break ;
        }
        fflush ( stdout ) ; //flush stdout to prevent abnormal lag in printing to screen
    }
}
```


texts:
This is my initial Facebook helper class. Is this code efficient or is there a way to improve this code?

using UnityEngine;
using System.Collections;
using Newtonsoft.Json;
using Facebook.MiniJSON;
using System.Linq;

public class FacebookManager : SingletonEternal<FacebookManager>
{
    public string accessToken;
    public FacebookFriends fbFriendsResult;
    public MyFacebookInfo myInfo = new MyFacebookInfo();
    public Texture2D pic;

    IEnumerator Start ()
    {
        if (!FB.IsInitialized)
            FB.Init (null);

        while (!FB.IsInitialized)
            yield return null;

        #if UNITY_EDITOR
        FacebookManager.instance.Login();
        #endif

        if(FB.IsLoggedIn)
        {
            GetMyInformation();
            GetMyFriendsList();
        }
    }

    void SetMyPicture(WWW www)
    {
        pic = www.texture;
    }

    public void Login()
    {
        FB.Login ("user_friends, email, public_profile",LoginCallback);
    }

    void LoginCallback(FBResult result)
    {
        if(result.Error!=null)
        {

        }
        else
        {
            GetMyInformation();
            GetMyFriendsList();
        }
    }

    public void Logout()
    {
        FB.Logout ();
    }

    void GetMyInformation()
    {
        FB.API ("me?fields=id,name,picture",Facebook.HttpMethod.GET,GotMyInformationCallback);
    }

    void GotMyInformationCallback(FBResult result)
    {
        if(result.Error!=null)
        {

        }
        else
        {
            myInfo = JsonConvert.DeserializeObject<MyFacebookInfo>(result.Text);
            MyRequest.CreateRequest(myInfo.picture.data.url,SetMyPicture);
        }
    }

    void GetMyFriendsList()
    {
        FB.API ("me/friends?fields=name,picture",Facebook.HttpMethod.GET,GotMyFriendsListCallback);
    }

    void GotMyFriendsListCallback(FBResult result)
    {
        if(result.Error!=null)
        {

        }
        else
        {
            fbFriendsResult = JsonConvert.DeserializeObject<FacebookFriends>(result.Text);
            fbFriendsResult.data = fbFriendsResult.data.OrderBy(a=>a.name).ToList();
        }
    }

    public void Invite()
    {
        FB.AppRequest ("Invite friends!");
    }
}


texts: Create a deck of playing cards & draw a hand of cards

texts:
I built a very basic blackjack program a couple of weeks ago, but I've learned a lot since then, and would like some input on a couple of basic functions for card games: a build_deck function and a draw_hand function.

It seems pretty efficient use of code (at least compared to my previous attempt) but I'm sure there are some ways I can improve on it.

import random

def build_deck():
# The deck is a list of tuples, with each tuple representing a card.
# Each card has a name, face, suit, and value.
    deck = []
    value = 0
    face = ''
    for value in range(13):
        value += 1
        suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
        for suit in suit_list:
            if value == 1:
                face = 'Ace'
            elif value == 11:
                face = 'Jack'
            elif value == 12:
                face = 'Queen'
            elif value == 13:
                face = 'King'
            else:
                face = str(value)
            name = 'the %s of %s' % (face, suit)
            # The deck is shuffled only once, when the deck is first built.
            random.shuffle(deck)
            deck.append((name, face, suit, value))
    return deck

def draw_hand(hand_size):
    # The player receives a card into their hand while the same card is removed from the deck.
    player_hand = []
    for draw in range(int(hand_size)):
        selected_card = (random.choice(deck))
        print('You drew %s.' % (selected_card[0]))
        player_hand.append(selected_card)
        deck.remove(selected_card)
    return player_hand

deck = build_deck()
player_hand= draw_hand(input('How many cards do you want to draw? There are %s cards in the deck.' % (str(len(deck)))))


texts:
Can I get a review of my code for the the Collatz Sequence from Chapter three of Automate the Boring Stuff with Python?

  The Collatz Sequence

  Write a function named collatz() that has one parameter named number.
  If number is even, then collatz() should print number // 2 and return
  this value. If number is odd, then collatz() should print and return 3
  * number + 1.

  Then write a program that lets the user type in an integer and that
  keeps calling collatz() on that number until the function returns the
  value 1. (Amazingly enough, this sequence actually works for any
  integer—sooner or later, using this sequence, you’ll arrive at 1! Even
  mathematicians aren’t sure why. Your program is exploring what’s
  called the Collatz sequence, sometimes called “the simplest impossible
  math problem.”)

  Remember to convert the return value from input() to an integer with
  the int() function; otherwise, it will be a string value.

  Hint: An integer number is even if number % 2 == 0, and it’s odd if
  number % 2 == 1.

  The output of this program could look something like this:

  Enter number:
3
10
5
16
8
4
2
1

  Input Validation

  Add try and except statements to the previous project to detect
  whether the user types in a noninteger string. Normally, the int()
  function will raise a ValueError error if it is passed a noninteger
  string, as in int('puppy'). In the except clause, print a message to
  the user saying they must enter an integer.

I am mainly wondering if there is a cleaner way to write my solution.

def collatz(num):
    while num > 1:
        if num % 2 == 0:
            print(num//2)
            num = num //2
        elif num % 2 ==1:
            print(3*num+1)
            num = 3*num+1
        else:
            print(num)

def getNum():
    global num
    num = (input("> "))
    try:
        num = int(num)
    except ValueError:
        print('plese enter a number')
        getNum()
getNum()
collatz(num)


texts: Prefix Sum in Ruby, Genomic Range Query from Codility

texts:
I'm currently going through some lessons on Codility. I've just spent a couple of hours with GenomicRangeQuery, which is intended to demonstrate the use of prefix sums.

The task description is here. Broadly, the idea is that given a string and a set of arbitrary cut points one should be able to return the lowest value character in a given slice. O(N*M) complexity is what we want to avoid.

My solution scores 100%, but I would still value any feedback on style and readability.

def solution(str, slice_starts, slice_ends)
    # Initiate an array to hold rolling totals of character occurrences
    prefix_sums = [0,0,0,0]]
    # Map possible characters to their positions in the prefix sum array
    chars = { "A" => 0, "C" => 1, "G" => 2, "T" => 3 }

    str.split('').each_with_index do |char, i|
        prefix_sums[i + 1] = prefix_sums[i].clone
        prefix_sums[i + 1][chars[char]] += 1
    end

    slice_starts.each_with_index.map do |slice_start, i|
        s = slice_start
        e = slice_ends[i]

        chars.each do |char, ii|
            occurrences = prefix_sums[e + 1][ii] - prefix_sums[s][ii]
            break (ii + 1) if occurrences > 0
        end
    end
end

Updated

Here's my current preferred version using tips from some of the answers below. I should probably also use an array of hashes, rather than arrays, for the prefix sums, but I'm lazy.

def solution(str, slice_starts, slice_ends)
  prefix_sums = [[0] * 4]
  chars = { "A" => 0, "C" => 1, "G" => 2, "T" => 3 }

  str.chars.each_with_index do |char, i|
      prefix_sums[i + 1] = prefix_sums[i].clone
      prefix_sums[i + 1][chars[char]] += 1
  end

  slice_starts.zip(slice_ends).map do |s, e|
    chars.each do |char, ii|
      occurrences = prefix_sums[e + 1][ii] - prefix_sums[s][ii]
      break (ii + 1) if occurrences > 0
    end
  end
end


texts: Better ways to build a linq specification for querying or is this the only way?

texts:
The code pretty much explains what I am doing here. Just wondering if anyone can think of a better way.

public class AttachmentQuery
{
    /// <summary>
    /// Initializes a new instance of the <see cref="AttachmentQuery"/> class.
    /// </summary>
    /// <param name="type">The type.</param>
    /// <param name="status">The status.</param>
    /// <param name="sort">The sort.</param>
    /// <param name="order">The order.</param>
    /// <param name="page">The page.</param>
    public AttachmentQuery(string type, string status, SortAttachment sort, SortOrder order, int? page)
    {
        IAttachmentSpecification specification = null;

        if (!string.IsNullOrEmpty(type))
        {
            specification = new AttachmentFileTypeSpecification(type);
        }

        if (!string.IsNullOrEmpty(status))
        {
            if (specification == null)
            {
                specification = new AttachmentStatusSpecification(status.AsEnum<AttachmentStatus>());
            }
            else
            {
                var spec = new AndSpecification<Attachment>(
                    specification,
                    new AttachmentStatusSpecification(status.AsEnum<AttachmentStatus>())
                );

                specification = spec as IAttachmentSpecification;
            }
        }

        if (specification == null)
        {
            specification = new AttachmentSpecification();
        }

        specification.Page = page;
        specification.Limit = Setting.AttachmentPageLimit.Value;
        specification.Sort = sort;
        specification.Order = order;

        this.Specification = specification;
    }

    /// <summary>
    /// Gets or sets the specification.
    /// </summary>
    /// <value>The specification.</value>
    public IAttachmentSpecification Specification
    {
        get;
        private set;
    }
}

Source.

How it is used.


texts: Endless stream: stream a range and return default value if the range is exhausted

texts:
Introduction:

Motivation

Sometimes there is a need to merge N > 1 ranges, and they don't have equal length, but there is a value which can be used in case the range is already exhausted. It is especially apparent in this question, in which most of the complexity comes from handling the nullness of either or both lists.

Solution

The solution constitutes a parody to std::optional's value_or(), but being the only option to retrieve a value. The idea is that users don't care if it is value from the range or it is default value. The stream will keep issuing values from range, until iterator hits end iterator, then it will return default value.

Problems by design

Not modelled after standard library iterator

The problem lies in the ValueType. I don't want to apply greater constraints on it, other than being constructible and destructible. One would think that since there is next(), the value should copy/move constructible.

No support for std::vector<bool>

std::vector<bool> for C++ is like older versions of IE for javascript. To return dereferenced value from iterator, the reference must be constructible from outside of std::vector<bool>, but that is not possible, so no, no support for std::vector<bool>.

Not compatible with standard library at all

The reason is that I didn't see much usage and discussion about this, thus I decided to take opportunity to look at more usage examples, before making more concrete interface.

Code

#include <utility>
#include <iterator>

namespace shino {
template <typename InputIterator,
          typename Sentinel = InputIterator,
          typename ValueType = typename std::iterator_traits<InputIterator>::value_type>
class endless_stream {
    InputIterator first;
    Sentinel last;
    ValueType default_value;
public:
    template <typename ... ArgTypes>
    endless_stream(InputIterator first, Sentinel last, ArgTypes&& ... args) :
        first(first),
        last(last),
        default_value(std::forward<ArgTypes>(args)...)
    {}

    ValueType& next() {
        if (first == last) {
            return default_value;
        } else {
            return *first++;
        }
    }

    bool has_next() const {
        return first != last;
    }

    InputIterator current_position() const {
        return first;
    }

    Sentinel end() const {
        return last;
    }
};
}

Usage example

As it was born from this question, I thought that it would be only natural to target the problem in the demo on Wandbox:

using iterator = std::list<int>::iterator;
void add_digit_lists(shino::endless_stream<iterator> left,
                     shino::endless_stream<iterator> right,
                     std::list<int>& output) {
    bool has_carry = false;
    std::stack<int, std::vector<int>> prev_sums; //default is std::deque, not desired
    while (left.has_next() || right.has_next() || has_carry) {
        auto sum = left.next() + right.next() + has_carry;
        has_carry = false;
        if (sum > 9) {
            sum -= 10;
            has_carry = true;
        }
        prev_sums.push(sum);
    }

    while (not prev_sums.empty()) {
        output.push_back(prev_sums.top());
        prev_sums.pop();
    }
}

Concerns

Non-descriptive name of the class

One would need to read the docs to figure out the exact behavior of the facility. Is there a better one?

Is it C++14 compatible?

I tried to keep the code C++14 friendly, but still allow C++17 users to not type too much.

Is implicit class template argument deduction from constructor sufficient?

I'm worried that in some cases compiler won't be able to deduce some of the types if they are not provided and C++17 mechanism is used.

Any other suggestions are welcome.