texts: Dominion card game - how can I take advantage of interfaces?

texts:
I'm writing a card game (Dominion) as a pet project. I'm new to C++ but not programming.
A player has a deck, containing the hand and cards in play (tableau). Outside the player, there are piles of cards to buy from (supply piles). I want to display these objects (the hand, tableau and supply piles) on the screen. I had chosen to represent the hand and tableau using std::vector<Card> and the supply piles as std::vector<SupplyPile>. Card and SupplyPile implement an interface for displaying contents to the screen
class IInfo {
public:
  virtual std::string Info() const = 0;
  virtual std::string ToString() const = 0;
};

I have a class I'm calling View that will take on displaying things to the screen.
class View {
public:
  View(const std::vector<IInfo*>& items, int window_starty, int window_startx);
  virtual ~View() { }

  const IInfo& CurrentItem() const;
  const int CurrentIndex() const;
  bool IsEmpty() const;
  void ItemDown();
  void ItemUp();
  void SetActive();
  void SetInactive();
  virtual void Update();
protected:
  virtual WINDOW* InitializeWindow(int lines,
    int cols,
    int starty,
    int startx);

  virtual ITEM** MakeMenuItems();
private:
  // Some constants

  const std::vector<IInfo*>& items_;

  MENU *menu_;
  WINDOW *window_;
};

I now know that C++ doesn't support covariance in templates, so I can't create instances of View with the supply pile, hand, and tableau. How can I redesign the system to maximize DRY? The View class operates on its container member in a very simple way, ripe for abstraction.
Examples of things I want to do
std::vector<Card> hand = player.hand();
std::vector<Card> tableau = player.tableau();
std::vector<SupplyPile> supply_piles = game.supply_piles();

View hand_view = new View(hand, starty, startx);
View tableau_view = new View(tableau, starty, startx);
View supply_piles_view = new View(supply_piles, starty, startx);

One answer suggested making View into a template, and it almost worked until I remembered that I want to track which View is active at a given time:
View active_ = hand_view;
// Later
active_ = supply_piles_view;

I can't do this with View<Card> and View<SupplyPile>.
Other code
class Card : public IInfo {
public:
  Card(std::string name,
    int cost,
    int initial_supply,
    std::string text,
    std::string type);
  ~Card();

  void Play();
  std::string Info() const;
  std::string ToString() const;

  int cost() const;
  int initial_supply() const;
  std::string name() const;
  std::string text() const;
private:
  int cost_;
  int initial_supply_;

  std::string name_;
  std::string text_;
  std::string type_;

  std::string set_;
};

class SupplyPile : public IInfo {

public:
    SupplyPile(const Card& card, int initial_count);
    SupplyPile(const SupplyPile& other);
    virtual ~SupplyPile();
    virtual bool operator==(const SupplyPile& other) const;

    bool BuyOrGain();
    std::string Info() const;
    std::string ToString() const;

    const Card& card() const;
    int count() const;
    std::string name() const;
private:
    const Card& card_;

    int count_;
};


texts:
I have finally finished a Ruby calculator project, which is not based on eval. Instead it parses input char by char. The project is hosted on GitHub.

However, I find a specific part of the program very annoying since whenever I have to add something I have to rewrite a portion of it again.

def trig
  case @look
  when 'c'
    match_all('cos')
    case @look
    when 'h'
      match_all('h(')
      value = cosh(calculate)
    when '('
      match('(')
      value = cos(calculate)
    else
      expected('cos() or cosh()')
    end
  when 's'
    match('s')
    if @look == 'q'
      match_all('qrt(')
      value = sqrt(calculate)
    else
      match_all('in')
      case @look
      when 'h'
        match_all('h(')
        value = sinh(calculate)
      when '('
        match('(')
        value = sin(calculate)
      else
        expected('sin() or sinh()')
      end
    end
  when 'r'
    match_all('root')
    base = get_number
    match('(')
    value = calculate ** (1.0/base)
  when 't'
    match_all('tan')
    case @look
    when 'h'
      match_all('h(')
      value = tanh(calculate)
    when '('
      match('(')
      value = tan(calculate)
    else
      expected('tan() or tanh()')
    end
  when 'l'
    match('l')
    case @look
    when 'n'
      match_all('n(')
      value = log(calculate)
    when 'o'
      match_all('og')
      if digit? @look
        base = get_number
      elsif @look == "("
        base = 10
      else
        expected("integer or ( ")
      end
      match('(')
      value = log(calculate, base)
    else
      expected('ln() or log()')
    end
  when 'e'
    match_all('exp(')
    value = exp(calculate)
  when 'a'
    match_all('arc')
    case @look
    when 'c'
      match_all('cos')
      case @look
      when 'h'
        match_all('h(')
        value = acosh(calculate)
      when '('
        match('(')
        value = acos(calculate)
      else
        expected('arccos() or arccosh()')
      end
    when 's'
      match_all('sin')
      case @look
      when 'h'
        match_all('h(')
        value = asinh(calculate)
      when '('
        match('(')
        value = asin(calculate)
      else
        expected('arcsin() or arcsinh()')
      end
    when 't'
      match_all('tan')
      case @look
      when 'h'
        match_all('h(')
        value = atanh(calculate)
      when '('
        match('(')
        value = atan(calculate)
      else
        expected('arctan() or arctanh()')
      end
    end
  else
    raise InvalidInput, "unexpected input: \"#{@look}\""
  end
  match(')')
  value
end

The @look variable will contain the next character. The match_all function will simply match the input character by character. For example, it would match c and if it works it continues to match o and so on, but if it doesn't it will output an error.


texts: Triangle categorizer -- completely refactored and re-written

texts:
While reviewing a C question I started writing my own implementation and in no time I had a completely refactored completely different implementation. As the asker is learning I did not want to post it, instead I ask you for further review and possibilities of improvement.

#include <stdio.h>
#include <stdbool.h>

int get_side(name) {
    printf("Side-%d has value: ", name);
    int value; scanf("%d", &value);
    return value;
}

bool is_valid_triangle(side_1,side_2,side_3) {
    bool all_positive = side_1 > 0 && side_2 > 0 && side_3 > 0;
    bool correct_sized_sides = side_1 + side_2 > side_3 && \
                               side_2 + side_3 > side_1 && \
                               side_3 + side_1 > side_2;
    return all_positive && correct_sized_sides;
}

bool is_equilater(side_1,side_2,side_3) {
    return (side_1 == side_2 && side_2 == side_3);
}

bool is_isosceles(side_1,side_2,side_3) {
    return (side_1 == side_2) || (side_2 == side_3) || (side_3 == side_1);
}

bool is_scalen(side_1,side_2,side_3) {
    return ! is_isosceles(side_1,side_2,side_3);
}

const char * triangle_categorizer(side_1,side_2,side_3) {
    if (is_equilater(side_1,side_2,side_3)) {
        return "equilater";
    }

    if (is_isosceles(side_1,side_2,side_3)) {
        return "isosceles";
    }

    if (is_scalen(side_1,side_2,side_3)) {
        return "scalen";
    }
}

int main() {
    int side_1 = get_side(1);
    int side_2 = get_side(2);
    int side_3 = get_side(3);

    if (! is_valid_triangle(side_1,side_2,side_3)) {
        puts("The triangle you intered is invalid!");
        return 1;
    }
    printf("The triangle you entered is %s.\n", \
           triangle_categorizer(side_1,side_2,side_3));
    return 0;
}


texts: Downloading 2 tables from db, does calculation and uploads resulting table

texts:
I have written this script that downloads two tables from the db, preforms an intersection on them and adds 2 new columns to the resulting table, and uploads the resulting table to the db. It's a bit slow and I realize my code is messy (I'm new to Python and GIS). I suspect more steps can be done in parallel, for example downloading both tables from the database at once.

import arcpy, os, subprocess
import logging, shutil, sys

if __name__ == '__main__':
    #create logger
    logger = logging.getLogger(__name__)
    FORMAT = '%(name)s - %(levelname)s - %(message)s'
    logging.basicConfig(filename='py_intersection.log', level=logging.DEBUG, format=FORMAT)
    logger.info('Started shp intr arcpy')

    host = sys.argv[1]
    database = sys.argv[2]
    schema1 = sys.argv[3]
    schema2 = sys.argv[4]
    username = sys.argv[5]
    password = sys.argv[6]
    table1 = sys.argv[7]
    table2 = sys.argv[8]

    print 'program started'

    out_path = r'\\storage1\gis\temp\output.shp'
    new_dir = r'\\storage1\gis\temp'
    if not os.path.exists(new_dir):
        os.makedirs(new_dir)

    pgsql2shp = 'pgsql2shp -f %s\\%s -h %s -p 5432 -P %s -u %s %s %s.%s' % (new_dir, table1, host, password, username, database, schema1, table1)
    print pgsql2shp
    logger.info('Return code pgsql2shp invocation 1: '+str(subprocess.Popen(pgsql2shp, shell=True).wait()))
    pgsql2shp = 'pgsql2shp -f %s\\%s -h %s -p 5432 -P %s -u %s %s %s.%s' % (new_dir, table2, host, password, username, database, schema2, table2)
    print pgsql2shp
    logger.info('Return code pgsql2shp invocation 2: '+str(subprocess.Popen(pgsql2shp, shell=True).wait()))
    print('Argument:'+ new_dir+'\\'+table1+'.shp'+' , '+ new_dir+'\\'+table2+'.shp')
    arcpy.Intersect_analysis([new_dir+'\\'+table1+'.shp', new_dir+'\\'+table2+'.shp'], out_path, "ALL")

    arcpy.AddField_management(out_path, "intersected_area", "DOUBLE")
    arcpy.AddField_management(out_path, "dist_perct", "DOUBLE")
    arcpy.CalculateField_management(out_path, "intersected_area","!SHAPE.AREA@SQUAREMETERS!", "PYTHON_9.3")

    formula = """def findArea(area_inter, area):
                    return float((float(area_inter/area))*100.0)"""

    arcpy.CalculateField_management(out_path, "dist_perct", "findArea(!intersected_area!, !AREA!)", "PYTHON_9.3", formula)

    #export shapefiles to database
    shp2pgsql = r"shp2pgsql -d -s 48591 "+out_path+" johnsmith.intersected"
    psql = "psql -U johnsmith -h example.org -d exampledb"
    logger.info("Running shp2pgsql | psql")
    sts = subprocess.Popen(shp2pgsql +" | "+psql, shell=True).wait()
    logger.info("Remove shapefiles")
    shutil.rmtree(new_dir)
    print 'program finished'
    logger.info("Done shp intr arcpy")
"""!
@endcond
"""


texts:
I wrote a function in Python to call 7zip to compress a folder. The code works and is able to perform the task, however I do not know if this is the most optimal way. Are there any ways to improve the code, any redundant steps?

def Compress_7z(Initial_path,Container_Name,File_List, compression_level = -1,DAC = False):
 """Compression level = -1 standard, 0-9 compression level
       DAC : Delete After Compression - Remove File after being compressed
    """
    try:
        chdir(Initial_path)
    except:
        return('Path does not exist')

    # write a listfile
    with open('list.txt', 'w') as f:
        for item in File_List:
            f.write("%s\n" % item)

    cmd = ['7z', 'a', Container_Name,'@list.txt']

    if compression_level != -1 and compression_level <= 9:
        cmd.append('-mx{0}'.format(compression_level))
    elif compression_level > 9 or compression_level < -1:
        return("Compression not standard: aborting compression")

    system = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE,shell=True)

    while system.poll() == None:  # .poll() will return a value once it's complete.
        time.sleep(1)
    if DAC:
        for f in File_List:
            remove(f)

    # Clean up from compression
    remove('list.txt')
    return(system.communicate())


texts:
I'd just like to ask if there's anyway to make the functions play_Game() or is_move_valid() anymore efficient. For example, using a loop of some sort, I haven't been able to figure out how and would like any help in trying to make those functions shorter.

#TicTacToe
import sys
rows=[[0,1,2],[3,4,5],[6,7,8]]
columns =[[0,3,6],[1,4,7],[2,5,8]]
diagonals=[[0,4,8],[2,4,6]]
count=0

def display_Grid():
    print("\n")
    print(grid[0][0], "|" , grid[0][1], "|" , grid[0][2])
    print("---------")
    print(grid[1][0], "|", grid[1][1], "|", grid[1][2])
    print("---------")
    print(grid[2][0], "|", grid[2][1], "|", grid[2][2])

def check_turn():
    if count%2 == 0:
        player_1()
    else:
        player_2()

def game_over(shape):
    try:
        sys.exit()

    except SystemExit:
        print(shape," won")
        win = True
        quit()
def player_1():
    p_number = ("Player one")
    p_shape = p1
    play_Game(p_number, p_shape)

def player_2():
    p_number = ("Player two")
    p_shape = p2
    play_Game(p_number, p_shape)

def checkDraw():
    try:
        if count==10:
            sys.exit()

    except SystemExit:
        print("Draw")
        quit()

def check_win(shape):
    directions=[rows,columns,diagonals]
    for i in directions:
        for j in i:
            status = map(lambda val: True if grid[int(val/3)][val%3] == shape else False, j)
            if all(status):
                return True

    return False

def play_Game(p_number, p_shape):
    global count
    checkDraw()
    print(p_number, ",enter where you would like to move on the grid: ")
    move = int(input(""))
    if move in (1, 2, 0):
        valid = is_move_valid(move)
        if valid:
            count+=1
            grid[0][move] = p_shape
            display_Grid()
        else:
            check_turn()
    elif move in (3, 4, 5):
        valid = is_move_valid(move)
        if valid:
            count+=1
            move2 = move-3
            grid[1][move2] = p_shape
            display_Grid()
        else:
            check_turn()
    elif move in (6, 7, 8):
        valid = is_move_valid(move)
        if valid:
            count+=1
            move2 = move-6
            grid[2][move2] = p_shape
            display_Grid()
        else:
            check_turn()

    else:
        print("Enter one of the numbers visible on the grid: ")

    if check_win(p_shape):
        game_over(p_shape)
    else:
        None
    if count%2 == 0:
        player_1()
    else:
        player_2()

def is_move_valid(move):
    print(move)
    if move in(0, 1, 2):
        if grid[0][move] in ("X", "O"):
            print("This place has already been picked...")
            return False
        else:
            None
    elif move in(3, 4, 5):
        move2 = move-3
        if grid[1][move2] in ("X", "O"):
            print("This place has already been picked...")
            return False
        else:
              None
    elif move in(6, 7, 8):
        move2 = move-6
        if grid[2][move2] in ("X", "O"):
            print("This place has already been picked...")
            return False
        else:
              None

    return True

win = False
grid = [[0,1,2],[3,4,5],[6,7,8]]
p_number = (" ")
display_Grid()
choose = input("Player one, would you like to be 'X' or 'O'?: ")
while win != True:
    try:
         if choose == "X":
             p2 = "O"
             p1 = choose
             player_1()
         elif choose == "O":
             p1 = "O"
             p2 = "X"
             player_1()
         else:
             print("Enter x or o: ")
             choose = input("Player 1, would you like to be 'X' or 'O'?: ")
    except ValueError:
        print("Please enter X OR O")


texts:
I want to perform a binary search on a continuous unimodal function ƒ(x)=y, where x and y are real numbers. I'm not looking up values in an array, and so I don't have clean integer inputs that I'm stepping along.

My original attempt at a function (written in JavaScript) has the problem that when the input value you are looking for happens to sit on a boundary chosen by the algorithm, the algorithm continues to run until the numeric precision is exhausted:

/**
 * y: the target output value to find a matching input
 * minX: the smallest input value
 * maxX: the largest input value
 * ƒ:    a function that returns a value given an X
 * ε:    the threshold to compare outputs versus the target (default:0)
 */
function binarySearch(y, minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=0;
    let m=minX, n=maxX, k, v, Δ;
    while (m<=n) {
        k = (n+m)/2;
        v = ƒ(k);
        Δ = y-v;
        if (Math.abs(Δ)<=ε) return k;
        if (Δ>0) m = k;
        else     n = k;
    }
    if (Math.abs(y-ƒ(m))<=ε) return m;
    if (Math.abs(y-ƒ(n))<=ε) return n;
}

With the above, the call binarySearch( 0, 0, 10, n=>n ) will run 1077 iterations until m=0 and n=5e-324 before (m+n)/2 is finally so close to 0 that even with ε=0 the JavaScript interpreter cannot tell the difference.

A hack I was going to use is to provide a minimum step function that modifies each boundary by a fixed amount (similar to array index +/- 1). This forces the boundary to move faster, but also requires an ε>0 in case the boundary overshoots the value. It feels gross:

// step: a minimum amount to move each boundary each time
function binarySearch(y, minX, maxX, ƒ, ε, step) {
    if (ε===undefined) ε=0;
    if (step===undefined) step=0;
    let m=minX, n=maxX, k, v, Δ;
    while (m<=n) {
        k = (n+m)/2;
        v = ƒ(k);
        Δ = y-v;
        if (Math.abs(Δ)<=ε) return k;
        if (Δ>0) m = k+step;
                 n = k-step;
    }
    if (Math.abs(y-ƒ(m))<=ε) return m;
    if (Math.abs(y-ƒ(n))<=ε) return n;
}

A ~clean fix is to check the boundaries on every pass by moving the final two if statements into the while loop. This calls ƒ() three times as often each pass, and so seems inelegant.

/**
 * y: the target output value to find a matching input
 * minX: the smallest input value
 * maxX: the largest input value
 * ƒ:    a function that returns a value given an X
 * ε:    the threshold to compare outputs versus the target (default:0)
 */
function binarySearch(y, minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=0;
    let m=minX, n=maxX, k, v, Δ;
    while (m<=n) {
        k = (n+m)/2;
        v = ƒ(k);
        Δ = y-v;
        if (Math.abs(y-ƒ(m))<=ε) return m;
        if (Math.abs(y-ƒ(n))<=ε) return n;
        if (Math.abs(Δ)<=ε) return k;
        if (Δ>0) m = k;
        else     n = k;
    }
}

It smells to me like there ought to be an elegant solution, some sort of fencepost I'm not thinking of, that fixes this efficiently and elegantly.


texts:
I know that this code would look a lot better if I made it so that checking the current prices against the open prices were in a function. This would avoid rewriting it for every stock I want to check. But I'm not sure how to get started on doing that properly. Do any of you have some tips to get me started?

from yahoo_finance import Share

apple = Share('AAPL')

appleopen = float(apple.get_open())
applecurrent = float(apple.get_price())

if appleopen > applecurrent:
    print(("Apple is down for the day. Current price is"), applecurrent)
else:
    print(("Apple is up for the day! Current price is "), applecurrent)

applechange = (applecurrent - appleopen)
if applechange > 0:
    print(('The price moved'),abs(applechange),("to the upside today."))
else:
    print(('The priced moved'),abs(applechange),("to the downside today."))
print('-----------------------')
nflx = Share('NFLX')

nflxopen = float(nflx.get_open())
nflxcurrent = float(nflx.get_price())

if nflxopen > nflxcurrent:
    print(("Netflix is down for the day. Current price is"), nflxcurrent)
else:
    print(("Netflix is up for the day! Current price is "), nflxcurrent)

nflxchange = (nflxcurrent - nflxopen)
if nflxchange > 0:
    print(('The price moved'),abs(nflxchange),("to the upside today."))
else:
    print(('The priced moved'),abs(nflxchange),("to the downside today."))


texts: Simple interface and class for holding text to be analyzed

texts:
I am making a sentiment analysis library targeted first at social media text (like Twitter) and then I will expand it for more general use.

For the first step I am making a simple interface and a class that is going to be used for storing some data about the text to be analyzed like the text itself, it's manually annotated sentiment and the calculated sentiment that must be set only once (that's my current design anyway).

ObjectForAnalysis.java interface:

package com.github.dkanellis.sa_for_socialmedia.sentiment.objects;

public interface ObjectForAnalysis {

    double getManuallyAnnotatedMeanSentiment();

    double getCalculatedMeanSentiment();

    boolean isCalculated();

    void setCalculatedMeanSentiment(double calculatedMeanSentiment);
}

TwitterStatus.java implementation:

package com.github.dkanellis.sa_for_socialmedia.sentiment.objects;

public class TwitterStatus implements ObjectForAnalysis {

    private final long id;
    private final String text;
    private final double manuallyAnnotatedMeanSentiment;
    private double calculatedMeanSentiment;
    private boolean calculated;

    public TwitterStatus(long id, String text, double manuallyAnnotatedMeanSentiment) {
        this.id = id;
        this.text = text;
        this.manuallyAnnotatedMeanSentiment = manuallyAnnotatedMeanSentiment;
        this.calculated = false;
    }

    @Override
    public double getManuallyAnnotatedMeanSentiment() {
        return manuallyAnnotatedMeanSentiment;
    }

    @Override
    public double getCalculatedMeanSentiment() {
        if (isCalculated()) {
            return calculatedMeanSentiment;
        } else {
            throw new IllegalStateException("Mean sentiment has not been calculated yet.");
        }
    }

    @Override
    public boolean isCalculated() {
        return calculated;
    }

    @Override
    public void setCalculatedMeanSentiment(double calculatedMeanSentiment) {
        if (isCalculated()) {
            throw new IllegalStateException("Mean sentiment has already been calculated.");
        } else {
            this.calculatedMeanSentiment = calculatedMeanSentiment;
            calculated = true;
        }
    }

    @Override
    public String toString() {
        StringBuilder buffer = new StringBuilder();
        buffer.append("Tweet: ").append(id).append("\n");
        buffer.append("Text: ").append(text).append("\n");
        buffer.append("Manual Annotation: ").append(manuallyAnnotatedMeanSentiment).append("\n");
        buffer.append("Calculated Annotation: ")
                .append(isCalculated() ? "Not calculated" : calculatedMeanSentiment).append("\n");

        return buffer.toString();
    }

}

Feel free to critique anything from package naming to class naming to the way I implemented my constraint of having the mean sentiment set only once.


texts: Project Euler #3 (Largest prime factor) in Swift

texts:
As mentioned in Project Euler #2 in Swift, I intend to work my way through Project Euler using Swift to make sure there aren't any tricks I'm missing.

This is the problem statement for #3:

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143?

This solution if fewer lines of code, but it is recursive (and I don't know about you, but recursion usually takes me a second to wrap my head around).

Here's my solution:

import Darwin

extension Int {
    func isMultipleOf(factor: Int) -> Bool {
        return self % factor  == 0
    }
    func largestPossibleFactor() -> Int {
        let squareRoot: Double = sqrt(Double(self))
        return Int(ceil(squareRoot))
    }
}

func findLargestPrimeFactor(let fromNumber: Int) -> Int {
    for factor in 2..<fromNumber.largestPossibleFactor() {
        if fromNumber.isMultipleOf(factor) {
            return findLargestPrimeFactor(fromNumber/factor)
        }
    }
    return fromNumber
}

let target: Int = 600_851_475_143

let answer: Int = findLargestPrimeFactor(target)

I like Flambino's tip of using extensions and can't believe I forgot about it in my last question (which is part of why I'm doing this--build muscle memory), but I did manage to implement it here.

In plain-English, here's how the findLargestPrimeFactor algorithm works.

Starting at two, we start checking numbers to see whether or not it's a factor of the starting fromNumber.  If we find one, then fromNumber obviously isn't prime, so we return the largest possible prime of fromNumber divided by possibleFactor (which we now know is an actual factor).

We're essentially just dividing the fromNumber by its factors until we get to a number that has no factors (and is therefore prime).


texts: Build an Array of StringBuffer with x elements from a List of n elements

texts:
I have an initial list that contains: 1,2,3,4,5,6,7 I want to create an array of StringBuffer that contains only 3 items per element as StringBuffer(String):

1,2,3
4,5,6
7

Initially I resolved this problem as in the following example, but I don't want to use another list to do that:

List accounts = new ArrayList();
List<Person> listOfObjects = results.getResults();
for(Person p: listOfObjects) {
   String persAccount = p.getAccount();
   accounts.add(persAccount);
}
String s = listToString(accounts);

public String listToString(List list) {
 StringBuffer b = new StringBuffer();
    for (int i = 0; i < list.size(); i++) {
        b.append(String.valueOf(list.get(i)));
        if (i < list.size()-1)
            b.append(',').toString();
    }
    return b.toString();
}

I think that an efficent way will be to create a StringBuffer and append all values in the for block.(3 by 3).

How can I do it in an efficient way?


texts:
I passed a technical test the other day, one part included a cheap string validation and I am wondering this can be further improved to be more versatile to requirement changes.

The requirements were something like that

  Create a Validate method, which accepts a string and returns true if it's valid and false if it's not.

  A string is valid if it satisfies the rules below:

  The string must be at least 6 characters long and not exceed 16 characters.
  The string must contain only letters, numbers and optionally one hyphen (-).
  The string must start with a letter, and must not end with a hyphen.
  For example, validate("Michelle Belle"); would return false because it contains a space.

My solution was like that:

public static class ComparableExtensions
{
    public static bool IsStrictlyLowerThan<TComparable>(this TComparable comparable, TComparable value)
        where TComparable : IComparable<TComparable>
    {
        return comparable.CompareTo(value) < 0;
    }

    public static bool IsStrictlyGreaterThan<TComparable>(this TComparable comparable, TComparable value)
        where TComparable : IComparable<TComparable>
    {
        return comparable.CompareTo(value) > 0;
    }

    public static bool IsStrictlyNotBetween<TComparable>(this TComparable comparable, TComparable lowerBound, TComparable upperBound)
        where TComparable : IComparable<TComparable>
    {
        if (lowerBound.IsStrictlyGreaterThan(upperBound))
        {
            throw new ArgumentOutOfRangeException(nameof(lowerBound) + nameof(upperBound));
        }

        return comparable.IsStrictlyLowerThan(lowerBound) || comparable.IsStrictlyGreaterThan(upperBound);
    }
}

public static class CharExtensions
{
    public static bool IsLetterOrDigit(this char c)
    {
        return char.IsLetterOrDigit(c);
    }

    public static bool IsLetter(this char c)
    {
        return char.IsLetter(c);
    }

    public static bool IsHyphen(this char c)
    {
        return c == '-';
    }
}

public class Test
{
    public static bool Validate(string str)
    {
        if (str.Length.IsStrictlyNotBetween(6, 16))
        {
            return false;
        }

        if (!str.First().IsLetter() || str.Last().IsHyphen())
        {
            return false;
        }

        var hyphenCount = 0;

        for (var i = 1; i < str.Length - 1; i++)
        {
            if (str[i].IsLetterOrDigit())
            {
                continue;
            }
            if (str[i].IsHyphen())
            {
                hyphenCount++;
                if (hyphenCount > 1)
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        return true;
    }
}

I purposefully decided to not go with Regular Expressions to keep the logic readable and I am wondering if my code can be further refactored to incorporate new business rules.


texts:
I was solving the DIVFACT problem from Sphere Online Judge:

  Given a number, find the total number of divisors of the factorial of the number.
  Since the answer can be very large, print the answer modulo \$10^9+7\$.

  Input

  The first line contains \$T\$, the number of test cases

  \$T\$ lines follows each containing the number \$N\$.

  Constraints:

  \$ 1 \le T \le 500\$

  \$ 0 \le N \le 50000\$

To solve this I took the following approach: I first calculated the primes up to 50000 using a sieve, then for each prime \$p\$ computed the power of \$p\$ in \$N!\$ given by:

$$ \mathrm{power}(p) = \frac{n}{p} + \frac{n}{p^2} + \frac{n}{p^3} + \ldots $$

… until I got a \$p^\mathrm{power}\$ greater than \$N\$.

Finally I computed the answer for each prime \$p\$:

$$ (\mathrm{power}(p_1)+1) \cdot (\mathrm{power}(p_2)+1) \cdot \ldots \cdot (\mathrm{power}(p_k)+1)$$

assuming there are \$k\$ prime numbers less than 50000.

def prime_numbers(limit=50001):
    '''Prime number generator. Yields the series
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ...
    using Sieve of Eratosthenes.
    '''
    yield 2
    sub_limit = int(limit**0.5)
    flags = [True, True] + [False] * (limit - 2)
    # Step through all the odd numbers
    for i in range(3, limit, 2):
        if flags[i]:
            continue
        yield i
        # Exclude further multiples of the current prime number
        if i <= sub_limit:
            for j in range(i*i, limit, i<<1):
                flags[j] = True

p=list(prime_numbers())
# print p

for i in range(int(raw_input())):
    n=int(raw_input())
    d=[]
    pr=1
    for num in p:
        if num<=n:
            exp=1
            s=0
            while n>=num**exp:
                s+=int(n/(num**exp))
                exp+=1
            pr*=(s+1)
            # d.append(s)
        else:
            break
    print pr%1000000007

but this code and algo is not fast enough to pass the test cases in the given time limit.Is there any way to improve this code to make it faster


texts: 12 hours to 24 hours conversion function

texts:
I have made a time format converter which converts 12 hour format to 24 hour format. My convert_to_24() takes a string in format of HH:MM:SS followed by AM or PM. It returns a converted string to 24 hours format without the AM/PM string.

Note: Let us assume that input will always have no space between them e.g. 07:05:45PM, not 07:05:45 PM

def convert_to_24(time):
    """str -> str
    converts 12 hours time format to 24 hours
    """
    return time[:-2] if time[-2:] == "AM" else str(int(time[:2]) + 12) + time[2:8]

Sample usage:

>>> convert_to_24("07:05:45PM")
'19:05:45'
>>> convert_to_24("10:47:00PM")
'22:47:00'
>>> convert_to_24("02:35:36AM")
'02:35:36'
>>>

Can my function be made even better? By better I mean better in way of performance, design etc.


texts: Quicklyish finding primes by trial division

texts:
I ask because it seems to be taking waaaay more space/time than it should. Also, I know that if I want to be super efficient I should use Java's BitSet and a Sieve of Eratosthenes, but I wrote it like this to compare to a friend's implementation in C#.

(defn primes-upto [n]
  (let [primes (transient [2 3])]
    (loop [i 5]
      (if (> i n)
        (persistent! primes)
        (do (when
                (loop [j 0 is-prime true]
                  (let [p (primes j)]
                    (when is-prime
                      (if (> (* p p) i)
                        true
                        (recur (inc j) (not= 0 (mod i p)))))))
              (conj! primes i))
            (recur (+ i 2)))))))


texts: EclipseLink metadata generation with Gradle

texts:
I'm new to Gradle, so I expect many things I did wrong in my build script, which is pasted below.

What is special about that build script is, that it runs the EclipseLink metadata processor and copies the generated Entity_.java file to a folder in the sources directory.

Are there ways to make my Gradle script, which works, more elegant?

version '0.1'

apply plugin: 'idea'
apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    // http://mvnrepository.com/artifact/org.xerial/sqlite-jdbc
    compile group: 'org.xerial', name: 'sqlite-jdbc', version: '3.8.11.2'

    // http://mvnrepository.com/artifact/org.eclipse.persistence/org.eclipse.persistence.jpa
    compile group: 'org.eclipse.persistence', name: 'org.eclipse.persistence.jpa', version: '2.6.3'

    // http://mvnrepository.com/artifact/org.eclipse.persistence/org.eclipse.persistence.jpa.modelgen.processor
    compile group: 'org.eclipse.persistence', name: 'org.eclipse.persistence.jpa.modelgen.processor', version: '2.6.3'

    // http://mvnrepository.com/artifact/javax.mail/mail
    compile group: 'javax.mail', name: 'mail', version: '1.4.7'
}

sourceSets {
    main {
        java {
            srcDir 'src/gen/java'
        }
    }
}

task copyMetaModel(type: Copy) {
    includeEmptyDirs = false
    FileTree tree = fileTree(dir: "build/classes/main")
    tree.include "**/*_.java"
    from tree
    into "src/gen/java"
}

task cleanMetaModel(type: Delete) {
    delete fileTree(dir: 'src/gen/java', exclude: '.keep')
}

compileJava.doFirst {
    Map otherArgs = [
            destdir: destinationDir,
            includeAntRuntime: false,
            source: sourceCompatibility,
            target: targetCompatibility,
            classpath: configurations.compile.asPath,
            failonerror: true
    ]
    options.compilerArgs = [
            "-Aeclipselink.persistencexml=${new File(project.projectDir, 'src/main/resources/META-INF/persistence.xml').absolutePath}"
    ]
    tasks.cleanMetaModel.execute()
    Map antOptions = otherArgs + options.optionMap()
    ant.javac(antOptions) {
        source.addToAntBuilder(ant, 'src', FileCollection.AntType.MatchingTask)
        options.compilerArgs.each {value ->
            compilerarg(value: value)
        }
    }
}

compileJava.doLast {
    tasks.copyMetaModel.execute()
}


texts:
I have created this first-timer implementation of Merge Sort
and I got confused by the C++ syntax once or twice.

So I have some questions about this code:

#include <iostream>
#include <thread>
#include <cstdlib>
#include <vector>

#define NUM 1048576*2

int sort(std::vector<int>* vec);
void run(std::vector<int>* vec, int left, int right);
void merge(std::vector<int>* vec, int left, int mid, int right);

int main() {
    srand(time(NULL));
    std::vector<int> tobesorted;
    for(int i = 0; i < NUM; i++){
        tobesorted.push_back(rand());
    }

    sort(&tobesorted);

    for(int i = 0; i < NUM; i++){
        std::cout << tobesorted[i] << ", ";
    }
    std::cout << std::endl;
    std::cout << "End of Program!";

}
int sort(std::vector<int>* pvec){
    int size = pvec->size();
    std::thread t1(run, pvec, 0, 0.25*size);
    std::thread t2(run, pvec, 0.25*size+1, 0.5*size);
    std::thread t3(run, pvec, 0.5*size+1, 0.75*size);
    std::thread t4(run, pvec, 0.75*size, size-1);

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    std::thread t5(merge, pvec, 0, 0.25*size, 0.5*size);
    merge(pvec, 0.5*size+1, 0.75*size, size-1);
    t5.join();

    merge(pvec, 0, 0.5*size, size-1);

    return 1;
}

void run(std::vector<int>* pvec, int left, int right){
    if(right - left == 0){
        return;
    }
    int mid = (left+ right)/2;
    run(pvec, left,mid);
    run(pvec, mid+1, right);

    merge(pvec, left, mid, right);

}

void merge(std::vector<int>* pvec, int left, int mid, int right){
    int ileft = 0;
    int iright = 0;
    int index = 0;

    std::vector<int> leftvec;
    std::vector<int> rightvec;

    int j = 0;
    for(int i= left; i <= mid; i++){
        leftvec.push_back(pvec[0][i]);
    }
    j = 0;
    for(int i= mid+1; i <= right; i++){
        rightvec.push_back(pvec[0][i]);
    }

    while(ileft < leftvec.size() && iright < rightvec.size()){
        if(leftvec[ileft] > rightvec[iright]){
            pvec[0][left+index] = leftvec[ileft++];
            index++;
        } else {
            pvec[0][left+index] = rightvec[iright++];
            index++;
        }
    }

    while(ileft < leftvec.size()){
        pvec[0][left+index] = leftvec[ileft++];
        index++;
    }

    while(iright < rightvec.size()){
        pvec[0][left+index] = rightvec[iright++];
        index++;
    }

}

I think I should have better optimized for better cache use, do you see any opportunities there?
What could have been generally improved on that code?


texts: Check whether a given sequence can be rearranged using a stack

texts:
Working on a problem, for a given input sequence to a stack, check whether it could produce (using stack push/pop operations) the output sequence.

For example if input is [1,2,3,4,5], possible output is [4,5,3,2,1] (push 1, push 2, push 3, push 4, pop 4, push 5, pop 5, pop 3, pop 2, pop 1), but [4,3,5,1,2] is not a feasible output.

Here is my code written in Python 2.7, and wondering if logically is correct?

stackInput = [1,2,3,4,5]
expOutput = [4,5,3,2,1] # return True
#expOutput = [4,3,5,1,2] # return False
stack = []
outputIndex = 0
result = True
i = 0

while i < (len(stackInput)):
    stack.append(stackInput[i])
    i += 1
    while outputIndex < len(expOutput) and stack[-1] == expOutput[outputIndex]:
        stack.pop(-1)
        outputIndex += 1

print outputIndex == len(expOutput)


texts:
My function works pretty slowly with big results from the db (420000 records and growing). Can some one give me any proposal to make it faster?

 public void GenerateExcelFileWithSPResultData(IEnumerable<Plans_Result> datasource, string excelFile)
    {

        var excelPackage = new ExcelPackage();
        ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("Plans");

        ws.Cells[1, 1].Value = "ACC_DATE";
        ws.Cells[1, 2].Value = "DUE_DATE";
        ws.Cells[1, 3].Value = "IDENTIFIER_VALUE";
        ws.Cells[1, 4].Value = "INSTALLMENT_NO";
        ws.Cells[1, 5].Value = "PRINCIPAL_AMT_DUE";
        ws.Cells[1, 6].Value = "SPA";

        for (int i = 0; i < datasource.Count(); i++)
        {
            ws.Cells[i + 2, 1].Value = datasource.ElementAt(i).ACC_DATE;
            ws.Cells[i + 2, 2].Value = datasource.ElementAt(i).DUE_DATE;
            ws.Cells[i + 2, 3].Value = datasource.ElementAt(i).IDENTIFIER_VALUE;
            ws.Cells[i + 2, 4].Value = datasource.ElementAt(i).INSTALLMENT_NO;
            ws.Cells[i + 2, 5].Value = datasource.ElementAt(i).PRINCIPAL_AMT_DUE;
            ws.Cells[i + 2, 6].Value = datasource.ElementAt(i).SPA;
        }

        using (ExcelRange rng = ws.Cells["A1:F1"])
        {
            rng.Style.Font.Bold = true;
            rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
            rng.Style.Fill.BackgroundColor.SetColor(Color.Yellow);
            rng.Style.Font.Color.SetColor(Color.Black);
        }
        byte[] data = excelPackage.GetAsByteArray();

        File.WriteAllBytes(excelFile, data);
    }


texts: Cracking the code interview: Problem 1 .6 basic string compression

texts:
I created a GitHub repository containing my code solutions for some of the exercises proposed in the book. I updated my solution for the problem 1.6 here.

Description

  A function that compress the original string and store the compressed
  string in compress ex. aabcccccaaa will become a2blc5a3. If the
  compressed string is longer than the original it returns the
  original string.

Here's the code:

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

const char *compression(const char *original, char *compress) {
    size_t len, i, j, nc;

    /*memorize the first char of original in compress*/
    char previous = original[0];
    len = strlen(original);
    nc = 1;

    for (i = 1, j = 0; i < len; ++i) {
        if (original[i] == previous) {
            ++nc;
        } else {
            compress[j++] = previous;
            compress[j++] = nc + '0';
            nc = 1;
            previous = original[i];

        }

    }
    /* there are characters still in the stream */
    compress[j++] = previous;
    compress[j++] = nc + '0';
    compress[j] = '\0';

    if (strlen(compress) >= len) return original;
    return compress;
}

int main() {
    char buffer[20] = {0};
    printf("%s\n", compression("aabcccccaaa", buffer));
    return 0;
}

I'm looking for possible improvement of the code or better algorithm to solve the problem.


texts: Challenge: phone keypad to letters - return all possible strings

texts:
The challenge:

Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent. You can assume each valid number in the mapping is a single digit.

Example:

If {"2": ["a", "b", "c"], 3: ["d", "e", "f"], …}
then "23" should return ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

My iterative solution:

const digitMap = (digiStr) => {

  const digitMapping = {
    2: ['a', 'b', 'c'],
    3: ['d', 'e', 'f'],
    4: ['g', 'h', 'i'],
    5: ['j', 'k', 'l'],
    6: ['m', 'n', 'o'],
    7: ['p', 'q', 'r', 's'],
    8: ['t', 'u', 'v'],
    9: ['w', 'x', 'y', 'z']
  }
  const length = digiStr.length;
  if (length === 1) return digitMapping[digiStr]; // in case of single digit strings
  const indexes = []; // index addresses of charsets, in order
  for (let i = 0; i < length; i++) {
    indexes.push(0);
  }
  let nextI = length === 2 ? 0 : 1; // current spot of nextI in indexes
  const possibleStrs = []; // for final answer of possible permutations
  let str = '';
  let endCount = 0; // if all addresses in indexes are at their end, then break while loop
  while (true) {
    console.log(indexes);
    for (let i = 0; i < length; i++) {
      str += digitMapping[digiStr[i]][indexes[i]];
      if (indexes[i] === digitMapping[digiStr[i]].length - 1) {
        endCount += 1;
      }
    }
    possibleStrs.push(str);
    str = '';
    if (endCount === length) {
      break;
    }
    endCount = 0;
    // increment last item in indexes as long as it < length of corresponding inner char array
    if (indexes[indexes.length - 1] < digitMapping[digiStr[digiStr.length - 1]].length - 1) {
      indexes[indexes.length - 1] += 1;
    }
    else {
      indexes[indexes.length - 1] = 0;
      // increment nextI as long as < length of corresponding inner array
      if (indexes[nextI] < digitMapping[digiStr[nextI]].length - 1) {
        indexes[nextI] += 1;
      }
      else {
      // otherwise shift position of nextI in indexes array
        // if next position of nextI not end of indexes array
          // shift nextI 1 spot forward in indexes
        if (nextI + 1 < length - 1) {
          nextI += 1;
          indexes[nextI] += 1;
        }
        else {
          // else reset all indexes to 0, starting from position 1
          for (let i = 1; i < indexes.length; i++) {
            indexes[i] = 0;
          }
          // increment first item in indexes
          indexes[0] += 1;
          nextI = 1; // place nextI at position 1
        }
      }
    }
  }
  return possibleStrs;
}

console.log(digitMap("2"));
console.log(digitMap("23"));
console.log(digitMap("234"));
console.log(digitMap("2345"));
console.log(digitMap("23456"));

Produces the correct output for all test cases. Any alternative approaches--recursive or iterative--to cleaning up the conditional logic would be greatly appreciated.


texts: Trying (and failing) to implement the best conventions on OOP Swift

texts:
I'm making a MacOS app that will do some analysis on the user's calendar data. For now it only supports Apple's native calendar (EventKit), but I will later add support to Google, outlook, etc.

Models/Events/Base.swift:

import Foundation

struct EventData {
    var title: String;
    var startDate: Date;
    var endDate: Date;
    var organizerName: String;
    var notes: String;
    var location: String;
}

struct CalendarData {
    var title: String;
    var isSubscribed: Bool;
}

class Events {
    init() {
        checkForAuthorization();
    }

    func checkForAuthorization() {}
    func requestAccess() {}
    func getCalendars() -> [CalendarData] {
        return [];
    }
    func getEvents(calendarName: String, from: Date, to: Date) -> [EventData] {
        return [];
    }
}

Models/Events/iCal.swift:

import Foundation
import EventKit

class iCal: Events {

    let eventStore = EKEventStore();
    var calendars: [EKCalendar]?;

    override func checkForAuthorization() {
        let status = EKEventStore.authorizationStatus(for: EKEntityType.event);

        switch (status) {
            case EKAuthorizationStatus.notDetermined:
                self.requestAccess();
                break;
            case EKAuthorizationStatus.authorized:
                break;
            case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:
                break;
         }
    }

    override func requestAccess() {
        eventStore.requestAccess(to: EKEntityType.event, completion:{ (accessGranted: Bool, error: Error?) in
            if accessGranted == true {
                print("Granted")
            } else {
                print("Denied")
            }
        });
    }

    override func getCalendars() -> [CalendarData] {
        let _cals = self.eventStore.calendars(for: .event);
        var cals: [CalendarData] = [];

        for cal: EKCalendar in _cals {
            cals.append(CalendarData(title: cal.title, isSubscribed: cal.isSubscribed));
        }
        return cals;
    }
    override func getEvents(calendarName: String, from: Date, to: Date) -> [EventData] {
        let cals = self.eventStore.calendars(for: .event);
        var events: [EventData] = [];

        if let calIndex: Int = cals.firstIndex(where: { $0.title == calendarName }) {
            let selectedCalendar: EKCalendar = cals[calIndex];

            let predicate = eventStore.predicateForEvents(withStart: from, end: to, calendars: [selectedCalendar])
            let _events = eventStore.events(matching: predicate) as [EKEvent];

            for ev: EKEvent in _events {
                events.append(
                    EventData(
                        title: ev.title,
                        startDate: ev.startDate,
                        endDate: ev.endDate,
                        organizerName: ev.organizer?.name ?? "",
                        notes: ev.notes ?? "",
                        location: ev.location ?? ""
                    )
                );
            }

        }

        return events;
    }
}

And I use this class like this:

let calendar = iCal();
for cal in calendar.getCalendars() {
   print("****** \(cal.title) *******\n");
   print(calendar.getEvents(calendarName: cal.title, from: Calendar.current.date(byAdding: .day, value: -2, to: Date())!, to: Calendar.current.date(byAdding: .day, value: 1, to: Date())!))
}

This works, but it feels very wrong...
I know the semi-colons are not needed, but I always used it in other languages and the linting will delete them anyway after.

Questions:

How can I improve this?
Would it be better to instantiate the class
Events, by passing the calendar type as an argument (eg. iCal,
outlook, etc)
Are those structs ok? As in should they go in another
file?

Thank you


texts: Remove the occurences of an element from array if it occurs more than n times

texts:
I wanted to remove the occurrence of an element from an array if it occurs more than n times. For example:

{ 20, 37, 20, 21 } (n->1) -> { 20, 37, 21}
{ 1, 1, 1, 1, 1 }  (n->5) -> { 1, 1, 1, 1, 1 }
{ 1, 2, 3, 1, 1, 2, 1, 2, 3, 3, 2, 4, 5, 3, 1 } (n->3 ) -> { 1, 2, 3, 1, 1, 2, 2, 3, 3, 4, 5 }

I tried the following code in java:

public class arr{
    public static void main(String[] args){
        int a[] = {1,1,3,3,7,2,2,2,2}; //Array of the elements
        int b =3; // maximum occurrences
        int u=1;  // Counter for same number of elements
        int c[] = new int[nterms(a, b)]; //initializing new array
        int k=0;
        int l=0;
        for(int i =a.length-1; i>=0; i--){
            k=0;
            // Checking the duplicate elements.
            for(int j=i-1; j>=0; j--){
                if(a[i]==a[j]){
                    k++;
                }
            }
            if(k!=b){
                c[c.length-u] = a[i];
                u++;
            }
        }
        for(int i =0; i<c.length; i++)
            System.out.println(c[i]);
    }

    // Returns no. of unique elements.
    public static int nterms(int[] x, int y){
        int k=0;
        int l=0;
        for(int i =0; i<x.length; i++){
            k=0;
            for(int j=i+1; j<x.length; j++){
                if(x[i]==x[j]){
                    k++;
                }
            }
            if(k==y){
                l++;
            }
        }
        return (x.length-l);
    }
}

It works fine but can anybody recommend a more short & efficient way.


texts:
I am in the process of making an assembler and one of the needed steps is actually getting the opcode from a table. However, the instruction set I'm working on has a handful of different addressing modes which give different opcodes. On top of that, even if you have the same mode the parameter size changes the opcode as well. This means to get an opcode I need to provide an instruction, an addressing mode, and a size. I also need to be able to get the average size for an addressing mode for setting an estimated size for another portion of my code.

My first solution was to make a large map to hold all the values. This has turned into a 200+ line triple-nested map. Something like this:

// <Instruction, <Addressing Mode, <Size, Opcode>>>
std::map<std::string, std::map<AddressMode, std::map<int, int>>> OpcodeTable = {
  {"ADC", {{Indirect_X, {{2, 0x61}}},
          {Stack, {{2, 0x63}}},
          {Direct, {{2, 0x65}, {3, 0x6D}, {4, 0x6F}}},
          {Indirect_Long, {{2, 0x67}}},
          {Immediate, {{2, 0x69}}},
          {Indirect_Y, {{2, 0x71}}},
          {Indirect, {{2, 0x72}}},
          {Stack_Y, {{2, 0x73}}},
          {Indexed_X, {{2, 0x75}, {3, 0x7D}, {4, 0x7F}}},
          {Indirect_Long_Y, {{2, 0x77}}},
          {Indexed_Y, {{3, 0x79}}}}},
   // and so on for every instruction
};

Currently I access this table through a function called get_opcode which hides the ugliness of navigating this map.

// Checks whether a given value exists in the table or not
bool has_opcode(std::string& instr, AddressMode& mode, int size)
{
  return (detail::OpcodeTable[instr].count(mode) == 1) &&
         (detail::OpcodeTable[instr][mode].count(size) == 1);
}

uint8_t get_opcode(std::string& instr, AddressMode& mode, int size)
{
  if (has_opcode(instr, mode, size))
  {
    return detail::OpcodeTable[instr][mode][size];
  }

  // If an invalid instruction is found, throw an exception with details on what it found.
  throw InvalidInstructionException(
          "Invalid instruction: " + instr +
          " with size " + util::to_string(size) +
          " and mode " + AddressModeString[mode] +
          " does not exist.");
}

I have seen ideas for using a pair as a key, and that helps slightly. It effectively turns into this, but I am not sure if this is a notable improvement.

std::map<std::pair<std::string, AddressMode>, std::map<int, int>> OpcodeTable = {
  {{"ADC", Indirect_X}, {{2, 0x61}}},
  {{"ADC", Stack}, {{2, 0x63}}},
  {{"ADC", Direct}, {{2, 0x65}, {3, 0x6D}, {4, 0x6F}}},
  {{"ADC", Indirect_Long}, {{2, 0x67}}},
  {{"ADC", Immediate}, {{2, 0x69}}},
  {{"ADC", Indirect_Y}, {{2, 0x71}}},
  {{"ADC", Indirect}, {{2, 0x72}}},
  {{"ADC", Stack_Y}, {{2, 0x73}}},
  {{"ADC", Indexed_X}, {{2, 0x75}, {3, 0x7D}, {4, 0x7F}}},
  {{"ADC", Indirect_Long_Y}, {{2, 0x77}}},
  {{"ADC", Indexed_Y}, {{3, 0x79}}},
  // and so on for every instruction
};

Is there any cleaner way to structure this data? I don't need to avoid maps entirely, but I feel like I might have gone overboard with this setup.


texts:
I am relatively new to C programming and I am currently working through the CS50 EDX course. The problem I have solved below is for week 1 (credit).

Any suggestions on how to improve this code to further my learning would be most appreciated. I feel like my solution is very clunky although it does the job!

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
    long number = get_long("Number: ");

    // get the individual intergers of number
    // *2 odd digits

    int i1 = ((number / 1000000000000000) % 10);
    int t1 = i1 * 2;
    int i2 = ((number / 100000000000000) % 10);
    int i3 = ((number / 10000000000000) % 10);
        int t3 = i3 * 2;
    int i4 = ((number / 1000000000000) % 10);
    int i5 = ((number / 100000000000) % 10);
        int t5 = i5 * 2;
    int i6 = ((number / 10000000000) % 10);
    int i7 = ((number / 1000000000) % 10);
        int t7 = i7 * 2;
    int i8 = ((number / 100000000) % 10);
    int i9 = ((number / 10000000) % 10);
        int t9 = i9 * 2;
    int i10 = ((number / 1000000) % 10);
    int i11 = ((number / 100000) % 10);
        int t11 = i11 * 2;
    int i12 = ((number / 10000) % 10);
    int i13 = ((number / 1000) % 10);
        int t13 = i13 * 2;
    int i14 = ((number / 100) % 10);
    int i15 = ((number / 10) % 10);
        int t15 = i15 * 2;
    int i16 = (number % 10);

    // Luhns Alg
    // calculate sum of variable digits if > 9

    if (t1>9)
    {t1 = t1 - 9;}
    if (t3>9)
    {t3 = t3 - 9;}
    if (t5>9)
    {t5 = t5 - 9;}
    if (t7>9)
    {t7 = t7 - 9;}
    if (t9>9)
    {t9 = t9 - 9;}
    if (t11>9)
    {t11 = t11 - 9;}
    if (t13>9)
    {t13 = t13 - 9;}
    if (t15>9)
    {t15 = t15 - 9;}

    // check lunghs algo = true (0)
    // print card type

    int sum = (t1+t3+t5+t7+t9+t11+t13+t15+i2+i4+i6+i8+i10+i12+i14+i16);
    int check = (sum % 10);

    if (check != 0)
    printf("INVALID\n");
    else
    {
    // check type of card
        if(i1 == 0 && i2 == 3 && i3 == 4)
        {
            printf("AMEX\n");
        }
        else if(i1 == 0 && i2 == 3 && i3 == 7)
        {
            printf("AMEX\n");
        }
        else if (i1 == 5 && (i2 == 1 || i2 == 2 || i2 == 3 || i2 == 4 || i2 == 5))
        {
            printf("MASTERCARD\n");
        }
        else if (i1 == 4)
        {
            printf("VISA\n");
        }
        else
            printf("INVALID\n");
    }
}

The code currently outputs the correct results below.

378282246310005 = AMEX
5555555555554444 = MASTERCARD
5105105105105100 = MASTERCARD
4111111111111111 = VISA
5673598276138003 = INVALID
4062901840 = INVALID


texts: Compute conditional median of PANDAS dataframe

texts:
I am new to Python/Pandas.
Consider the following code:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Time': [0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 0.0, 2.0, 0.0, 1.0, 2.0],
                   'Id': [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4],
                   'A': [10, 15, np.NaN, 11, 16, 25, 10, 15, 9, 14, 19]})
print(df)

Output:

       A  Id  Time
0   10.0   1   0.0
1   15.0   1   1.0
2    NaN   1   2.0
3   11.0   2   0.0
4   16.0   2   1.0
5   25.0   2   2.0
6   10.0   3   0.0
7   15.0   3   2.0
8    9.0   4   0.0
9   14.0   4   1.0
10  19.0   4   2.0

I want to add a column Feature_1 which, for each row of the dataframe, compute the median of column A for ALL the values which have the same Time value. This can be done as follows:

df['Feature_1'] = df.groupby('Time')['A'].transform(np.median)
print(df)

Output:

       A  Id  Time  Feature_1
0   10.0   1   0.0       10.0
1   15.0   1   1.0       15.0
2    NaN   1   2.0       19.0
3   11.0   2   0.0       10.0
4   16.0   2   1.0       15.0
5   25.0   2   2.0       19.0
6   10.0   3   0.0       10.0
7   15.0   3   2.0       19.0
8    9.0   4   0.0       10.0
9   14.0   4   1.0       15.0
10  19.0   4   2.0       19.0

My problem is now to compute another feature, Feature_2, which for each row of the dataframe, compute the median of column A for OTHER values which have the same Time value. I was not able to vectorize this, so my solution with a for loop:

df['feature_2'] = np.NaN

for i in range(len(df)):

    current_Id = df.Id[i]
    current_time = df.Time[i]

    idx = (df.Time == current_time) & (df.Id != current_Id)

    if idx.any():
        df['feature_2'][i] = df.A[idx].median()

print(df)

Output:

       A  Id  Time  Feature_1  Feature_2
0   10.0   1   0.0       10.0       10.0
1   15.0   1   1.0       15.0       15.0
2    NaN   1   2.0       19.0       19.0
3   11.0   2   0.0       10.0       10.0
4   16.0   2   1.0       15.0       14.5
5   25.0   2   2.0       19.0       17.0
6   10.0   3   0.0       10.0       10.0
7   15.0   3   2.0       19.0       22.0
8    9.0   4   0.0       10.0       10.0
9   14.0   4   1.0       15.0       15.5
10  19.0   4   2.0       19.0       20.0

This is working but it is very slow as my dataframe has 1 million rows (but only four different IDs).

Is it possible to vectorize the creation of Feature_2 ?

I hope, I am clear enough. Live code can be found here.


texts: For each line in a file, read two integers and output the minimum

texts:
I am going through some CodingAbbey problems to learn basic programming tasks, with a focus on taking input from a file, and saving to another. I have just completed this task:

  Of two numbers, please, select one with minimum value. Here are several pairs of numbers for thorough testing.

  Input data will contain number of test-cases in the first line.
  Following lines will contain a pair of numbers to compare each.
  For Answer please enter the same amount of minimums separated by space, for example:

  data:

3
5 3
2 8
100 15

  answer:

3 2 15

Here is my code:

using System;

namespace cosnPrjo
{
    class MinimumOfTwo
    {

        const string inputPath = @"/Users/rs/Dropbox/InputFile.txt";
        const string outputPath = @"/Users/rs/Dropbox/OutputFile.txt";
        const string searchAfterParam = "\n";

        static void Main ()
        {
            string input = readFile (inputPath);
            input = input.Substring (input.IndexOf (searchAfterParam) + searchAfterParam.Length);
            string[] pairDelims = { "\n" };
            string[] paramDelims = { " " };
            string[] pairs = input.Split (pairDelims, StringSplitOptions.RemoveEmptyEntries);
            string result = "";

            foreach (string pair in pairs) {
                int numToAppend = 0;
                string[] paramas = pair.Split (paramDelims, StringSplitOptions.RemoveEmptyEntries);

                int firstNum = Convert.ToInt32 (paramas [0]);
                int secondNum = Convert.ToInt32 (paramas [1]);

                numToAppend = firstNum < secondNum ? firstNum : secondNum;

                result += numToAppend.ToString () + " ";
            }
            writeFile (outputPath, result.TrimEnd ());
        }

        static string readFile (string input)
        {
            return System.IO.File.ReadAllText (input);
        }

        static void writeFile (string path, string contents)
        {
            System.IO.File.WriteAllText (path, contents);
        }
    }
}

My questions are:

Is this method (reading from and writing to files) an effective and/or sensible way to deal with multi-line input? I find it more cumbersome when I am using the console.
Should a StringBuilder be used to append elements to string in this case?
Is the exercise of ignoring the first number, as I have done here, useful or useless in this context? I don't need to use that number, but should I?
This code is pretty long for such a small task. Is it more useful to write shorter code for such tasks?


texts: Find 2 numbers that multiply to a number and add to another number

texts:
Here is my code, however, I am unsure whether it is the fastest way to achieve this objective.

import random

add_to = int(input("2 numbers must add to: "))
multiply_to = int(input("2 numbers must multiyply to: "))
solved = False

while solved == False:
    nums = random.sample(range(-100, 150), 2)
    if (nums[0] + nums[1] == add_to) and (nums[0] * nums[1] == multiply_to):
        print(nums)
        print('Solved')
        break

Question:
1. Is it possible for the range to be set based upon the input of numbers given by the user.


texts: Hough transform algorithm - Idiomatic c++

texts:
I've got some working code to compute the Hough transform for circles:

#include <stdio.h>
#include <opencv/cv.hpp>
#include <math.h>
#include <string>
#include <iostream>

int *** allocate3DArray(int y, int x, int r)  {
    int ***array = (int***)malloc(sizeof(int**)*y);
    for (int i = 0; i < y; i++)  {
        array[i] = (int**)malloc(sizeof(int*)*x);
        for (int j = 0; j < x; j++)  {
            array[i][j] = (int*)malloc(sizeof(int)*r);
            for(int k = 0; k < r; k++) {
                array[i][j][k] = 0;
            }
        }
    }
    return array;

}

void free3d(int ***arr, int y, int x, int r)  {
    for (int i = 0; i < y; i++)  {
        for (int j = 0; j < x; j++)  {
            free(arr[i][j]);
        }
        free(arr[i]);

    }
    free(arr);

}

vector<Circle> HoughTransformCircles(Mat image, Mat &gradient_mag, Mat &gradient_dir)  {
    //Maximum circle radius is rLen = image.width / 2
    int rLen = image.rows/2;
    int ***houghSpace = allocate3DArray(image.rows, image.cols, rLen);
    for (int y = 0; y < image.rows; y++) {
        for (int x = 0; x < image.cols; x++) {
            for (int r = 0; r < rLen; r++)     {
                int x0 = x - (int)(r*cos(gradient_dir.at<double>(y, x)));
                int y0 = y - (int)(r*sin(gradient_dir.at<double>(y, x)));
                if(x0 >= 0 && x0 < image.cols && y0 >= 0 && y0 < image.rows )  {
                    houghSpace[y0][x0][r]++;
                }
                x0 = x + (int)(r*cos(gradient_dir.at<double>(y, x)));
                y0 = y + (int)(r*sin(gradient_dir.at<double>(y, x)));
                if(x0 >= 0 && x0 < image.cols && y0 >= 0 && y0 < image.rows )  {
                    houghSpace[y0][x0][r]++;
                }

            }
        }
    }
    vector<Circle> circles;
    for (int y = 0; y < image.rows; y++)    {
        for (int x = 0; x < image.cols; x++)  {
            for (int r = 0; r < rLen; r++)  {
                if (houghSpace[y][x][r] > 30)  {
                    Circle temp  = Circle(x, y, r);
                    circles.push_back(temp);
                }
            }
        }
    }

    free3d(houghSpace, image.rows, image.cols, rLen);

   return circles;
}

How do I make this as idiomatic as possible? I am not allowed to use C++ 11  unfortunately.


texts:
Is there a faster way to get all primes between 0 - n?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace myPrime
{
    public class simplePrimer
    {
        public List<BigInteger> primeList;

        public void findVersion(BigInteger goal)
        {
            BigInteger number = 3;
            primeList = new List<BigInteger> { 2 };

            try
            {
                while (number < goal)
                {
                    if (isPrime(number))
                        primeList.Add(number);
                    number += 2;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("i found " + primeList.Count + " Prime Numbers");
                Console.WriteLine(primeList.Last() + "was the last Prime");
            }
        }

        private bool isPrime(BigInteger number)
        {
            foreach (BigInteger prime in primeList)
                if (number % prime == 0)
                    return false;

            return true;
        }
    }
}

You can call it like:

primer.findVersion1(999999);


texts:
I need to return private collection and

avoid calling code modifying them
avoiding copying overhead if possible

So I thought of returning copy-on-write arrays, hashes, and sets.

I couldn't find any implementations of these, so I tried my own.

require 'delegate'
require 'set'

module Cow end

class Cow::Base < SimpleDelegator
  def initialize(obj)
    super
    obj.freeze
    @copied = false
  end

  def method_missing(*args, &block)
    if @copied
      super
    else
      begin
        super
      rescue RuntimeError => e
        if e.to_s.include? 'can\'t modify frozen'
          __setobj__ __getobj__.dup
          @copied = true
          super
        else
          raise
        end
      end
    end
  end
end

module CowClass
  def cow
    Cow::Base.new self
  end
end

class Array
  include CowClass
end

class Hash
  include CowClass
end

class Set
  include CowClass
end

And then used like

a = [1, 2, 3]
b = a.cow
b << 4
puts a.join ' ' # 1 2 3
puts b.join ' ' # 1 2 3 4

Suggestions? Applause? Boos?

Thread-safety is a non-goal.


texts: Generate a random numbers class - follow-up

texts:
Previous question:

Generate a random numbers class

I have come up with three different ways to define type of mUniformDistribution. All of them work fine in VC++ 2013 and GCC.

First approach by SFINAE:

template<typename U >
static typename std::enable_if<
    std::is_integral<U>::value,
    std::uniform_int_distribution<U>
>::type dist();

template<typename U >
static typename std::enable_if<
    std::is_floating_point<U>::value,
    std::uniform_real_distribution<U>
>::type dist();

decltype(dist<T>()) mUniformDistribution;

Second approach by SFINAE:

template<typename U, typename std::enable_if<std::is_integral<U>::value>::type* = nullptr>
static auto dist() -> std::uniform_int_distribution<U>;

template<typename U, typename std::enable_if<std::is_floating_point<U>::value>::type* = nullptr>
static auto dist() -> std::uniform_rea_distribution<U>;

decltype(dist<T>()) mUniformDistribution;

Third approach:

I'm quite comfortable with it for simplicity.

template <typename T>
using dist = typename std::conditional<
    std::is_integral<T>::value,
    std::uniform_int_distribution<T>,
    std::uniform_real_distribution<T>>::type;

dist<T> mUniformDistribution;

which one is the better approach and why?

Code sample:

#include <random>
#include <iostream>
#include <type_traits>

template<typename T >
class Random
{
public:
    Random(const T& min, const T& max)
        : mUniformDistribution(min, max)
    {}

    T operator()()
    {
        return mUniformDistribution(mEngine);
    }

private:
    std::default_random_engine mEngine{ std::random_device()() };
    /////////////////////////////////////////
    // first approach
    //
    //template<typename U >
    //static typename std::enable_if<
    //  std::is_integral<U>::value,
    //  std::uniform_int_distribution<U>
    //>::type dist();
    //
    //template<typename U >
    //static typename std::enable_if<
    //  std::is_floating_point<U>::value,
    //  std::uniform_real_distribution<U>
    //>::type dist();
    //decltype(dist<T>()) mUniformDistribution;

    //////////////////////////////////////////
    // second approach
    //
    //template<typename U, typename std::enable_if<std::is_integral<U>::value>::type* = nullptr>
    //static auto   dist() -> std::uniform_int_distribution<U>;
    //
    //template<typename U, typename std::enable_if<std::is_floating_point<U>::value>::type* = nullptr>
    //static auto   dist() -> std::uniform_real_distribution<U>;
    //decltype(dist<T>()) mUniformDistribution;

    //////////////////////////////////////////
    // third approach
    //
    template <typename U>
    using dist = typename std::conditional<
        std::is_integral<U>::value,
        std::uniform_int_distribution<U>,
        std::uniform_real_distribution<U>>::type;

    dist<T> mUniformDistribution;
};

int main()
{
    Random<int> getRandom(0, 9);
    for (int i = 0; i<9; ++i)
        std::cout << getRandom() << '\n';
}


texts: Advent of Code 2018 Day 1 in OCaml: Find length of cycles when accumulating deltas

texts:
I just started Advent of Code 2018. This is exercise 2 of day 1, and I can't understand why my code is so slow (4 minutes 37 seconds, compared to 200ms for a friend who did it in Clojure with the same computer).

Basically, it accumulates integers from a provided list of ints, named input. Whenever the current value of the accumulator is equal to one of its previous values, it is returned. We might have to loop many times over the provided list before we find such an occurrence. Here is the code:

  let main () =
    let rec my_slow_code lst history =
        if lst == [] then my_slow_code input history
        else
          let current = List.hd lst + List.hd history in
          if List.mem current history then current
          else my_slow_code (List.tl lst) (current :: history)
      in
      my_slow_code input [0]

I can't understand what mistake here makes such a slow code, maybe the use of List.mem?


texts: Detecting the total amount of RAM installed on a hardware from a Linux system using a POSIX shell script

texts:
Today, I gave myself a small task of detecting the total amount of RAM installed on a hardware from a Linux system using a POSIX shell script. I ended up using dmidecode utility and a rather complex looking code for such a simple task.

Though I found countless simple pieces of code on various places, they are all doing not just that exactly.

I don't want free RAM or total available RAM to the kernel.

I want the pure number of MiBs, which are installed in the hardware (memory sticks).

Reasons are multiple, to name one, for example, there could be less available RAM to the system due to various things, like integrated graphics shared memory, etc.

Performance is not an issue. I know it is slow. I just want to know if there is a way to perhaps simplify the code.

#!/bin/sh

is_number()
{
    [ "${1}" -eq "${1}" ] 2> /dev/null
}

ram_entries=$(sudo dmidecode --type 17 | grep Size: | awk '{ print $2 }')
ram_entries_count=$(( $(printf '%s\n' "${ram_entries}" | wc -l) - 1 ))

i=0
ram_entry=x
total_ram_size_mb=0

while [ "${i}" -le "${ram_entries_count}" ]
do
    is_number "${ram_entry}" && total_ram_size_mb=$(( total_ram_size_mb + ram_entry ))
    i=$(( i + 1 ))
    ram_entry=$(echo "${ram_entries}" | sed --posix --quiet "${i}{p;q}")
done

if [ "${total_ram_size_mb}" -ge 1024 ]
then
    echo "Total RAM installed in Gigabytes =" $(( total_ram_size_mb / 1024 ))
else
    echo "Total RAM installed in Megabytes = ${total_ram_size_mb}"
fi


texts: Elevator Interview Problem OOP - Revised

texts:
Elevator program code challenge, revised:

Can someone please critique my Elevator problem - I wanted to use OOP principles and coding standards. Also, does logic make sense?

internal enum Status
{
    GoingUp,
    GoingDown,
    Stopped
}

internal class Elevator
{
    private readonly SortedList<int, bool> _sorted = new SortedList<int, bool>();
    public readonly int TopFloor;

    public Elevator(int topFloor)
    {
        TopFloor = topFloor;
    }

    public int CurrentFloor { get; set; } = 1;
    public Status Status { get; set; } = Status.Stopped;

    public void AddRequest(int floor)
    {
        if (!_sorted.ContainsKey(floor))
            _sorted.Add(floor, false);

        switch (Status) {
            case Status.GoingDown:
                MoveDown();
                break;

            case Status.Stopped:
                if (CurrentFloor < floor)
                    MoveUp();
                else
                    MoveDown();
                break;

            case Status.GoingUp:
                MoveUp();
                break;

            default:
                break;
        }
    }

    public void MoveUp()
    {
        var max = _sorted.OrderByDescending(x => x.Key).First();
        for (var i = CurrentFloor; i <= max.Key; i++) // Go to top most requested floor
            if (_sorted.ContainsKey(i))
                Stop(i);
            else
                continue;

        Status = Status.Stopped;
    }

    public void MoveDown()
    {
        var min = _sorted.OrderBy(x => x.Key).First();
        for (var i = CurrentFloor; i >= min.Key; i--)
            if (_sorted.ContainsKey(i))
                Stop(i);
            else
                continue;

        Status = Status.Stopped;
    }

    public void Stop(int floor)
    {
        _sorted.Remove(floor);
        CurrentFloor = floor;
        Console.WriteLine("Stopped at: {0}", CurrentFloor);
    }
}

internal class Manager
{
    private readonly Elevator _elevator = new Elevator(10);

    public void ButtonPressed(int floor)
    {
         // testing...
        _elevator.AddRequest(10);
        _elevator.AddRequest(10);
        _elevator.AddRequest(5);
        _elevator.AddRequest(2);
        _elevator.AddRequest(9);
        _elevator.AddRequest(6);
    }
}


texts: Determine if all characters are unique in string: Without using Bitwise operator

texts:
I am implementing the said question on "Cracking the Coding interview" using HashSet. Please have a look and suggest how I can improve the efficiency of the following code considering that I am only taking either all lower case or upper case characters.

static void detrUniqChar(String str)
{
 int flag = 0; //Flag declared here
 Set<Character> hashSet = new HashSet<Character>();

 for(char c : str.toCharArray())
 {
   if(c != ' ')
    {
     if(!hashSet.add(c))
      {
       System.out.println("Not unique " + c  );
       flag = 0;
       break;
      }
     else {
       flag = 1;
      }
    }
  }
if(flag ==1 )System.out.println("Unique characters");
}

Does the space and time efficiency of this code equal to bitwise operation as per the solution provided by the book. As in solution worse case will be when the common elements are at first and last position of the string.

The code given in "Cracking the coding interview" is as follows:

public static boolean isUniqueChars(String str) {
if (str.length() > 256) {
    return false;
}
int checker = 0;
for (int i = 0; i < str.length(); i++) {
    int val = str.charAt(i) - 'a';
    if ((checker & (1 << val)) > 0) return false;
    checker |= (1 << val);
}
return true;
}


texts: Copying contents of two files into one file/ bufferedReader close calls

texts:
I am using the following code to copy the contents of two files into one. Earlier I was not closing the Buff and as eclipse gave warnings I did close it. I want to know if this code is susceptible to failure.

public void mergeFiles() throws IOException{
        ArrayList<String> list = new ArrayList<String>();
        BufferedReader br = null;
        BufferedReader r = null;
        try{
            br = new BufferedReader(new FileReader(getApplicationContext().getFilesDir()+"/BirthdayReminders/fileone.txt"));
            r = new BufferedReader(new FileReader(getApplicationContext().getFilesDir()+"/BirthdayReminders/filetwo.txt"));
            String s1 =null;
            String s2 = null;

            while ((s1 = br.readLine()) != null){
                list.add(s1);
            }
            while((s2 = r.readLine()) != null){
                list.add(s2);
            }
        }
        catch (IOException e){
            e.printStackTrace();
            FLAG =1;
        }finally{
            br.close();
            r.close();
        }

        BufferedWriter writer=null;
        writer = new BufferedWriter(new FileWriter(getApplicationContext().getFilesDir()+"/BirthdayReminders/output.txt"));
        String listWord;
        for (int i = 0; i< list.size(); i++){
            listWord = list.get(i);
            writer.write(listWord);
            writer.write("\n");
        }

        writer.close();
    }

Should I check if br is null in the finally block - my intuition tells me no, because finally will be only executed when try is. I have something over Here which is contradictory to my belief in declaring the variables before try block. What is the best way to do this?


texts: Most efficient implementation of Djisktra's shortest path using vectors and pairs in C++ stl

texts:
If std::vector<vector<pair<int,int> > > v(n) represents the adjacency list of the graph with pair<int,int> is the {vertex,weight} pair, I tried to implement the algorithm the following way:

while(true)
        {
            long long yo = LLONG_MAX;
            int ind=-1;
            for(int i=0;i<n;++i)
            {
                if(ans[i]<yo && !v[i].empty())
                {
                    ind=i;
                    yo=ans[i];
                }
            }
            if(ind==-1)
                break;
            for(int i=0;i<v[ind].size();++i)
            {
                if(ans[v[ind][i].first] > ans[ind]+v[ind][i].second)
                    ans[v[ind][i].first] = ans[ind]+v[ind][i].second;
                v[ind].erase(v[ind].begin()+i);
            }
        }

Where ans[i] stores the shortest paths which is initialised as {LLONG_MAX,...0,...LLONG_MAX}, 0 being the source. Since this is the first time I tried implementing it, is there a better way to implement using the vectors/list in stl (in terms of time/space complexity maybe)?


texts:
This is my first attempt with a lisp language. I'd like your review to address the following points, already listed in order of relevance:

Is my code making good use of standard library?
Is my code using the right data structures?
Is my code well formated and organized?
Is my code computationally efficient?

Code:

(ns clojure-first-try.core)

(use '[clojure.string :only [split]])
(use '[clojure.set :only [intersection]])

(defn sum [arr]
  (reduce + 0.0 arr))

(defn squares [arr]
  (map #(* % %) arr))

(defn words-frequency [text]
  (as-> text $
    (split $ #"\s+")
    (filter (complement empty?) $)
    (frequencies $)))

(defn cos-numerator [map-1 map-2]
  (def common-keys (intersection (set (keys map-1)) (set (keys map-2))))
  (sum (map #(* (map-1 %) (map-2 %)) common-keys)))

(defn cos-denominator [map-1 map-2]
  (def p-1 (sum (squares (vals map-1))))
  (def p-2 (sum (squares (vals map-2))))
  (* (Math/sqrt p-1) (Math/sqrt p-2)))

(defn cos-similarity [freq-1 freq-2]
  (def a (cos-numerator freq-1 freq-2))
  (def b (cos-denominator freq-1 freq-2))
  (if (= b 0.0) 0.0 (/ a b)))

(defn sort-by-similarity [base options]
  (def base-freq (words-frequency base))
  (def sorter (comp (partial cos-similarity base-freq) words-frequency))
  (sort-by sorter > options))

Tests:

(ns clojure-first-try.core-test
  (:require [clojure.test :refer :all]
            [clojure-first-try.core :refer :all]))

(defn close-enough? [a b]
  (def delta (- a b))
  (def abs-delta (max delta (- delta)))
  (> 0.0001 abs-delta))

(deftest words-frequency-test
  (testing "Counting the frequency of words in a text with actual words"
    (def expected {"a" 3, "bb" 2, "ccc" 4})
    (def input "ccc ccc a bb a bb a ccc ccc")
    (def result (words-frequency input))
    (is (= expected result)))
  (testing "Counting the frequency of words in an empty text"
    (def expected {})
    (def input "")
    (def result (words-frequency input))
    (is (= expected result))))

(deftest cos-similarity-test
  (testing "Getting the similarity of two equal texts"
    (def expected 1.0)
    (def input-1 {:a 1 :b 2})
    (def input-2 {:b 2 :a 1})
    (def result (cos-similarity input-1 input-2))
    (is (close-enough? expected result)))
  (testing "Getting the similarity of two totally different texts"
    (def expected 0.0)
    (def input-1 {:a 1 :b 2})
    (def input-2 {:c 2 :d 1})
    (def result (cos-similarity input-1 input-2))
    (is (close-enough? expected result)))
  (testing "Getting the similarity of two half equal texts"
    (def expected 0.5)
    (def input-1 {:a 2 :b 2})
    (def input-2 {:b 2 :d 2})
    (def result (cos-similarity input-1 input-2))
    (is (close-enough? expected result))))

(deftest sort-by-similarity-test
  (testing "Sorting regular texts"
    (def expected ["a b c" "a b d" "d e f"])
    (def input-1 "a b c")
    (def input-2 ["d e f" "a b c" "a b d"])
    (def result (sort-by-similarity input-1 input-2))
    (is (= expected result)))
  (testing "Sorting empty list of options")
    (def expected [])
    (def input-1 "a b c")
    (def input-2 [])
    (def result (sort-by-similarity input-1 input-2))
    (is (= expected result)))

All tests passing:

lein test clojure-first-try.core-test

Ran 3 tests containing 7 assertions.
0 failures, 0 errors.


texts:
I wrote some code for an application that uses the following pattern:

function _getData() {
    return new Promise(function(resolve, reject) {
        if(_hasDataTypeA()) {
            SomeBackendAccessObject.getTypeAData().then(resolve, reject);
        } else {
            SomeBackendAccessObject.getTypeBData().then(_convertToTypeA).then(resolve, reject);
        }
    });
}

My rationale for writing the code this way is that if _hasDataTypeA throws an exception, we're still able to return a Promise. This means the caller doesn't have to do a try block and a Promise .catch; but this code feels smelly to me. Is there a better way to write it?


texts: Retrieving user details from a custom form

texts:
I have been working on a Magento module for sometime now (not because it is a large module, it's my first and I really struggled with it). I now have it working, which I was really pleased with at first, but now I would like to improve it by increasing the reusability of the code.

While making my module I have looked at other modules to learn from them and have seen that many actions are only a line or two and I have tried keeping in with the skinny controller approach but failed, my example is as follows:

I have a function that get a users details that they have inputted into a custom form.

protected function _setPostData()
{
    $this->_salutation = $this->getRequest()->getPost('salutation');
    $this->_f_name = $this->getRequest()->getPost('f_name');
    $this->_l_name = $this->getRequest()->getPost('l_name');
    $this->_email = $this->getRequest()->getPost('email');
    $this->_emailAddressCheck = $this->getRequest()->getPost('emailAddressCheck');
    $this->_gender = $this->getRequest()->getPost('gender');
    $this->_country = $this->getRequest()->getPost('country');
    $this->_pref_lang = $this->getRequest()->getPost('pref_lang');
}

I feel that this is not the correct way to do it and that there is a better way of achieving the same goal. As you can see, this function gets the posts data and assigns it to attributes that I've set at the start of the class. I have several other examples that are very similar to the above and if someone could please offer some guidance on this one I am sure I will be able to work out the others.

This example is held within the index action. Should I put it in a helper? Once it's created correctly, will there be a few occasions in which I will be able to use it again.


texts: Improving the performance of interpolating between two arrays

texts:
The Problem

I am currently writing a script that converts images into numerical array representation and then calculates "in-between" images based on linear interpolation between the start and end array.

My code does exactly what I want but goes over many nested loops which strikes me as something that will lead to very high computation times for many interpolation steps or big images.

The Code

The code is in python

import numpy as np

# Helper function that calculates the interpolation between two points
def interpolate_points(p1, p2, n_steps=3):
    # interpolate ratios between the points
    ratios = np.linspace(0, 1, num=n_steps)
    # linear interpolate vectors
    vectors = list()
    for ratio in ratios:
        v = (1.0 - ratio) * p1 + ratio * p2
        vectors.append(v)
    return np.asarray(vectors)

# final function that interpolates arrays
def interpolate_arrays(start_array,end_array,n_steps=10):
    n = 0
    array_interpolation = []
    while n < n_steps:
        i = 0
        x = []
        while i < len(start_array):
            e = interpolate_points(start_array[i],end_array[i],n_steps)[n]
            x.append(e)
            i += 1
        array_interpolation += [x]
        n += 1
    return array_interpolation

This results in:

#Test
X1 = [1,1]
X2 = [3,3]

interpolate_arrays(X1,X2,n_steps=3)
#[[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]


texts:
I recently had quite a lot of fun answering a Stack Overflow question, and I think I've gone a bit overboard and ended up with a fairly decent way of populating a ComboBox from a Range.

Given a simple UserForm featuring some ComboBox1 control that I'd want to populate from a ListObject on Sheet1, the calling/client code looks like this:

Option Explicit

Sub Test()
    With New UserForm1
        .PopulateFromList Sheet1.ListObjects(1)
        .Show vbModal
    End With
End Sub

(thanks to Thomas Inzina for helping with the column headings)

...the Change handler in the form's code is just to illustrate that the hidden ID column is effectively being used as the Combobox.Value:

Private Sub ComboBox1_Change()
    If Not IsNull(ComboBox1.Value) Then Debug.Print ComboBox1.Value, ComboBox1.Text
End Sub

And it works!

 3            Star Wars
 1            Lord of the Rings

Here's the rest of the form's code-behind, the actual code under review - I'm wondering what's the best way to reuse it, I haven't decided whether it's best to extract it into a class module as a utility; with a WithEvents foo As ComboBox field I could be having a dynamic control there... it's certainly not practical in the code-behind of some random form though.

I'm not very happy with GetColumnWidths, I'm sure there's a better way to do this. As for the PopulateFromXxxx methods, ...they're perfect, aren't they? ;-)

Option Explicit

Public Sub PopulateFromList(ByVal source As ListObject, Optional ByVal valueColumn As Long = 1, Optional ByVal hasHeader As Boolean = True)
    With Me.ComboBox1
        .ColumnCount = source.Range.Columns.Count
        .ColumnWidths = GetColumnWidths(source.Range)
        .ListWidth = IIf(ComboBox1.Width > source.Range.Width, ComboBox1.Width, source.Range.Width)
        .RowSource = source.Name & "[#Data]"
        .BoundColumn = valueColumn
        .ColumnHeads = hasHeader
    End With
End Sub

Public Sub PopulateFromArray(ByVal source As Range, Optional ByVal valueColumn As Long = 1, Optional ByVal hasHeader As Boolean = True)
    With Me.ComboBox1
        .ColumnCount = source.Columns.Count
        .ColumnWidths = GetColumnWidths(source)
        .ListWidth = IIf(ComboBox1.Width > source.Width, ComboBox1.Width, source.Width)
        .List = source.Range(source.Rows(IIf(hasHeader, 2, 1)).EntireRow, source.Rows(source.Rows.Count).EntireRow).Value
        .BoundColumn = valueColumn
    End With
End Sub

Private Function GetColumnWidths(ByVal source As Range) As String
    Dim cols As Long
    cols = source.Columns.Count

    Dim widths()
    ReDim widths(1 To cols)
    Dim col As Long
    For col = 1 To cols
        widths(col) = source(, col).Width
    Next
    GetColumnWidths = Join(widths, ",")
End Function

Is there any way to clean this up? The .List assignment in PopulateFromArray seems particularly painful.


texts:
Problem

I've seen this basic interview question in a couple of places, but never implemented it.

  Create an algorithm to output a fair die roll (values between 1 and 6, inclusive),
  given a function that outputs the outcome of a fair coin toss (0 or 1).

Approach

The idea here is to use three coin flips to generate the binary values from 000 to 111 (0 to 7 in Base 10).
Then, ignore the values 110 (6) and 111 (7) so that we are only considering the binary values from 000 to
101 (0 to 5 in Base 10).

Note that 110 and 111 will be the only values that start with two 1s, so any time the first two rolls start with
two 1s we know to ignore the previous values and try rolling again.

If the first two rolls do not start with two 1s, then we roll a third time, concatenate the three values to form our
binary representation and then convert the binary value into Base 10 (while adding one since the value will be 0-5
and we want 1-6).

Implementation Discussion

Most of my questions might be coming from the over-engineering part of my brain.

That part of my brain basically wants to create Enums for coin toss outcomes and for the die roll outcomes
(DieRoll.ONE, DieRoll.TWO, etc.).

Partly because it feels kind've weird that getCoinToss returns an int when it really represents a binary
(i.e. boolean) value.
Is it better to return a boolean here? I thought about it, but ultimately ended up not doing so because I would've
had to convert the booleans into 1s and 0s when generating the String binary representation.

Same thing (but to a lesser extent) with generateValue - the possible values are really 1-6.

Implementation

public class RandomDieValueGenerator {
    public static int generateValue() {
        int firstCoinToss = RandomDieValueGenerator.getCoinToss();
        int secondCoinToss = RandomDieValueGenerator.getCoinToss();

        if (firstCoinToss * secondCoinToss == 1) {
          return RandomDieValueGenerator.generateValue();
        }

        String binaryRepresentation = String.valueOf(firstCoinToss) + secondCoinToss + RandomDieValueGenerator.getCoinToss();
        return Integer.parseInt(binaryRepresentation, 2) + 1;
    }

    private static int getCoinToss() {
        return Math.toIntExact(Math.round(Math.random()));
    }
}


texts: Is calling a function only twice a good use of recursion?

texts:
Is this, technically, a recursive function? It only gets called once by itself, but it cleaned up my code quite a bit, I think.  Or, does it needlessly complicate the code?

sub check_backlog {
    my $topic        = shift;
    my $prev_backlog = shift;
    my $backlog      = undef;
    my @status = `$CMD -topicstat $topic`;
    foreach (@status) {
        if (/Message count: (\d+)/) {
            $backlog = $LAST_PAREN_MATCH;
            if ( !$prev_backlog && $backlog > 1 ) {
                sleep $topic_wait_time;
                check_backlog( $topic, $backlog );
            }
            elsif ( $backlog > $prev_backlog ) {
                check_over_thresholds($backlog);
            }
        }
    }
    return $backlog;
}


texts: Simple calculator to evaluate arithmetic expressions

texts:
I've studied Java for 2 and a half months. Got bored and decided to make a basic calculator that takes any basic expression with 2 integers/doubles. E.g. 5.5x10, 5+5, 5-2.5, 6/2.

Is this a good way to approach this task?
How could it be improved?

The subtraction has a "+"  because substring takes into account the "-" as part of the second substring and the parseDouble turns that into a minus therefor two minuses would make a plus. I corrected the multiplication and division and i left the addition and subtraction how it was. I would correct all in the future.

/*
 * Author v0lk
 * Simple calculator program
 * 10/01/18
 */

import java.util.*;

public class Calc {

    public static void main(String[] args) {
        Calc c = new Calc();

        c.repeatCalc();

    }

    Scanner input = new Scanner(System.in);

    public void repeatCalc() {

        while (1>0) {
            calculator();
        }
    }

    public void calculator() {
        double result=0;
        String problm = "";
        System.out.println("Use: \n\"/\" to divide \n\"x\" to multiply \n\"+\" for addition \n\"-\" to substract \n\n>");

        problm = input.nextLine();

        for (int i=0; i<problm.length();i++) {

            if (problm.charAt(i)=='/') {

                result = Double.parseDouble(problm.substring(0, i)) / Double.parseDouble(problm.substring(i+1,problm.length()));

            }

            if  (problm.charAt(i)=='-') {
                result = Double.parseDouble(problm.substring(0, i)) + Double.parseDouble(problm.substring(i,problm.length()));

            }

            else if  (problm.charAt(i)=='x') {
                result = Double.parseDouble(problm.substring(0, i)) * Double.parseDouble(problm.substring(i+1,problm.length()));

            }

            else if  (problm.charAt(i)=='+') {

                result = Double.parseDouble(problm.substring(0, i)) + Double.parseDouble(problm.substring(i,problm.length()));

            }
        }

        System.out.println("Answer is: " + result);
    }

}


texts: All possible ways of merging two lists while keeping their order

texts:
I am writing a function gives all possible ways of merging two ordered lists such that in the merged list, the elements are still ordered according to the elements in their respective starting list.

For example, merging (a b) with (1 2) would result in:

((a b 1 2) (a 1 b 2)(a 1 2 b) (1 a b 2) (1 a 2 b) (1 2 a b))

My initial intuition was to map over an indexing list:

(define (ordered-merge l1 l2)
  (if (null? l2)
      (list l1)
      (let ((num-list (enumerate 0 (length l1) inc identity)))
        (flatten (lambda (pos)
                   (map (lambda (result) (append (take l1 pos)
                                                 (cons (car l2) result)))
                        (ordered-merge (drop l1 pos) (cdr l2))))
                 num-list))))

enumerate is just a list-builder, which here will return a list (0 1 ... (length l1)).

But I'm having feelings this is probably trying to force imperative style into functional style.

Here's my second attempt:

(define (ordered-merge2 l1 l2)
  (cond ((null? l1) (list l2))
        ((null? l2) (list l1))
        (else
         (let ((insert-here (ordered-merge2 l1 (cdr l2)))
               (not-here (ordered-merge2 (cdr l1) l2)))
           (append (map (lambda (result) (cons (car l2) result))
                        insert-here)
                   (map (lambda (result) (cons (car l1) result))
                        not-here))))))

How could this be improved?


texts: Creating unique registration numbers using object factories

texts:
I'm learning about immutability and uniqueness in Java, particularly the use of defensive programming and object factories.

I have been asked to create a class containing an object factory that when called creates a unique registration number comprised of a single letter and 4 digits. I think my solution ticks all boxes, but would appreciate some input on this one before I go any further to see if I'm on the right track.

public class RegistrationNumber
{
    private static final Map<String, RegistrationNumber> REG = new HashMap<String, RegistrationNumber>();

    private static int number;
    private static char letter;
    private static String strRep;

    private RegistrationNumber(int number, char letter, String strRep) {

      this.number = number;
      this.letter = letter;
      this.strRep = strRep;

    }

    public static final RegistrationNumber getInstance() {

       Random r = new Random();

       int numbers = r.nextInt(9000) + 1000;

       Character letter = (char)(r.nextInt(26) + 'a');

       String strRep = letter + "" + numbers;

       RegistrationNumber n = REG.get(strRep);

       if (n == null) {

           n = new RegistrationNumber(numbers, letter, strRep);

           REG.put(strRep, n);

        }
             return n;
           }

      char getLetter() {

          return letter;

        }

      int getNumbers() {

          return number;

        }

      public String toString() {

       return strRep;

    }

}


texts: Error handling for Stripe credit card processing

texts:
I have a rails application that uses Stripe for credit card processing. Currently several exceptions are being handled anywhere a transaction takes place. The code below is being used currently in 11 places. In all places it is essentially the same with the exception of the message being passed to stripe_error. Is it possible to create a reusable piece of code that can be used in all these places?

begin
  charge = Stripe::Charge.retrieve(@purchase.stripe_charge_id)
  resp = charge.capture(amount: fee.cancellation_fee,
                        receipt_email: @customer.email)
  @purchase.update_attributes(
    accepted_charge: true,
    stripe_transaction_id: resp['balance_transaction']
  )
  logger.info("Charged customer for cancellation #{@customer.id} #{@purchase.total_fee}")
  event('cancellation_charge', 'purchase_id', @purchase.id,
        fee: @purchase.total_fee, customer_id: @purchase.customer_id,
        provider_id: @purchase.provider_id)
  purchase_set_md5(@purchase.id)
rescue Stripe::CardError => e
  @err = stripe_error(e, 'cancellation', fee.cancellation_fee)
  @purchase.update_attributes(
    accepted_charge: false,
    charge_errors: message,
    stripe_transaction_id: '',
    status: "Cancellation fee charge did not go through #{@err['message']}"
  )
  purchase_set_md5(@purchase.id)
  render :err_show, status: :payment_required, json: @err
  return
rescue Stripe::InvalidRequestError => e
  @err = stripe_error(e, 'cancellation_invalid_request', fee.cancellation_fee)
  render :err_show, status: :payment_required, json: @err
  return
rescue Stripe::AuthenticationError => e
  @err = stripe_error(e, 'cancellation_authentication', fee.cancellation_fee)
  render :err_show, status: :payment_required, json: @err
  return
rescue Stripe::APIConnectionError => e
  @err = stripe_error(e, 'cancellation_api_connect', fee.cancellation_fee)
  render :err_show, status: :payment_required, json: @err
  return
rescue Stripe::StripeError => e
  @err = stripe_error(e, 'cancellation_generic error', fee.cancellation_fee)
  render :err_show, status: :payment_required, json: @err
  return
rescue => e
  @err = stripe_error(e, 'cancellation_something_else', fee.cancellation_fee)
  render :err_show, status: :payment_required, json: @err
  return
end

stripe_error

  def stripe_error(e, charge_type, fee = 0)
    logger.error("e #{e}")
    err = {
      charge_type: charge_type,
      errcode: ERR_STRIPE_ERR,
      message: "#{e}"
    }
    event(charge_type, 'error', "#{e}")
    logger.error("Charging error on #{charge_type} purchase for #{fee} ")
    logger.error("type #{e} ")
    err
  end