texts:
I am working on a product-related app where the data model for a product attribute feels too heavy. But I can't split it into several small data models because they are all about goods.

At present, my approach is to parse network data directly into a data model. The properties of the data model are readwrite. For example, when I want to modify a property, I will directly modify it, without copying or reinitializing the new data model.
 I know there may be problems with this, but I don't have a better way, if you have, please help me.

ATProductModel.h

#import "ATBaseModel.h"

NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSUInteger, ATFilterType) {
    ATFilterTypeComplex = 0,
    ATFilterTypeSales,
    ATFilterTypePrice,
    ATFilterTypeVoucher,
};

typedef NS_ENUM(NSUInteger, ATFilterLayoutType) {
    ATFilterLayoutTypeNone = 0,
    ATFilterLayoutTypeOneRows,
    ATFilterLayoutTypeMoreRows,
};

@interface ATProductSubModel : ATBaseModel

@property (copy, nonatomic) NSString *productId;
@property (copy, nonatomic) NSString *productURL;
@property (copy, nonatomic) NSString *productURLShort;
@property (copy, nonatomic) NSString *productIcon;
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *voucher;
@property (copy, nonatomic) NSString *currentPrice;
@property (copy, nonatomic) NSString *price;
@property (copy, nonatomic) NSString *couponURL;
@property (copy, nonatomic) NSString *discountRate;
@property (copy, nonatomic) NSString *endTime;
@property (copy, nonatomic) NSString *couponInfo;
@property (copy, nonatomic) NSString *volume;
@property (copy, nonatomic) NSString *couponStartTime;
@property (copy, nonatomic) NSString *couponEndTime;
@property (copy, nonatomic) NSArray <NSString *>* smallImages;
@property (copy, nonatomic) NSString *shopName;
@property (copy, nonatomic) NSString *shopLogo;
@property (copy, nonatomic) NSString *platType;
@property (copy, nonatomic) NSString *shopScore;
@property (copy, nonatomic) NSString *share;
@property (copy, nonatomic) NSString *shareFee;
@property (copy, nonatomic) NSString *income;
@property (copy, nonatomic) NSString *upIncome;
@property (strong, nonatomic) NSNumber *finished;

+ (instancetype)defaultModel;

@end

@interface ATProductModel : ATBaseModel

@property (strong, nonatomic) NSArray <ATProductSubModel *>* products;
@property (assign, nonatomic) ATFilterLayoutType layoutType;
@property (assign, nonatomic) BOOL recommended;

@end

NS_ASSUME_NONNULL_END

ATProductViewController.h

#import "ATProductModel.h"

NS_ASSUME_NONNULL_BEGIN

@interface ATProductViewController : UIViewController

@property (strong, nonatomic) ATProductSubModel *model;

@end

ATProductViewController.m

#import "ATStringUtil.h"

@implementation ATProductViewController

@property (strong, nonatomic) ATProductModel *productModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self defaultModels];
}

- (void)defaultModels{

    NSMutableArray *smallImages = [NSMutableArray arrayWithArray:self.model.smallImages];
    if (![ATStringUtil containStr:self.model.icon inArr:self.model.smallImages]) {
        [smallImages insertObject:self.model.icon atIndex:0];
    }
    self.model.smallImages = smallImages;
}

@end
```


texts: Did not pass the interview about an RPN Calculator

texts:
I recently received a simple interview assignment as to implement an RPN calculator in Ruby. The program takes user input and quits when the user presses 'q'.

I did it in under 30 minutes and was quite confident about my solution, but the interviewers did not like it. I would love to know the flaws it has so I can avoid being overconfident next time and learn better coding practices!

#!usr/bin/env ruby

# A Ruby RPN Calculator
#Note: decimal numbers are rounded to nearest tenth
=begin
example input/ouput
> 2
2
> 9
9
>3
3
> +
12
> * 24
=end

class RPNCalculator

  attr_reader :operators
  def initialize(operators)
    @operators=operators
  end

  def start
    print '> '
    n = gets.strip
    stack = []

    while n!= 'q'
      if n =~ /\d/
        stack.push(n.to_f)
        puts n
      elsif self.operators.include? n
        operands = stack.pop(2)
        res = operands.reduce(n.to_sym)
        (res.to_i == res) ? (puts res.to_i) : (puts "%0.1f" % res)
        stack.push(res)
      else
        puts "Invalid input"
      end
      print '> '
      n = gets.strip
    end
  end
end

rpn = RPNCalculator.new(["+","-","*","/"])
rpn.start


texts:
It is my first program in Javascript. Is there any lack or a thing to be improved? It simply increases, decreases, or reset the counter either by buttons or arrow keys.
HTML,

<button class="btn" id="incr">Increase</button>
<button class="btn" id="reset">Reset</button>
<button class="btn" id="decr">Decrease</button>

JS,
let number = 0

const getNumber = document.getElementById(`number`)
const incrButton = document.getElementById(`incr`)
const decrButton = document.getElementById(`decr`)
const resetButton = document.getElementById(`reset`)

getNumber.textContent = number

const incrFunc = function () {
  ++number
  getNumber.textContent = number
  if (number > 0) {
    getNumber.style.color = `green`
  }
}

const resetFunc = function () {
  number = 0
  getNumber.textContent = number
  getNumber.style.color = `gray`
}

const decrFunc = function () {
  --number
  getNumber.textContent = number
  if (number < 0) {
    getNumber.style.color = `red`
  }
}

incrButton.addEventListener(`keyup`, function (e) {
  e.stopPropagation()
  //console.log(e.target === document.body)
  if (e.code === `ArrowUp`) {
    incrFunc()
  }
})

document.addEventListener(`keyup`, function (e) {
  //console.log(e.target === document.body)
  if (e.code === `ArrowUp`) {
    incrFunc()
  }
})

document.addEventListener(`keyup`, function (e) {
  if (e.code === `ArrowRight` || e.code === `ArrowLeft`) {
    resetFunc()
  }
})

resetButton.addEventListener(`keyup`, function (e) {
  if (e.code === `ArrowRight` || e.code === `ArrowLeft`) {
    resetFunc()
  }
})

document.addEventListener(`keyup`, function (e) {
  if (e.code === `ArrowDown`) {
    decrFunc()
  }
})

decr.addEventListener(`keyup`, function (e) {
  if (e.code === `ArrowDown`) {
    decrFunc()
  }
})

incrButton.addEventListener(`click`, incrFunc)

resetButton.addEventListener(`click`, resetFunc)

decrButton.addEventListener(`click`, decrFunc)


texts:
I've got this code

Double best = nodes.get(edge.getToNodeId());
if (best == null || (best > g+h)) {
    nodes.put(edge.getToNodeId(), g+h);
    if (best == null) {
        open.add(new State(edge.getToNodeId(), g, h, top));
    } else {
        open.modify(new State(edge.getToNodeId(), g, h, top));
    }
}

I don't quite like it because I duplicate the best == null clause. Would it be better in these types of situation to duplicate the nodes.put() instead? Or is there some third, more readable, way without duplicates?


texts:
I am creating a set of bots. Those bots are made to visit websites and perform certain actions automatically on the website. Different actions are available for the bots depending on the website they are visiting.

I would like to know if there is a better version to do this since the current one is not convincing me.

class Bot {
    constructor (name) {
        this.name = name;
        this.browser = new Browser(); // Instance of a headless browser.
        this.website = null; // The current website.
    }

    visit (website) {
        this.website = website;
    }

    doAction (name, ...parameters) {
        return this.website.actions[name](this, ...parameters);
    }
}

class Website {
    constructor (name, url) {
        this.name = name;
        this.url = url;
        this.actions = {};
    }

    addAction (name, call) {
        this.actions[name] = call;
    }
}

// The following is a short use case example.
const bot = new Bot("bot1");
const fb = new Website("facebook", "https://www.facebook.com");

fb.addAction("login", (bot, username, password) => {
    bot.browser.visit("https://facebook.com/");

    bot.browser.query("#username").value = username;
    bot.browser.query("#password").value = password;
    bot.browser.query("#login-form").submit();
});

bot.visit(fb);
bot.doAction("login", "username", "password");

Do you think it's simple and clear? Have you thought another way to do it?


texts:
I created a simple Tic-Tac-Toe.  I'm looking for any critiques from a code standpoint: general structure / style / efficiency.

Unfortunately I couldn't get a live demo working because of the dependency on the NodeJS library prompt.

/*  A simple Tic-Tac-Toe game implemented in Javascript V8 3.14.5.9

Players 'X' and 'O' take turn inputing their position on the command line using numbers 1-9

1 | 2 | 3
---------
4 | 5 | 6
---------
7 | 8 | 9

*/

// prompt for nodejs is required: https://github.com/flatiron/prompt
// npm install prompt
var prompt = require('prompt');

var board = {
    1: ' ',
    2: ' ',
    3: ' ',
    4: ' ',
    5: ' ',
    6: ' ',
    7: ' ',
    8: ' ',
    9: ' '
};

function markBoard(position, mark) {
    board[position] = mark.toUpperCase();
}

function printBoard() {
    console.log('\n' +
        ' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + '\n' +
        ' ---------\n' +
        ' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + '\n' +
        ' ---------\n' +
        ' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + '\n');

}

function isInt(value) {
    var x;
    if (isNaN(value)) {
        return false;
    }
    x = parseFloat(value);
    return (x | 0) === x;
}

function validateMove(position) {
    if (isInt(position) === true && board[position] === ' ') {
        return true;
    }
    return false;
}

// Everyone possible combination of three in a row
var winCombinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
                       [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]];

// Determins if the passed in player has three in a row
function checkWin(player) {
    for (var i = 0; i < winCombinations.length; i++) {
        var markCount = 0;
        for (var j = 0; j < winCombinations[i].length; j++) {
            if (board[winCombinations[i][j]] === player) {
                markCount++;
            }
            if (markCount === 3) {
                return true;
            }
        }
    }
    return false;
}

function playTurn(player) {

    console.log('Your turn player: ' + player);
    prompt.start();
    prompt.get(['position'], function (err, result) {

        if (validateMove(result.position) === true) {
            markBoard(result.position, player);
            printBoard();
            if (checkWin(player) === true) {
                console.log('Winner Winner!');
                return;
            }
            if (player === 'X') {
                playTurn('O');
            } else {
                playTurn('X');
            }
        } else {
            console.log('incorrect input please try again...');
            playTurn(player);
        }
    });
}

console.log('Game started: \n' +
    ' 1 | 2 | 3 \n' +
    ' --------- \n' +
    ' 4 | 5 | 6 \n' +
    ' --------- \n' +
    ' 7 | 8 | 9 \n');

playTurn('X');


texts: Improving performance of a subroutine that checks for a vacancy in a lattice

texts:
I use the following subroutine to check whether a small subsection of a 3D Int array is all equal to zero. If any value in the particular subsection is non-zero, I exit and return .false.. Within CheckForVacancy, subroutine bc gets called which takes care of out of bounds array indices.

This subroutine gets called millions of times during a particular run and it is responsible for about half the running time of the entire program. In the distant past, I tried to optimize it by changing the order in which I access the Lattice array and by using the any built-in with array slices but I never saw much improvement. Furthermore, the "array slices" solution can get complicated when dealing with the boundaries of the array. I also tried fiddling with optimization flags but I was largely experimenting blindly at that point.

The code is as follows:

LOGICAL FUNCTION CheckForVacancy (x, y, z)
  ! Checks for vacancy for a site [x,y,z]

  use atrpmodule

  IMPLICIT NONE

  INTEGER, INTENT(IN) :: x, y, z
  INTEGER :: Sx, Sy, Sz, i
  INTEGER, DIMENSION(1:26) :: SpaceX = (/1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,0,1,1,1,0,-1,-1,-1,0,0/)
  INTEGER, DIMENSION(1:26) :: SpaceY = (/0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1/)
  INTEGER, DIMENSION(1:26) :: SpaceZ = (/1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1,1,0,1,0,-1,-1,-1,0,1,1,0/)
  !---------------------------------------------------------------------------

  checkforvacancy=.true.
  do i=1,26
     Sx = x + SpaceX(i)
     Sy = y + SpaceY(i)
     Sz = z + SpaceZ(i)
     call bc(Sx,Sy,Sz)
     if (lattice(Sx,Sy,Sz)/=0)then
        CheckForVacancy=.false.
        exit
     endif
  enddo

END FUNCTION CheckForVacancy

SUBROUTINE bc (x, y, z)
  ! Takes case of boundary conditions
  USE atrpmodule
  IMPLICIT NONE

  INTEGER :: x, y, z
  !---------------------------------------------------------------------------
  IF (x < 1) then
     x = x + LattXDimm
  elseIF(x > LattXDimm) then
     x = x - LattXDimm
  endif

  IF (y < 1) then
     y = y + LattYDimm
  elseIF (y > LattYDimm) then
     y = y - LattYDimm
  endif

  IF (z < 1) then
     z = z + LattZDimm
  elseIF (z > LattZDimm) then
     z = z - LattZDimm
  endif

END SUBROUTINE bc

For reference, Lattice is defined like this:

INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: Lattice

It is allocated depending on program input and then set equal to zero. Also for reference, I am using the GNU compiler.

I suspect that the answer to this questions may be that I cannot do better, but I wanted to see if any Fortran programmers can spot something that I am missing or may want to try.


texts: Refactoring Golang to avoid manual fields updating between similar structs and other redundant code

texts:
I'm using GraphQL and go-pg.
I have many entities like these:
type Player struct {
    ID        int
    CreatedAt time.Time `pg:"default:now(),notnull"`
    TeamID    int `pg:",notnull"`
    Team      *Team
    Type      int
    Score     int64 `pg:",notnull"`
  Note      *string
  // and others...
}

type PlayerInput struct {
    TeamID  int
    Type    int
    Score   int64
    Note    *string
  // and others...
}

I have many times functions like these:
func (db *postgres) Update(context context.Context, id int, input types.PlayerInput) (*types.Player, error) {

    var actualPlayer types.Player

    newPlayer := graphqlToDB(&input)

    tx, err := db.Begin()
    //handle err

    err = tx.Model(&actualPlayer).Where("id = ?", id).For("UPDATE").Select()
    // handle err and rollback

    actualPlayer.TeamID = dbo.TeamID
    actualPlayer.Type = dbo.Type
    actualPlayer.Score = dbo.Score
  actualPlayer.Note = dbo.Note
  // and others...

    _, err = tx.Model(&actualPlayer).WherePK().Update()
    // handle err and rollback

    err = tx.Commit()
    //handle err

    return &actualPlayer, nil
}

func graphqlToDB(input *types.PlayerInput) *types.Player {

    var output = &types.Player{
        TeamID:   input.TeamID,
        Type:     input.Type,
        Score:    input.Score,
        Note:     input.Note,
    // and others...
    }

    if input.Type == "example" {
        output.Score = 10000000
  }

    return output
}

I have this code for each entity in my project and I would like to limit/avoid redundant code, specially:

transformation from Graphql input type every time
newPlayer := graphqlToDB(&input)

manual updating of these (and other) fields every time
actualPlayer.TeamID = dbo.TeamID
actualPlayer.Type = dbo.Type
actualPlayer.Score = dbo.Score
actualPlayer.Note = dbo.Note

opening and closing DB transaction every time
tx, err := db.Begin()

Am I asking for the moon?


texts: Flip Sprite using the SpriteRenderer component

texts:
I want to create a 2D topdown game with Unity. When moving the player I also want him to rotate.

Most tutorials provide a solution changing the localscale of the transform component on the x axis setting -1 for left movement and 1 for right movement.

The attached SpriteRenderer component also got flipX and flipY checkboxes. I think setting these checkboxes by code might be more efficient.

Using this example code achieves the desired rotation

bool flipX;
bool flipY;

void Update()
{
    float horizontalInput = movementDirection.x;

    if (horizontalInput > 0)
    {
        flipX = false;
    }
    else if (horizontalInput < 0)
    {
        flipX = true;
    }

    float verticalInput = movementDirection.y;

    if (verticalInput > 0)
    {
        flipY = false;
    }
    else if (verticalInput < 0)
    {
        flipY = true;
    }

    spriteRenderer.flipX = flipX;
    spriteRenderer.flipY = flipY;
}

My question is: Is there a way avoiding these four if-statements? Maybe there is a more optimized way using some math.


texts: Reading environment variables of various types

texts:
I need to extract some data from the environment variables using Go. This data can be string, boolean or integer, so I ended up writing three functions.

package main
import (
    "fmt"
    "os"
    "strconv"
)

func getStrEnv(key string) string {
    val := os.Getenv(key)
    if val == "" {
        panic(fmt.Sprintf("some error msg"))
    }
    return val
}

func getIntEnv(key string) int {
    val := getStrEnv(key)
    ret, err := strconv.Atoi(val)
    if err != nil {
        panic(fmt.Sprintf("some error"))
    }
    return ret
}

func getBoolEnv(key string) bool {
    val := getStrEnv(key)
    ret, err := strconv.ParseBool(val)
    if err != nil {
        panic(fmt.Sprintf("some error"))
    }
    return ret
}

Which works, but in a language like Python, I would just create one function getEnv(key, type_var), which would go through various passes depending on the type_var provided. Is there a way to produce similar result with Go?


texts:
I asked a math question and was hoping someone could have a look at the code for me as well. Unfortunately you might have to go look at the original question here.

protected void ButtonCalRetire_Click(object sender, EventArgs e)
{
double FVc = 0;
double FVd = 0;
double PV = double.Parse(TextBoxCurrentSave.Text);
double i = double.Parse(TextBoxRoR.Text) / 100;
double b = (double)(int.Parse(TextBoxRetireAge.Text) - int.Parse(TextBoxCurrentAge.Text));
double R1 = double.Parse(TextBoxCurrentMonthlyContribution.Text);
double g2 = double.Parse(TextBoxAnnuityGrowthRetire.Text) / 100;

FVc = PV * Math.Pow((1 + i / 12), (b * 12));

FVd = R1 * (Math.Pow((1 + i / 12), (b * 12)) - Math.Pow((1 + g2 / 12), (b * 12))) / ((i / 12) - (g2 / 12));

double totSaved = FVc + FVd;

double R2 = double.Parse(TextBoxCurrentMonthlyContribution.Text);
double n = (double)(int.Parse(TextBoxDeathAge.Text) - int.Parse(TextBoxRetireAge.Text));

double PVg = R2 * Math.Pow((1 + g2 / 12), (b * 12)) / (i / 12 - g2 / 12) * (1 - ((Math.Pow((1 + g2 / 12), (n * 12))) / (Math.Pow((1 + i / 12), (n * 12)))));

double diff = FVc + FVd - PVg;

double R3 = diff / (Math.Pow((1 + i / 12), (b * 12)) - Math.Pow((1 + g2 / 12), (b * 12))) / ((i / 12) - (g2 / 12));

LabelTotControNeeded.Text = (R3 + R2).ToString("R ### ##0.00");
LabelControNeeded.Text = R3.ToString("R ### ##0.00");
}

Edit:

If I debug correctly, the PVg above (line repeated below) returns 0

double PVg = R2 * Math.Pow((1 + g2 / 12), (b * 12)) / (i / 12 - g2 / 12) * (1 - ((Math.Pow((1 + g2 / 12), (n * 12))) / (Math.Pow((1 + i / 12), (n * 12)))));

Edit:

Here is the calculator: http://exceed.myib.co.za/calc


texts:
public class RunnableThreadPrimeNumber implements Runnable
{
    private long startNum;
    private long endNum;
    private Thread t;

RunnableThreadPrimeNumber(long start , long end )
{
        t = new Thread(this);
        this.startNum = start;
        this.endNum = end;

        t.start();
}

public void run()
{
    for ( int i = start ; i <= last ; i++)
    {
        if (isPrime(i) == true)
        {
            System.out.println(i + " is prime")
        }

    }

}

private boolean isPrime(long n)
{
    int counter = 0;

    for (int i = 2 ; i < n / 2 ; i++)
    {
        if ( n % i == 0 )
        {
            counter ++;
        }
    }

    if ( count > 0 )
    {
        //number is prime
        return true;
    }
    else
    {
        //number is not prime
        return false;
    }

}

public static void main(String[] args)
{
    RunnableThreadPrimeNumber(2000,4000);
    RunnableThreadPrimeNumber(4001,6000);
}

}

Questions:

Is there any way to improve this algorithm which checks if a given number is prime? The improvement can be anything from space to running time complexity.
For my function isPrime(long n), I am currently looping through every possible number less than half the input number and returning true or false only after the for loop has finished.

I am thinking of adding an addition if statement in the for loop which checks if the variable counter is greater than 0.  If it's greater than 0, immediately return true. The advantage to this approach is that for some numbers, I can immediately return true/false without needing to finish the for loop.  However, the cost comes at adding an additional if statement for every iteration in the for loop.

How should I go about deciding if the additional if statement is worth the cost?


texts: Find the nth prime between 1 and 1,000,000 in under 3 minutes - follow-up

texts:
Previous question:

Checking for the nth prime number between 1 and 1,000,000, must compute 1,000,000th in under 3 minutes

My mission is to find the nth prime number, based on user input 1-1,000,000. It also must be able to compute the 1,000,000th prime in under 3 minutes.
My code is relatively fast, however I need to make it calculate the 1,000,000th prime in 180 seconds or less. As of now it is taking 430 seconds, although before heavy updating last night it was taking about 20 minutes.

I am trying to accomplish this without importing any libraries (time's just for record keeping) and without making use of the sieve of Eratosthenes.  This is an assignment that I have been given, and I have been instructed to not use the help of either of those options.

import time
goal = int(input("Enter a number n, 1-1,000,000 to find the nth prime number."))
start = time.time()
if goal > 4:
    lst = [2, 3, 5, 7]
    chk = 11
    primes = 4
    while primes < goal:
        j = chk**.5
        for n in lst:
            if n > j:
                lst.append(chk)
                primes += 1
                break
            if chk % n == 0:
                break
        chk += 2

else:
    if goal == 1:
        print("2")
    if goal == 2:
        print("3")
    if goal == 3:
        print("5")
    if goal == 4:
        print("7")
print("Prime", str(goal), "is", str(chk - 2))
elapsed = (time.time() - start)
print(elapsed, "\n")


texts: Convert a Hex value string to an ASCII Text String

texts:
We had a little bit of fun in the 2nd Monitor this morning, one user greeted another with a hex string. It turned out that the user being greeted deals with Hex Dumps enough that they were able to read the string, but I wasn't so I created this converter.

What could I have done to reduce the dependency on cstring?

How could I have made this more C++17 and less C Programming language.

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstring>

class HexStringToAsciiStringConverter
{
    std::vector<unsigned> HexValues;

    const char* Remove0x(const char* hxv)
    {
        if (std::strstr(hxv, "0x") == hxv)
        {
            hxv += 2;
        }

        return hxv;
    }

    void ConvertStringToUnsigned(std::string HexStringToConvert)
    {
        const char *hxv = Remove0x(HexStringToConvert.c_str());
        while (*hxv && *(hxv+1))
        {
            char hxva[3] = {'\0'};
            std::strncpy(hxva, hxv, 2);
            HexValues.push_back(std::strtol(hxva, nullptr, 16));
            hxv += 2;
        }
    }

public:
    HexStringToAsciiStringConverter::HexStringToAsciiStringConverter(std::string Original)
    {
        ConvertStringToUnsigned(Original);
    }

    std::string HexStringToAsciiStringConverter::ConvertHexToString()
    {
        std::vector<unsigned char> tmpcarray;
        for (auto HexValue: HexValues)
        {
            tmpcarray.push_back(HexValue);
        }

        std::string output(tmpcarray.begin(), tmpcarray.end());

        return output;
    }
};

int main() {
    std::string Original = "0x486920446f6e2c20686f7727732073706163653f";

    HexStringToAsciiStringConverter Converter(Original);
    std::cout << Converter.ConvertHexToString() << std::endl;

    return EXIT_SUCCESS;
}


texts:
Can I make this more efficient?

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

void setvalue(int array_copy[], int i, int n)
{
    int j,p;

    for(j = i*i ; j <= n ; j +=(i*2) )
    {
        array_copy[j] = 1;
    }
}

int main()
{
    int n,i,l=0,sq;
    scanf("%i",&n);

    sq = sqrt(n);

    int prime_array[n];
    int array[n];
    for (i = 1; i <= n; ++i)
    {
        array[i] = 0;
    }
    for ( i = 4; i <= n; i+=2)
    {
        array[i] = 1;
    }

    for( i = 3; i <= sq; i+=2)
    {
        setvalue(array,i,n);
    }
    array[2] = 0;
    for(i = 2; i <= n; i++)
    {
        if(array[i] == 0)
        {
            prime_array[l] = i;
            l++;
        }
    }

    for ( i = 0; i <= (l-1) ; i++)
    {
        printf("%i\n",prime_array[i] );
    }
    return 0;
}


texts: Graphs and Kruskal's Algorithm - Python OOP

texts:
This is my implementation of a graph and Kruskal's algorithm in Python. I wanted to design the graph module myself and I would like some feedback on the design. I tried to follow SOLID throughout. I am not sure if the separate Vertex object is wise, but I feel it could be useful as I expand this module.

I had a copy of a flowchart of Kruskal's algorithm from a textbook (not my current course) and I decided to implement it, I am wondering how Pythonic my code is.

I have also programmed Prim's algorithm in the same file but I will split it over two questions.

class Vertex:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"Vertex {self.name}"

class Edge:
    def __init__(self, start, end, weight):
        self.start = start
        self.end = end
        self.weight = weight

    def __str__(self):
        return f"{self.start}{self.end}"

class Graph:
    def __init__(self, v, e):
        self.vertices = v
        self.edges = e

    def vertex_from_name(self, name):
        """ Return vertex object given vertex name. """
        return next((v for v in self.vertices if v.name == name), None)

    def add_edge(self, start, end, weight):
        """ Add an edge connecting two vertices. Arguments can either be vertex name or vertex object. """
        if isinstance(start, str):
            start = self.vertex_from_name(start)
        if isinstance(end, str):
            end = self.vertex_from_name(end)

        self.edges.append(Edge(start, end, weight))

    def edge_on_vertex(self, v):
        """ Return edges connected to given vertex v."""
        return [e for e in self.edges if (e.start == v) or (e.end == v)]

    def connected_vertices(self, v):
        """ Return the vertices connected to argument v."""
        if isinstance(v, str):
            v = self.vertex_from_name(v)

        return [e.start for e in self.edges if e.end == v] + [e.end for e in self.edges if e.start == v]

    def union(self, lst, e1, e2):
        """ Given a list of lists, merges e1 root list with e2 root list and returns merged list."""
        xroot, yroot = [], []
        # Find roots of both elements
        for i in lst:
            if e1 in i:
                xroot = i
            if e2 in i:
                yroot = i
        # Same root, cannot merge
        if xroot == yroot:
            return False
        xroot += yroot
        lst.remove(yroot)
        return lst

    def is_cycle(self):
        """ Return if the graph contains a cycle. """
        self.sets = [[v] for v in self.vertices]
        self._edges = sorted(self.edges, key=lambda x: x.weight)
        for e in self._edges:
            _temp = self.union(self.sets, e.start, e.end)
            if _temp == False:
                return True
            else:
                self.sets = _temp
        return False

    def Kruskals(self):
        """ Return MST using Kruskal's algorithm. """
        self.tree = Graph([], [])
        self.tree.vertices = self.vertices
        self.sorted_edges = sorted(self.edges, key=lambda x: x.weight)
        self.tree.edges.append(self.sorted_edges.pop(0))

        for edge in self.sorted_edges:
            self.tree.edges.append(edge)
            if self.tree.is_cycle():
                self.tree.edges.remove(edge)

        return self.tree

if __name__ == "__main__":
    v = [Vertex(x) for x in ["A", "B", "C", "D", "E", "F"]]

    g = Graph(v, [])

    g.add_edge("A", "B", 9)
    g.add_edge("A", "C", 12)
    g.add_edge("A", "D", 9)
    g.add_edge("A", "E", 11)
    g.add_edge("A", "F", 8)
    g.add_edge("B", "C", 10)
    g.add_edge("B", "F", 15)
    g.add_edge("C", "D", 8)
    g.add_edge("D", "E", 14)
    g.add_edge("E", "F", 12)

    print(g.Kruskals().edges)


texts: Portfolio object made of Asset classes and Securities

texts:
I am learning Swift and object oriented programming. I am new to design patterns and protocol oriented programming.

In my test code I have several related objects:

Security: the most important object that will be contained in the other ones.
AssetClass: Contains Security objects
Portfolio:  Contains Security and AssetClass objects
Watchlist: Contains Security objects. Think about it as a Portfolio object that cannot contain AssetClass objects, only Security objects.

I want to be the most abstract as I can to avoid tight coupling.

The following code works but I am wondering how it can be improved. Do you see major weak points in my design?

import Foundation

protocol SecurityType{
    var code : String {get set}
    var name : String? {get set}
}

class Security:SecurityType{

    var code : String = ""
    var name : String?

    init(withCode aCode: String, andName aName: String?){
        self.code = aCode
        if let securityName = aName{
            self.name = securityName
        }
    }
}

protocol SecuritiesBasketType{
    var name : String {get set}
    var securities : [SecurityType]{get set}
    init()
}

extension SecuritiesBasketType{

    //Default Initializers

    init(withName aName: String){
        self.init()
        self.name = aName
    }

    init(withName aName: String, andSecurities securitiesArray:[SecurityType]){
        self.init()
        self.name = aName

        for aSecurity : SecurityType in securitiesArray{
            securities.append(aSecurity)
        }
    }

    mutating func addSecurity(security: SecurityType){
        securities.append(security)
    }
}

class AssetClass : SecuritiesBasketType{

    var name : String = ""
    var securities = [SecurityType]()
    required init(){}
}

class WatchList: SecuritiesBasketType{

    var name : String = ""
    var securities = [SecurityType]()
    required init(){}
}

class Portfolio{

    var name : String = ""
    var securities = [Security]()
    var assetClasses = [AssetClass]()

    init(withName aName: String){
        self.name = aName
    }

    init(withName aName: String, andAssetClasses assetClasses:[AssetClass]){
        self.name = aName
        for assetClass in assetClasses{
            self.assetClasses.append(assetClass)
        }
    }

    init(withName aName: String, andAssetClasses assetClasses:[AssetClass], andSecurities securities:[Security]){

        self.name = aName

        for assetClass in assetClasses{
            self.assetClasses.append(assetClass)
        }

        for security in securities{
            self.securities.append(security)
        }
    }

}

//Creating Securities
var sMicrosoft = Security(withCode: "MSFT", andName: "Microsoft")
var sApple = Security(withCode: "AAPL", andName: "Apple")
var sJPMorgan = Security(withCode: "JPM", andName: "JP Morgan")
var sBankOfAmerica = Security(withCode: "BAC", andName: "Bank of America")
var sCaterpillar = Security(withCode: "CAT", andName: "Caterpillar")

//Creating Asset Classes
var acBanks = AssetClass(withName: "Banks", andSecurities: [sJPMorgan, sBankOfAmerica])
var acTechnology = AssetClass(withName: "Technology", andSecurities: [sMicrosoft, sApple])

//Creating Watchlists
var watchList1 = WatchList(withName: "List1", andSecurities: [sMicrosoft,sJPMorgan,sCaterpillar])
var watchList2 = WatchList(withName: "List2", andSecurities: [sBankOfAmerica,sApple])

//Creating Portfolios

var portfolio1 = Portfolio(withName: "Portfolio1", andAssetClasses: [acBanks,acTechnology])
var portfolio2 = Portfolio(withName: "Portfolio2", andAssetClasses: [acBanks, acTechnology], andSecurities: [sCaterpillar])

//Test

for ac : AssetClass in portfolio2.assetClasses{
    for s : SecurityType in ac.securities{
        print("\(s.name!)")
    }
}
for s : SecurityType in portfolio2.securities{
    print("\(s.name!)")
}


texts: A data structure with push(int x), pop(), min() and max() in O(1)

texts:
I have written this Java code for a data structure which includes 3 stacks to supports four operations in \$O(1)\$: push(int x), pop(), min() and max().

Instead of pushing new max and min in every push, I tried to optimize code in this way to have less space.

import java.util.Stack;

public class MyDS {

    Stack<Integer> s;
    Stack<Integer> minStack;
    Stack<Integer> maxStack;

    public MyDS(){
        s = new Stack<Integer>();
        minStack = new Stack<Integer>();
        maxStack = new Stack<Integer>();
    }

    // Push Method
    public void push(int k){

        if(minStack.isEmpty()){
            minStack.push(k);
        }else if(k <= minStack.peek()){
            minStack.push(k);
        }

        if(maxStack.isEmpty()){
            maxStack.push(k);
        }else if(k >= maxStack.peek()){
            maxStack.push(k);
        }
        s.push(k);
    }

    // Pop Method
    public void pop(){

        int popped;
        if(!s.isEmpty()){
            popped = s.pop();
        }else{
            popped = -1;
        }

        if(popped == min()){
            minStack.pop();
        }

        if(popped == max()){
            maxStack.pop();
        }
    }

    // Min Method
    public int min(){
        if(!minStack.isEmpty()){
            return minStack.peek();
        }else{
            return Integer.MIN_VALUE;
        }
    }

    // Max Method
    public int max(){
        if(!maxStack.isEmpty()){
            return maxStack.peek();
        }else{
            return Integer.MAX_VALUE;
        }
    }
}

This is my earlier version of DS:

import java.util.Stack;

public class DS {
    static Stack<Integer> stack;
    static Stack<Integer> minStack;
    static Stack<Integer> maxStack;

    public DS(){
        stack = new Stack<Integer>();
        minStack = new Stack<Integer>();
        maxStack = new Stack<Integer>();
    }

    // Push Method
    public void push(int k){
        stack.push(k);
        if(!minStack.isEmpty()){
            minStack.push(Math.min(k, minStack.peek()));
        }else{
            minStack.push(k);
        }
        if(!maxStack.isEmpty()){
            maxStack.push(Math.max(k, maxStack.peek()));
        }else{
            maxStack.push(k);
        }
    }

    // Pop Method
    public void pop(){
        if(!stack.isEmpty() && !minStack.isEmpty() && !maxStack.isEmpty()){
            stack.pop();
            minStack.pop();
            maxStack.pop();
        }
    }

    // Find Min
    public int findMin(){
        if(!minStack.isEmpty()){
            return minStack.peek();
        }
        return Integer.MIN_VALUE;
    }

    // Find Max
    public int findMax(){
        if(!maxStack.isEmpty()){
            return maxStack.peek();
        }
        return Integer.MAX_VALUE;
    }

    public static void main(String[] args) {

        DS ds = new DS();

        System.out.println("Push 7, 6, 5: ");
        ds.push(7);
        ds.push(6);
        ds.push(5);

        System.out.println("S1: " + stack);
        System.out.println("S2: " + minStack);
        System.out.println("S3: " + maxStack);

        System.out.println("Min till now: " + ds.findMin());
        System.out.println("Max till now: " + ds.findMax());

        System.out.println("Push 4, 3: ");
        ds.push(4);
        ds.push(3);

        System.out.println(stack);
        System.out.println(minStack);
        System.out.println(maxStack);

        System.out.println("Min till now: " + ds.findMin());
        System.out.println("Max till now: " + ds.findMax());

        System.out.println("1 pop(): ");
        ds.pop();
        System.out.println("Min till now: " + ds.findMin());
        System.out.println("Max till now: " + ds.findMax());

        System.out.println("1 pop(): ");
        ds.pop();
        System.out.println("Min till now: " + ds.findMin());
        System.out.println("Max till now: " + ds.findMax());
    }
}


texts: Simple AngularJS controller for REST API

texts:
We record software builds from our build machine into a database and for practice purposes I'm building a little web dashboard for it.

The API is REST (WebApi) and provides access to query for Products, Branches, Profiles and specific Builds.

The controller queries all products (each product contains a list of branches and profiles it has been build for) as well as all branches and profiles anything was ever built for.

It then goes on to query the last 10 builds for each of the branches and profiles a product was built for.

This is my first attempt at anything related to web-programming so I thought I'll get someone to look at it. Here is the code:

(function (angular) {
    var app = angular.module("app", ["ngResource"]);

    app.factory("Product", ["$resource", function ($resource) {
        return $resource("/api/Product");
    }]);

    app.factory("Build", ["$resource", function ($resource) {
        return $resource("/api/Build");
    }]);

    app.factory("BasicResource", ["$q", "$http", function ($q, $http) {
        var resourceFactory = {
            async: function(type) {
                var d = $q.defer();
                var result = $http.get("/api/" + type).success(function() {
                    d.resolve(result);
                });
                return d.promise;
            }
        };
        return resourceFactory;
    }]);

    app.controller("MainCtrl", ["$rootScope", "$scope", "$q", "$http", "BasicResource", "Product", "Build", function ($rootScope, $scope, $q, $http, BasicResource, Product, Build) {
        $rootScope.title = "Build Dashboard";
        $scope.Builds = [];

        $q.all([
            Product.query().$promise,
            BasicResource.async("Branch"),
            BasicResource.async("Profile")
        ]).then(function(data) {
            $scope.Products = data[0];
            $scope.Branches = data[1].data;
            $scope.Profiles = data[2].data;
        }).then(function() {

            var allBuildQueries = [];
            $scope.Products.forEach(function (prod) {
                prod.branches.forEach(function(b) {
                    prod.profiles.forEach(function(prof) {
                        allBuildQueries.push(Build.query({ product: prod.name, branch: b, profile: prof, limit: 10 }).$promise);
                    });
                });
            });

            $q.all(allBuildQueries).then(function (allBuilds) {
                allBuilds.forEach(function(builds) {
                    builds.forEach(function(build) {
                        $scope.Builds.push(build);
                    });
                });
            });
        });
    }]);

})(angular);

There are a few things which I don't really like about it so far but don't know how to improve it:

The /api/Branch and /api/Profile resources return a list of strings. This causes the issue described in the SO question. The two basic workarounds are to use $http or transform the response. I have used $http because it seemed the easiest and I have not figured out how to use transformResponse properly so far (documentation on that is somewhat light). However it results in the factories (Branch and Profile vs Product and Build) having slightly different interfaces which bugs me.
The second issue is the async query of the builds. Currently it queries Number of Branches x Number of Profiles per product for all products. At the moment this results in about 90 queries and really is no problem. However I'm wondering how this should be done properly in case the number of queries can grow into the hundreds or thousands.
The way how I combine all the build query results seems somewhat inelegant to me. In C# I'd use a LINQ query like allBuilds.SelectMany(x => x.builds).ToList(). Would strike me as weird if there wouldn't be a more elegant javascript way of doing it.
Since asking the question I have started using linqjs so that solves this issue.


texts:
(Initial discussion from Classic merge sort, since it is new code, I start a new thread)

Post my code below, my major question is, I have to create another array result to hold sub-parts merge sort result. Is there a way I can just use original number to save additional space in result?

Any other comments on code bugs, performance (in terms of algorithm time complexity), code style, etc. are appreciated.

Code written in Python 2.7.

def merge_sort(numbers, start, end):
    if start == end:
        return
    pivot_index = start + (end-start)//2
    merge_sort(numbers, start, pivot_index)
    merge_sort(numbers, pivot_index+1, end)
    i = start
    j = pivot_index+1
    result = []
    while i <= pivot_index and j <= end:
        if numbers[i] <= numbers[j]:
            result.append(numbers[i])
            i+=1
        else:
            result.append(numbers[j])
            j+=1
    if i <= pivot_index:
        result.extend(numbers[i:pivot_index+1])
    if j <= end:
        result.extend(numbers[j:end+1])
    k=0
    for i in range(start, end+1):
        numbers[i] = result[k]
        k+=1

if __name__ == "__main__":
    numbers = [1,4,2,5,6,8,3,4,0]
    merge_sort(numbers, 0, len(numbers)-1)
    print numbers


texts:
I have a big Python dictionary with more then 150,000 keys every key has list value. This dictionary contains infinitive words as key and all grammatical forms of these words as values:

 {"конфузити": ["конфузить", "конфужу", "конфузиш", "конфузить", "конфузим", "конфузимо", "конфузите", "конфузять", "конфузитиму", "конфузитимеш", "конфузитиме", "конфузитимем", "конфузитимемо", "конфузитимете", "конфузитимуть", "конфузив", "конфузила", "конфузило", "конфузили"]}

I formed list of words from particular text there are  more then 2m words in it, every word has it's grammatical form. So what I am trying to do is searching  these words in my dictionary values and returning dictionary keys, which as I have already told, are base or dictionary forms of words. This process is called lemmatization. Have tried different approaches but they are all too slow.

In this part I perform text tokenization.

lst =[]
with open("/home/yan/PycharmProjects/vk/my_patrioty/men_patrioty.txt", 'r', encoding="utf-8") as f:
    for sent in f:
        sent = sent.lower()
        sent = re.sub("[A-z0-9\'\"`\|\/\+\#\,\)\(\?\!\B\-\:\=\;\.\«\»\—\@]", '', sent)
        sent = re.findall('\w+', sent)
        for word in sent:
            lst.append(word)

In this part I am trying to perform binary search but is very slow.

with open("/home/yan/data.txt") as f:
    d = json.load(f)
    for w in lst:   #list of my words
        for key, value in d.items():
            lb = 0
            ub = len(value)
            mid_index = (lb + ub) // 2
            item_at_mid = value[mid_index]
            if item_at_mid == w:
                    print(key)
            if item_at_mid < w:
                    lb = mid_index + 1
            else:
                ub = mid_index

This is liner search it is a bit faster. But still not enough fast for my amount of data.

with open("/home/yan/data.txt") as f:
    d = json.load(f)  #dictionary to search in
    for w in lst:
        for key, value in d.items():
              if w in value:
                  print(key)

Below you can find links to my dictionary and sample of data to test it. If somebody does not know it is Ukrainian language that is presented in data set.

Dictionary data:

https://drive.google.com/file/d/0ByIY5scTeLYqbXp6OExKa0xXbDg/view?usp=sharing

Sample of text:

https://drive.google.com/file/d/0ByIY5scTeLYqMHhHbUJ5aXRWdWs/view?usp=sharing


texts: Setting variables inside if / else-if statment blocks

texts:
I have written the code below and I am trying to work out if there is a more efficient way of doing it: i.e. less lines of code and quicker etc.

I am also wondering whether it is OK to declare variables inside of an if ... else if statement.

function test() {
    var x = 3;
    if (x > 5) {
        var msg = "m", state = "d";
    } else if (x < 5) {
        var msg = "a", state = "d";
    } else {
        var msg = "e", state = "n";
    }
    $('#id1').removeClass().addClass(state);
    $('#id2').html("Some text " + msg + " and more text.");
    $('#id3').attr('title', "Different text " + msg + " still different text.");
}

As background, the following code is the original code I had before refactoring/rewriting:

function test() {
  var x = 3;
  if (x > 5) {
        $('#id1').removeClass().addClass('d');
        $('#id2').html("Some text message and more text.");
        $('#id3').attr('title', "Different text message still different text.");
  } else if (x < 5) {
        $('#id1').removeClass().addClass('d');
        $('#id2').html("Some text message2 and more text.");
        $('#id3').attr('title', "Different text message2 still different text.");
  } else {
        $('#id1').removeClass().addClass('n');
        $('#id2').html("Some text message3 and more text.");
        $('#id3').attr('title', "Different text message3 still different text.");
  }
}


texts: Leetcode longest substring without repeating characters

texts:
Link here
I'm currently learning c++ coming from a python background, so I'll include a solution in python and in c++ for the following problem statement and based on very helpful answers obtained on my previous question I made some improvements in the c++ implementation:

Given a string s, find the length of the longest substring without repeating characters.

Example 1:
Input: s = "abcabcbb"
Output: 3
Example 2:
Input: s = "bbbbb"
Output: 1
I would like to improve speed for both python and c++ implementations, and I need to improve memory consumption in the c++ implementation since I got a very high figure (600+ MB) as well as the reasons for this high consumption (if the figure is accurate), and I would like general suggestions too.
longest_substring.py
def get_longest(s: str):
    possibilities = (s[i:] for i in range(len(s)))
    maximum = 0
    for possibility in possibilities:
        end_idx = maximum
        while end_idx <= len(possibility):
            current_chunk = possibility[0:end_idx]
            end_idx += 1
            if not (current_size := len(current_chunk)) == len(set(current_chunk)):
                break
            maximum = max(current_size, maximum)
    return maximum

if __name__ == '__main__':
    print(f'Longest substring:\n{get_longest("abcabcbb")}')

Leetcode stats:

Runtime: 260 ms, faster than 19.36% of Python3 online submissions for Longest Substring Without Repeating Characters.

Memory Usage: 14.4 MB, less than 100.00% of Python3 online submissions for Longest Substring Without Repeating Characters.

longest_substring.h
#ifndef LEETCODE_LONGEST_SUBSTRING_H
#define LEETCODE_LONGEST_SUBSTRING_H

#include <string>

int longest_sub(const std::string &s);
bool check_unique(const std::string &s);

#endif //LEETCODE_LONGEST_SUBSTRING_H

longest_substring.cpp
#include "longest_substring.h"
#include <iostream>
using std::endl;
using std::cout;
using std::string;

bool check_unique(const string &s) {
    for (size_t i = 0; i < s.size() - 1; ++i) {
        for (size_t j = i + 1; j < s.size(); ++j) {
            if (s[i] == s[j])
                return false;
        }
    }
    return true;
}

int longest_sub(const string &s) {
    int maximum = 0;
    for (size_t i = 0; i < s.size(); ++i) {
        const string possibility = s.substr(i);
        auto end_idx = maximum;
        while (end_idx < possibility.size()) {
            const string current_chunk = possibility.substr(0, ++end_idx);
            if (!check_unique(current_chunk))
                break;
            auto current_size = current_chunk.size();
            if (current_size > maximum)
                maximum = current_size;
        }
    }
    return maximum;
}

int main() {
    cout << "Longest substring: " << endl;
    cout << longest_sub("abcabcbb");
}

Leetcode stats:

Runtime: 100 ms, faster than 14.88% of C++ online submissions for Longest Substring Without Repeating Characters.

Memory Usage: 604.2 MB, less than 5.02% of C++ online submissions for Longest Substring Without Repeating Characters.


texts:
Some patterns are emerging ("fmap (b->a) . fmap (c->b) . .. . (IO z)"). Also infix zip is kind-of a hack.

What is:

Best practice in point-free style?
Best practice?

Elegance > Performance;  Functional > Imperative

import qualified Data.Map.Lazy as M
import qualified Data.ByteString.Char8 as BS

fromFile :: FilePath -> IO (M.Map Char Int)
fromFile = fmap (M.fromListWith (+)) . fmap (`zip` [1,1..]) . readFile
    where readFile = fmap BS.unpack . BS.readFile


texts:
I was playing around with sorting methods, brushing up on my algorithms. I have made the following implementation of quicksort:
def quicksort(l):

    def inner_qs(list_, start, end):
        if end - start > 1:
            piv = list_[end - 1]
            aux_index = start
            for i in range(start, end):
                if list_[i] < piv or i == end - 1:
                    list_[aux_index], list_[i] = list_[i], list_[aux_index]
                    aux_index += 1
            pivot_position = aux_index - 1
            # left
            inner_qs(list_, start=start, end=pivot_position)
            # right
            inner_qs(list_, start=pivot_position + 1, end=end)

    l = l[:]
    inner_qs(l, 0, len(l))
    return l

Please, take a look at it.


texts: Calculate huge Fibonacci Numbers in C++ using GMP and boost::multiprecision

texts:
Problem Statement

Calculate the exact value of the n-th Fibonacci number, say the one-billionth.

Algorithm

The algorithm is based on the idea that Fibonacci numbers can be represented as 2x2 matrices, in particular as powers of the matrix [ 1 1; 1 0]. Matrices of this form can be represented implicitly without having to store all 4 elements as [ a+b a; a b ]. In particular, we only need to store a and b to represent the matrix. This not only saves memory but we can perform fewer operations when multiplying or squaring matrices if we work on the implicit form.

The other aspect of the algorithm is exponentiation by squaring, the idea that we can calculate a^(2^n) very quickly by starting with a and repeatedly squaring. To calculate the n-th Fibonacci number, we simply compute the n-th power of the basis matrix (using the implicit form) and read off the diagonal element a.

Build and Implementation Details

For performance we use the boost::multiprecision::mpz_int wrapper around the Gnu MP library. The mpz_int type is a lightweight wrapper around GMP which gives it a C++-style interface with overloaded operators.  The GMP is an "arbitrary precision arithmetic" library for doing math with numbers that don't fit into 64 bits. I installed these libraries on Debian/Ubuntu like so:

sudo apt install libboost-all-dev libgmp-dev

The following program was built like so:

g++ -std=c++17 -O3 -o fib main.cpp -lgmp

Program

#include <iostream>
#include <boost/multiprecision/gmp.hpp>

typedef boost::multiprecision::mpz_int bigint;

namespace fib {

class ImplicitMatrix {
public:
    bigint a;
    bigint b;

    ImplicitMatrix(const ImplicitMatrix& other)
        : a(other.a)
        , b(other.b)
    {
    }

    ImplicitMatrix(
        const bigint& _a,
        const bigint& _b)
        : a(_a)
        , b(_b)
    {
    }
};

ImplicitMatrix multiply(
    const ImplicitMatrix& x,
    const ImplicitMatrix& y)
{
    return {
        y.a * (x.a + x.b) + x.a * y.b,
        x.a * y.a + x.b * y.b
    };
}

ImplicitMatrix square(const ImplicitMatrix& x)
{
    // we save one bigint multipication by
    // specializing for the case of squaring.
    bigint a2 = x.a * x.a;
    bigint _2ab = (x.a * x.b) << 1;
    bigint b2 = x.b * x.b;
    return {
        a2 + _2ab,
        a2 + b2
    };
}

ImplicitMatrix power(
    const ImplicitMatrix& x,
    const bigint& m)
{
    if (m == 0) {
        return { 0, 1 };
    }
    else if (m == 1) {
        return x;
    }

    // powers of two by iterated squaring
    ImplicitMatrix powerOfTwo = x;
    bigint n = 2;
    while (n <= m) {
        powerOfTwo = square(powerOfTwo);
        n = n * 2;
    }
    // recurse for remainder
    ImplicitMatrix remainder = power(x, m - n / 2);

    return multiply(powerOfTwo, remainder);
}

} // end namespace fib

bigint fibonacci(const bigint& n)
{
    fib::ImplicitMatrix f1{ 1, 0 };
    return fib::power(f1, n).a;
}

int main(int argc, const char* argv[])
{
    // require the first command line argument
    if (argc < 2) {
        std::cerr << "USAGE: fib N" << std::endl;
        return 1;
    }
    // parse the first argument into a bigint
    bigint n(argv[1]);

    // force the calculation of the n-th fibonacci
    // number but do not print it.
    volatile bigint f = fibonacci(n);
    return 0;
}

I am looking for style advice, modern C++ tips, performance suggestions, and best practices.


texts: Counting number of 1's and 0's from integer with bitwise operation

texts:
Is there a better way of doing this?

// Definition: Count number of 1's and 0's from integer with bitwise operation
//
// 2^32 = 4,294,967,296
// unsigned int 32 bit

#include<stdio.h>

int CountOnesFromInteger(unsigned int);

int main()
{
    unsigned int inputValue;
    short unsigned int onesOfValue;
    printf("Please Enter value (between 0 to 4,294,967,295) : ");
    scanf("%u",&inputValue);
    onesOfValue = CountOnesFromInteger(inputValue);

    printf("\nThe Number has \"%d\" 1's and \"%d\" 0's",onesOfValue,32-onesOfValue);
}

int CountOnesFromInteger(unsigned int value)
{
    unsigned short int i, count = 0;
    for(i = 0; i < 32 ; i++)
    {
        if (value % 2 != 0)
        {
            count++;
        }
        value = value >> 1;
    }
    return count;
}


texts: Search strings within a list from strings within a dictionary with the least complexity

texts:
I have the following input:

newValue = [['men', 'John Doe,Chris perry'], ['women', 'Mary,Anne,Lita']] - list within list

keywords_list = [('MEN', 'john,zack')]    - tuple in a list (Dictionary on which .items() is used.)

Expected Output is:

newValue = [['men', 'John Doe'],['women','']]

What I want to do here is extract those names for Men which is common in both newValue and keywords_list.

Below is my working implementation that gets the desired result:

      allValues = []
      for item in newValue:
            for key in keywords_list:
                if str(item[0])[1:].upper() == key[0]:
                    ValueSplit = item[1].split(',')
                    keyWordSplit = key[1].split(',')
                    for EverySplit in ValueSplit:
                        for everyKey in keyWordSplit:
                            if everyKey.lower() in EverySplit.lower():
                                pass
                            else:
                                ValueSplit.remove(EverySplit)
                    item[1]= ValueSplit
      allValues.append(item)

This isn't an efficient way of solving the problem. If anyone could recommend an efficient way with lesser complexity to achieve the desired result, it would be really helpful.


texts:
I am in the process of learning Clojure. I am fairly new to functional programming and would like to know if my code smells or if there are any performance implications with my approach.

; Returns the the given sequence with the given item appended to it.
(defn snoc [xs x] (concat xs [x]))

; Returns the Fibonacci sequence up to the highest number less than max.
(defn fib [max]
  (loop [a 1, b 1, acc [1]]
    (if (> b max)
      acc
      (recur b (+ a b) (snoc acc b)))))

; Project Euler Problem 2: Attempt A
(defn pe2a []
  (reduce +
    (filter even? (fib 4000000))))

For reference:

  Each new term in the Fibonacci
  sequence is generated by adding the
  previous two terms. By starting with 1
  and 2, the first 10 terms will be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the
  Fibonacci sequence whose values do not
  exceed four million, find the sum of
  the even-valued terms.


texts: Point utilities in ClojureScript and Reagent

texts:
As one of my first "real" projects in Clojure(Script), I took one of the programming exercises from my Algebra II textbooks. The goal is to receive two 2D coordinates from the user and calculate the distance, midpoint, and slope of the resulting line segment. What I have written fulfills the requirements, but I feel like it is very repetitive (e.g. pt1-str pt2-str, or x1 y1 x2 y2). I have only posted the cljs code, since nothing else is relevant to the problem, and I'm fairly confident that the other code is ok.

(ns project2.core
    (:require [reagent.core :as r]
              [clojure.string :as str]
              [cljs.pprint :as pprint]))

(enable-console-print!)

;; data functions

(defn parse-inputs [input]
  (map js/parseFloat (str/split input ",")))

(defn input-valid? [pt-str]
   (let [parsed (parse-inputs pt-str)]
     (and
      (= 2 (count parsed))
      (every? #(not (js/isNaN %)) parsed))))

(defn dist [[x1 y1 x2 y2]]
  (let [dx (.abs js/Math (- x1 x2))
        dy (.abs js/Math (- y1 y2))]
    [(.sqrt js/Math (+ (* dx dx) (* dy dy)))]))

(defn mdpt [[x1 y1 x2 y2]]
  [(/ (+ x1 x2) 2) (/ (+ y1 y2) 2)])

(defn slope [[x1 y1 x2 y2]]
  [(/ (- y1 y2) (- x1 x2))])

(defn value-of [f pt1-str pt2-str]
 (->> [pt1-str pt2-str]
     (map parse-inputs)
     (flatten)
     (f)
     (map #(pprint/cl-format nil "~,2f" %))
     (str/join ", ")))

;; ui functions

(defn text-input [place-holder value-atom]
  (fn []  [:input {:placeholder place-holder
                   :type "text"
                   :on-change #(reset! value-atom (-> % .-target .-value))}] ))

(defn invalid-input []
  [:h3.invalid-input.center "Enter a valid input to see the answer."])

(defn answer [pt1-str pt2-str]
  [:table.center.top-space.valid-answer
   [:tr [:td "Distance"]       [:td (value-of dist pt1-str pt2-str)]]
   [:tr [:td "Midpoint"]       [:td (str "(" (value-of mdpt pt1-str pt2-str) ")")]]
   [:tr [:td "Slope"]          [:td (value-of slope pt1-str pt2-str)]]])

(defn answer-container [pt1-atom pt2-atom]
  (fn []
    (if (every? input-valid? [@pt1-atom @pt2-atom])
      [answer @pt1-atom @pt2-atom]
      [invalid-input])))

(defn container []
 (let [pt1 (r/atom "") pt2 (r/atom "")]
   (fn []
     [:div [text-input "x, y" pt1]
           [text-input "x, y" pt2]
           [answer-container pt1 pt2]])))

(r/render-component [container]
       (. js/document (getElementById "content")))

Here is a screen shot, if you are interested.


texts:
I have found the need to schedule a few simple functions in a first-come-first-served way so I developed a small task scheduler based on multiprocessing and I thought it would be a good candidate for my first question here.

I'm open to all kind of comments, regarding style, conventions, possible bugs and other things I'm not considering now. I added some comments for the most sensible mechanism but this is mostly a half-day code.

from multiprocessing import Process
from multiprocessing import JoinableQueue

def worker_process(in_queue, out_queue):
    run = True
    while run:
        # in the queue there should be a Job or None.
        # Latter case is the signal that we should stop.
        task = in_queue.get()
        if task:
            task.run()
            in_queue.task_done()
            # when done, we signal and we put the task id in the output queue
            out_queue.put(task.get_id())
        else:
            run = False

class Scheduler:
    def __init__(self, job_done_cb, cb_args=[], N=2):
        self.n = N
        self.processes = []
        self.job_queue = JoinableQueue()
        self.done_queue = JoinableQueue()
        self.job_done_cb = job_done_cb
        self.cb_args = cb_args
        for i in range(self.n):
            # these workers will get jobs from the queue and give us back the id when done
            p = Process(target=worker_process, args=(self.job_queue, self.done_queue))
            self.processes.append(p)
        # there process will get back the job of the id done and execute the callback
        self.cb_process = Process(target=self.on_job_done)

    def start(self):
        for p in self.processes:
            p.start()
        self.cb_process.start()

    def stop(self):
        # add the necessary None to the queue and wait for the processes to be done
        # this will make the queue execute the remaining task before finishing
        for i in range(self.n):
            self.job_queue.put(None)
        self.job_queue.close()
        for p in self.processes:
            p.join()
        self.done_queue.put(None)
        self.cb_process.join()

    def add_task(self, task_id, task, arg_list):
        job = Job(task, task_id, arg_list)
        self.job_queue.put(job)

    def wait_for_idle(self):
        self.job_queue.join()

    def on_job_done(self):
        run = True
        while run:
            # again, if the id is not None then we should go on waiting for stuff
            done = self.done_queue.get()
            if done:
                self.job_done_cb(self, done, *self.cb_args)
            else:
                run = False

class Job:
    def __init__(self, task, job_id, arg_list):
        self.task = task
        self.id = job_id
        self.arg_list = arg_list

    def run(self):
        self.task(*self.arg_list)

    def get_id(self):
        return self.id


texts:
My attempt at creating a snake game, in pygame. I tried to make it as simple as possible, but i feel it could be better in terms of best practice, and efficiency, along the idea of avoiding redundant code.
It would be appreciated, if anyone can give me advice in that regard.
import pygame
import time
import random
pygame.init()
pygame.font.init()

WINDOW = pygame.display.set_mode((500, 500))

pygame.display.set_caption('snake')

FOOD_COORS = []

TICK = 15

RUN = True
SNAKE_COMP = [[50, 50, 2], [40, 50, 2], [30, 50, 2], [20, 50, 2], [10, 50, 2]]
f = [random.randint(0, 50)*10, random.randint(0, 50)*10]
d = 2
CLOCK = pygame.time.Clock()

def hit():
    time.sleep(3)
    pygame.quit()

class snake():
    def __init__(self, SNAKE_COMP):
        self.x, self.y = SNAKE_COMP[0][0:2]
    def draw(self, SNAKE_COMP):
        self.SNAKE_COMP = SNAKE_COMP
        for i in range(0, len(SNAKE_COMP)):
            pygame.draw.rect(WINDOW, (255, 255, 255), (SNAKE_COMP[i][0], SNAKE_COMP[i][1], 10, 10))

    def hit_check(self, SNAKE_COMP):
        self.SNAKE_COMP = SNAKE_COMP
        if SNAKE_COMP[0][0] >= 500 or SNAKE_COMP[0][0] < 0:
            hit()
        if SNAKE_COMP[0][1] >= 500 or SNAKE_COMP[0][1] < 0:
            hit()
        test_l = [[]]
        for i in range(0, len(SNAKE_COMP)):
            test_l.append(tuple(SNAKE_COMP[i][0:2]))
        for i in range(0, len(test_l)):
            if test_l.count(test_l[i]) > 1:
                hit()

class food():
    global FOOD_COORS
    def draw(self):
        x, y = self.x, self.y
        pygame.draw.rect(WINDOW, (255, 0, 0), (x, y, 10, 10))
    def spawn(self, SNAKE_COMP):
        global FOOD_COORS
        self.SNAKE_COMP = SNAKE_COMP
        test_l = [[]]
        for i in range(0, len(SNAKE_COMP)):
            test_l.append(SNAKE_COMP[i][0:2])
        g = True
        while g:
            x = random.randint(0, 49)*10
            y = random.randint(0, 49)*10
            if [x, y] not in test_l:
                g = False
        FOOD_COORS = [x, y]
        self.x, self.y = x, y
snek = snake(SNAKE_COMP)
apple = food()
apple.spawn(SNAKE_COMP)
s = False
g = False
while RUN:
    CLOCK.tick(TICK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            RUN = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP] and d != 3:
        d = 1
    elif keys[pygame.K_RIGHT] and d != 4:
        d = 2
    elif keys[pygame.K_DOWN] and d != 1:
        d = 3
    elif keys[pygame.K_LEFT] and d != 2:
        d = 4
    if g != True and SNAKE_COMP[0][0:2] != FOOD_COORS:
        last = len(SNAKE_COMP) - 1
        for i in range(1, len(SNAKE_COMP)):
            SNAKE_COMP[len(SNAKE_COMP)-i][2] = SNAKE_COMP[len(SNAKE_COMP)-i-1][2]
        SNAKE_COMP[0][2] = d
        for i in range(0, len(SNAKE_COMP)):
            if SNAKE_COMP[i][2] == 1:
                SNAKE_COMP[i][1] -= 10
            elif SNAKE_COMP[i][2] == 2:
                SNAKE_COMP[i][0] += 10
            elif SNAKE_COMP[i][2] == 3:
                SNAKE_COMP[i][1] += 10
            elif SNAKE_COMP[i][2] == 4:
                SNAKE_COMP[i][0] -= 10
    else:
        k = SNAKE_COMP[0][2]
        FOOD_COORS.append(k)
        if k == 1:
            FOOD_COORS[1] -= 10
        elif k == 2:
            FOOD_COORS[0] += 10
        elif k == 3:
            FOOD_COORS[1] += 10
        elif k == 4:
            FOOD_COORS[0] -= 10
        SNAKE_COMP.insert(0, FOOD_COORS)
        apple.spawn(SNAKE_COMP)
    snek.hit_check(SNAKE_COMP)
    apple.draw()
    snek.draw(SNAKE_COMP)
    pygame.display.update()
    WINDOW.fill((0, 0, 0))

pygame.quit()


texts:
I made a placeholder for entry widgets from tkinter, so I was wondering how good it is. I just started learning Python a bit before, so please do correct me if I'm wrong or if I missed something, or some easy steps or where it loses the efficiency.
Code:
import tkinter as tk
from tkinter import ttk

class PlaceholderEntry(ttk.Entry):
    '''
    Custom modern Placeholder Entry box, takes positional argument master and placeholder\n
    Use acquire() for getting output from entry widget\n
    Use shove() for inserting into entry widget\n
    Use remove() for deleting from entry widget\n
    Use length() for getting the length of text in the widget\n
    BUG 1: Possible bugs with binding to this class\n
    BUG 2: Potential bugs with config or configure method
    '''

    def __init__(self, master, placeholder, **kwargs):
        # style for ttk widget
        self.s = ttk.Style()
        self.s.configure('my.TEntry', foreground='black', font=(0, 0, 'normal'))
        self.s.configure('placeholder.TEntry', foreground='grey', font=(0, 0, 'bold'))

        # init entry box
        ttk.Entry.__init__(self, master,style='my.TEntry', **kwargs)
        self.text = placeholder
        self.__has_placeholder = False  # placeholder flag

        # add placeholder if box empty
        self._add()

        # bindings of the widget
        self.bind('<FocusIn>', self._clear)
        self.bind('<FocusOut>', self._add)
        self.bind('<KeyRelease>',self._normal)

    def _clear(self, *args):  # method to remove the placeholder
        if self.get() == self.text and self.__has_placeholder:  # remove placeholder when focus gain
            self.delete(0, tk.END)
            self.configure(style='my.TEntry')
            self.__has_placeholder = False  # set flag to false

    def _add(self, *args):  # method to add placeholder
        if self.get() == '' and not self.__has_placeholder:  # if no text add placeholder
            self.configure(style='placeholder.TEntry')
            self.insert(0, self.text)  # insert placeholder
            self.icursor(0)  # move insertion cursor to start of entrybox
            self.__has_placeholder = True  # set flag to true

    def _normal(self, *args):  # method to set the text to normal properties
        self._add()  # if empty add placeholder
        if self.get() == self.text and self.__has_placeholder:  # clear the placeholder if starts typing
            self.bind('<Key>', self._clear)
            self.icursor(-1)  # keep insertion cursor to the end
        else:
            self.configure(style='my.TEntry')  # set normal font

    def acquire(self):  # custom method to get the text
        if self.get() == self.text and self.__has_placeholder:
            return 'None'
        else:
            return self.get()

    def shove(self, index, string):  # custom method to insert into entry
        self._clear()
        self.insert(index, string)

    def remove(self, first, last):  # custom method to remove from entry
        if self.get() != self.text:
            self.delete(first, last)
            self._add()
        elif self.acquire() == self.text and not self.__has_placeholder:
            self.delete(first, last)
            self._add()

    def length(self):
        if self.get() == self.text and self.__has_placeholder:
            return 0
        else:
            return len(self.get())

#usage of class
if __name__ == '__main__':
    root = tk.Tk()
    e = PlaceholderEntry(root,placeholder='Type something here...')
    e.pack(padx=10,pady=10)
    root.mainloop()

Edit:
The older update used global changes, which lead to problems when using more than one entry widget, now that is fixed.


texts: Implementation of merge sort algorithm in C++

texts:
This is my implementation of "merge sort" in C++. I'm still a newbie at C++ so:

Have I understood how merge sort works and implemented it in the right way?
Have I used any bad practices?
How could the code be improved upon in terms of efficiency?

Criticism is welcome and appreciated!

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

vector<float> merge(vector<float> firstHalf, vector<float> secondHalf){
    vector<float> combined;
    for(int i = firstHalf.size() + secondHalf.size(); i > 0;  i--){//merge two vectors
        if(firstHalf.back() > secondHalf.back() && !firstHalf.empty()){
            combined.push_back(firstHalf.back());
            firstHalf.pop_back();
        }else if(!secondHalf.empty()){
            combined.push_back(secondHalf.back());
            secondHalf.pop_back();
        }
    }
    vector<float> revCombined;//reverse merged vectors. Vectors don't have pop_front and I didn't want to use lists.

    for(int i = 0; i < combined.size(); i++){
        revCombined.push_back(combined[combined.size()-i-1]);
    }
    return revCombined;
}

vector<float> mergeSort(vector<float> &inputArray){//for example [9, 8, 1] as input
    if(inputArray.size() > 1){
        vector<float> firstHalf;
        vector<float> secondHalf;

        for(int i = 0; i < inputArray.size()/2; i++){//auto round the input array because size() returns int
            firstHalf.push_back(inputArray[i]);
        }//first half = [9, 8]

        for(int i = inputArray.size()/2; i < inputArray.size(); i++){
            secondHalf.push_back(inputArray[i]);
        }//second half = [1]

        return merge(mergeSort(firstHalf), mergeSort(secondHalf));
    }
    else{
        return inputArray;
    }
}

vector<string> split(string str, char delimiter) {
    vector<string> internal;
    stringstream ss(str); // Turn the string into a stream.
    string tok;

    while(getline(ss, tok, delimiter)) {
        internal.push_back(tok);
    }

    return internal;
}
vector<float> floatVectorInput(){
    string inputString;
    getline(cin, inputString);

    vector<string> stringArray = split(inputString, ' ');

    vector<float> array;
    for(int i = 0; i < stringArray.size(); i++){
        array.push_back(stof(stringArray[i]));
    }
    return array;
}

int main(){
    cout << "Array to sort (separate by spaces): " << endl;
    vector<float> inputArray = floatVectorInput();

    vector<float> sorted = mergeSort(inputArray);

    cout << endl << "Sorted Array:" << endl;
    for(int i = 0; i < sorted.size(); i++){
        cout << sorted[i];
        if(i == sorted.size()-1){
            cout << endl << endl;
        }else{
            cout << ", ";
        }
    }
    return 0;
}


texts: Using a for-loop or sleeping to wait for short intervals of time

texts:
I need to wait for short intervals of time in my program, but I really don't want to include unistd.h just to use sleep, so I'm doing it this way:

int main()
{
for(int i=0; i<=100000000000; i++); // <----- note that the loop doesn't do anything
return 0;
}

I do this when I don't really have a specific interval to set for sleep.

Is there anything wrong with this?  Would this harm the program in any way?

In C I know that if I did include unistd.h, and that if I used sleep(), that the following code would also make the program wait for a short interval of time:

int main()
{
sleep(2000); //or whatever the number (in milliseconds)
return 0;
}


texts: Avoiding Arrow Pattern with C# Pattern Matching

texts:
I have started to use C# 7's type based pattern matching. A method that only manages a single pattern-based result looks very clean and is easy to reason about.
However, once a second pattern-based result that depends on the first pattern-based result creates an arrow anti-pattern, and will only get worse with n-results that depend on each other.
Here is an simplified example that demonstrates the arrow pattern:
public Result<bool> ValidateSomething(string strId)
{
    var id = Guid.Parse(strId);
    Result<Something> fetchSomethingResult = new SomethingDao.FetchSomething(id);
    switch (fetchSomethingResult)
    {
        case ValueResult<Something> successfulSomethingResult:
            Result<Related> fetchRelatedFieldsResult = new RelatedDao.FetchRelatedFields(successfulSomethingResult.Value.RelatedId);

            switch (fetchRelatedFieldsResult)
            {
                case ValueResult<Related> successfulFieldValueResult:
                    var isValid = successfulSomethingResult.Value.ComparableVal <= successfulFieldValueResult.Value.RelatedComparableVal;
                    return new ValueResult<bool>(isValid);
                case ValueNotFoundResult<Related> _:
                    return new ValueNotFoundResult<bool>();
                case ErrorResult<Related> errorResult:
                    return new ErrorResult<bool>(errorResult.ResultException);
                default:
                    throw new NotImplementedException("Unexpected Result Type Received.");
            }
        case ValueNotFoundResult<Something> notFoundResult:
            return new ValueNotFoundResult<bool>();
        case ErrorResult<Something> errorResult:
            return new ErrorResult<bool>(errorResult.ResultException);
        default:
            throw new NotImplementedException("Unexpected Result Type Received.");
    }
}

For reference, these are the definitions for the Result classes:
public abstract class Result<T>
{

}

public class ValueResult<T> : Result<T>
{
    public ValueResult()
    {
    }

    public ValueResult(T inValue)
    {
        Value = inValue;
    }

    public T Value { get; set; }
}

public class ValueNotFoundResult<T> : Result<T>
{
    public ValueNotFoundResult()
    {
    }
}

public class ErrorResult<T> : Result<T>
{
    public Exception ResultException { get; set; }

    public ErrorResult()
    {
    }

    public ErrorResult(Exception resultException)
    {
        ResultException = resultException;
    }
}

What options are there to handle this type of code better? What suggestions do you have for the previous examples? How do I avoid the arrow anti-pattern with pattern-based results?


texts: Searching through rows of paged grid until row is found or there are no more pages

texts:
I have a GWT Grid, using a pager, so pages of the grid (table) can be any number of elements long. I'm looking to iterate over every row of each page until I find a row with the matching text in the corresponding column.
Here is an example of what the table looks like. http://samples.gwtproject.org/samples/Showcase/Showcase.html#!CwDataGrid

  def find_account_by_column(column, value)
    loop do
      k = worklist_table_element.find(false) { |row| row[column].text == value }
      return k if k

      return false if on_last_page?
      move_page_right
    end
  end

  def on_last_page?
    txt = worklist_nav_element[0][2].text
    match = txt.match(/(\d+)-(\d+) of \d+/)
    first, second = match.captures if match
    second.to_i - first.to_i <= 0
  end

  def move_page_right
    worklist_nav_element[0][3].element.click
    wait_to_process
  end

worklist_table_element is a GWT grid, with a pager, on_last_page? returns whether we are on the last page of the pager, and move_page_right goes to the next page. I'm thinking I could do this with recursion, but that just doesn't seem like the right solution. The reek gem seems to be indicating that I should be changing something here, I just don't see what I could change.

Using the reek gem on the code gives me a warning about NestedIterators and TooManyStatements (6). I don't see a way to make this simpler.


texts: Rendering partials dynamically in Rails 3

texts:
My User model has multiple roles (utilizing CanCan). Each role's dashboard view is different enough to warrant a partial for each role (admins get big-picture reports of users and app activity, students get big-picture overviews of grades, current courses, and lessons to be taken).

At first I had a case statement to iterate through the views based on current_user.role (of course, that was just temporary, even I know that!). Now, I have this:

<%= render "#{current_user.role}" %>

This doesn't feel right. What's the proper way to dynamically render partials (or maybe this method is perfectly fine)? Also, please mention why the proper way is best, as I want to learn from this.


texts: Return the best factors of a whole number

texts:
I've just finished writing my code to return the prime factors of a number and I feel the GetBestFactors function could be improved.
The GetFactors function was hacked together from the code found here:https://support.microsoft.com/en-us/kb/202782.  This returns all the factors of a number in a collection.

The GetBestFactors then loops through each number finding the best set to use.
So my question is - could the GetBestFactors function use less For...Next loops?

Sub Test()

    Dim tmp As Collection
    Set tmp = New Collection

    Dim tmp1 As Collection
    Set tmp1 = New Collection

    Set tmp = GetFactors(15) 'Change number - will return all factors.
    Set tmp1 = GetBestFactors(15) 'Change number - will return best factors.

    Debug.Assert False

End Sub

'Returns the factors of a whole number.
Public Function GetFactors(NumToFactor As Single) As Collection

    Dim Count As Integer
    Dim Factor As Single
    Dim y As Single
    Dim tmpCollection As Collection

    Set tmpCollection = New Collection

    Count = 0
    For y = 1 To NumToFactor
        Factor = NumToFactor Mod y
        If Factor = 0 Then
            tmpCollection.Add y
        End If
    Next y

    Set GetFactors = tmpCollection

End Function

'Returns the highest factors of a number.
Public Function GetBestFactors(NumToFactor As Single) As Collection

    Dim tmpFactors As Collection
    Dim FactorNums As Collection
    Dim x As Single, y As Single, z As Single
    Dim FirstFactor As Single

    Set tmpFactors = New Collection
    Set FactorNums = New Collection

    'Get all factors for the number.
    Set FactorNums = GetFactors(NumToFactor)

    'If the collection has 1 item then the NumToFactor is 1.
    'If there's 2 items then it's a prime number (1 and NumToFactor)
    If FactorNums.Count = 1 Or FactorNums.Count = 2 Then
        tmpFactors.Add FactorNums(FactorNums.Count)
    Else
        For x = FactorNums.Count - 1 To 1 Step -1
            If FactorNums(x) ^ 2 = NumToFactor Then
                tmpFactors.Add FactorNums(x)
                tmpFactors.Add FactorNums(x)
                Exit For
            Else
                For y = x To 1 Step -1
                    FirstFactor = FactorNums(y)
                    For z = y - 1 To 1 Step -1
                        If FirstFactor * FactorNums(z) = NumToFactor Then
                            tmpFactors.Add FirstFactor
                            tmpFactors.Add FactorNums(z)
                            Exit For
                        End If
                    Next z
                    If tmpFactors.Count = 2 Then Exit For
                Next y
            End If
            If tmpFactors.Count = 2 Then Exit For
        Next x
    End If

    Set GetBestFactors = tmpFactors

End Function


texts:
I worked on a problem from Automate the Boring Stuff Chapter 7:

Write a regular expression that can detect dates in the DD/MM/YYYY
format. Assume that the days range from 01 to 31, the months range
from 01 to 12, and the years range from 1000 to 2999. Note that if the
day or month is a single digit, it’ll have a leading zero.
The regular expression doesn’t have to detect correct days for each
month or for leap years; it will accept nonexistent dates like
31/02/2020 or 31/04/2021. Then store these strings into variables
named month, day, and year, and write additional code that can detect
if it is a valid date. April, June, September, and November have 30
days, February has 28 days, and the rest of the months have 31 days.
February has 29 days in leap years. Leap years are every year evenly
divisible by 4, except for years evenly divisible by 100, unless the
year is also evenly divisible by 400. Note how this calculation makes
it impossible to make a reasonably sized regular expression that can
detect a valid date.

Here's my code:
#Program that detects dates in text and copies and prints them

import pyperclip, re
#DD/MM/YEAR format
dateRegex = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)')
#text = str(pyperclip.paste())
text = 'Hello. Your birthday is on 29/02/1990. His birthday is on 40/09/1992 and her birthday is on 09/09/2000.'

matches = []
for groups in dateRegex.findall(text):
    day = groups[0]
    month = groups[1]
    year = groups[2]

    #convert to int for comparisons
    dayNum = int(day)
    monthNum = int(month)
    yearNum = int(year)

    #check if date and month values are valid
    if dayNum <= 31 and monthNum > 0 and monthNum <= 12:
        #months with 30 days
        if month in ('04', '06', '09', '11'):
            if not (dayNum > 0 and dayNum <= 30):
                continue
        #February only
        if month == '02':
            #February doesn't have more than 29 days
            if dayNum > 29:
                continue
            if yearNum % 4 == 0:
                #leap years have 29 days in February
                if yearNum % 100 == 0 and yearNum % 400 != 0:
                    #not a leap year even if divisible by 4
                    if dayNum > 28:
                        continue
            else:
                if dayNum > 28:
                    continue
        #all other months have up to 31 days
        if month not in ('02', '04', '06', '09', '11'):
            if dayNum <= 0 and dayNum > 31:
                continue
    else:
        continue
    date = '/'.join([groups[0],groups[1],groups[2]])
    matches.append(date)

if len(matches) > 0:
    pyperclip.copy('\n'.join(matches))
    print('Copied to clipboard:')
    print('\n'.join(matches))
else:
    print('No dates found.')

I've tested it out with various different date strings and it works as far as I can tell. I wanted to know about better ways of doing this though. As a beginner and an amateur, I understand there might be methods of writing the above code that are better and I don't mind being guided in the right direction and learning more about them. What is a better way of doing all of the above without using so many if statements?


texts: python script to download multiple reports from odoo

texts:
We have an odoo server running (http://www.odoo.com/documentation/9.0/api_integration.html), which allows us to programmatically query and download invoice reports as PDF's

We're running this on python 2.7.3.  I'm looking for tips on DRYness, future maintainability and help on blind spots in the code where something might go wrong, and the ability to output helpful data to the person running the script.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import xmlrpclib
import os

class UniReportPrinter():
    def __init__(self, mode):

        self.mode = mode

        from apiv9connector import s51OpenERPConnector_apiv9

        # during dev only get vals from prod that are needed
        self.odooconnection1 = s51OpenERPConnector_apiv9()
        self.odooconnection1.login()
        print "logged in"

        odooconnection1 = ''
        self.partners = []

    @property
    def partners(self):
        return self.partners

    @partners.setter
    def partners(self, value):
        self.partners = value

    def get_reports(self):
        nextmonth = self.__get_next_month()

        print('searching for invoices, filtered by:')
        print('state: open')
        print('date: ' + nextmonth.strftime("%Y-%m-%d"))
        print('reference: like SB%')

        invoice_ids = self.odooconnection1.models.execute_kw(
            self.odooconnection1.db, self.odooconnection1.uid, self.odooconnection1.password, 'account.invoice', 'search',
            [[('state', '=', 'open'), ('date_invoice', '=', nextmonth.strftime("%Y-%m-%d")),('reference', 'like', 'SB%')]])

        self.__get_partner_details(invoice_ids)
        self.__download_report(invoice_ids)

    def __get_next_month(self):
        from datetime import date
        from dateutil.relativedelta import *
        today = date.today()
        nextmonth = today+relativedelta(months=+1)
        nextmonth = nextmonth+relativedelta(day=1)

        return nextmonth

    def __get_partner_details(self, invoice_ids):
        partners = self.odooconnection1.models.execute_kw(
            self.odooconnection1.db, self.odooconnection1.uid, self.odooconnection1.password, 'account.invoice', 'search_read',
            [[['id', 'in', invoice_ids]]],
            {'fields': ['reference', 'id', 'partner_id']})

        self.partners = partners

    def __download_report(self, invoice_ids):
        for invoice_id in invoice_ids:
            report = xmlrpclib.ServerProxy('{}/xmlrpc/2/report'.format('https://odoo.example.com'))
            result = report.render_report(
                self.odooconnection1.db, self.odooconnection1.uid, self.odooconnection1.password, 'account.report_invoice', [invoice_id])
            filename = self.__get_file_name(invoice_id)
            sys.stdout.write("\r[%s]" % filename )
            sys.stdout.flush()
            self.__save_report(result, filename)

    def __get_file_name(self, invoice_id):
        partner = ([p for p in self.partners if p["id"] == invoice_id])[0]
        return str(partner['partner_id'][0])+'-'+partner['reference'] + '.pdf'

    def __save_report(self, report_data, filename):
        nextmonth = self.__get_next_month()
        year = nextmonth.year
        month = nextmonth.month
        path = str(year) + '/' + str(month) + '/'

        try:
            os.makedirs(path)
        except OSError:
            if not os.path.isdir(path):
                raise

        fileNamePath = os.path.join(path, filename)
        my_file = open(fileNamePath, 'w')
        my_file.write(report_data['result'].decode('base64'))
        my_file.close()

###############main#############

if __name__ == "__main__":

    unireportprinter = UniReportPrinter(mode='live')
    unireportprinter.get_reports()


texts: Extracting data from vue-chartjs into an array of datasets

texts:
I have a function which returns an array of datasets for a chart written with vue-chartjs. The getter getChartData returns an array with three objects with nested objects. I see that my function has a so called 'callback hell' and I want to refactor this.

getDatasets() {
  let datasetLabels = [];
  const obj = this.getChartData;
  Object.entries(obj).forEach((entry) => {
    datasetLabels = [...datasetLabels, ...Object.keys(entry[1])];
  });
  let datasets = [];
  [...new Set(datasetLabels)].forEach((item, index, arr) => {
    datasets.push({ label: item, backgroundColor: this.getColor(arr, index), data: [] });
  });
  Object.entries(obj).forEach((el) => {
    const datasetData = Object.entries(el[1]);
    datasetData.forEach(
      (item) => {
        datasets = datasets.map((e) => {
          if (e.label === item[0]) {
            e.data.push(item[1].median);
          }
          return e;
        });
      });
  });
  return datasets;
},


texts: C++ interview problem: finding an Island in a 2D grid

texts:
I was asked this question from an online coding interview and I have provided my solution that passes all of the test cases. I wanted to see if someone can review my code.

You can find my solution below using BFS. Here's also the link to the question that was asked at Pramp.

  Island Count

  Given a 2D array binaryMatrix of 0s and 1s, implement a function getNumberOfIslands that returns the number of islands of 1s in binaryMatrix.

  An island is defined as a group of adjacent values that are all 1s. A cell in binaryMatrix is considered adjacent to another cell if they are next to each either on the same row or column. Note that two values of 1 are not part of the same island if they’re sharing only a mutual “corner” (i.e. they are diagonally neighbors).

  Explain and code the most efficient solution possible and analyze its time and space complexities.

input:  binaryMatrix = [ [0,    1,    0,    1,    0],
                         [0,    0,    1,    1,    1],
                         [1,    0,    0,    1,    0],
                         [0,    1,    1,    0,    0],
                         [1,    0,    1,    0,    1] ]

output: 6 # since this is the number of islands in binaryMatrix.
          # See all 6 islands color-coded below.

#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>

#define AND &&
using namespace std;

int getNumberOfIslands( const vector<vector<int>>& binaryMatrix )
{
  int ans=0;
  int n = binaryMatrix.size();
  if (!n) return 0;
  int m = binaryMatrix[0].size();
  unordered_set<int> *used = new unordered_set<int>[n];
  for (int i=0; i<n; i++) used[i].clear();
 //Implementation through Breadth First Search
 // starting origin for my x and y coordinates
  int dx[] = {-1, 1, 0, 0};
  int dy[] = {0, 0, -1, 1};
  queue< pair<int, int> > q;

  for (int i=0; i<n; i++)
    for (int j=0; j<m; j++){

      if (!used[i].count(j) AND binaryMatrix[i][j]==1){

        ans++;

        q.push(make_pair(i, j));
        used[i].insert(j);
        while (!q.empty()){
          pair<int, int> pos = q.front();
          q.pop();

          for (int k=0; k<4; k++){
            int nx = pos.first+dx[k];
            int ny = pos.second+dy[k];
            if (nx<0 || nx>=n) continue;
            if (ny<0 || ny>=m) continue;
            if (used[nx].count(ny)) continue;
            if (binaryMatrix[nx][ny]!=1) continue;

            used[nx].insert(ny);
            q.push(make_pair(nx, ny));

          }

        }

      }

    }

  return ans;

}

int main() {
  return 0;
}

My code passes all of the test cases:

Test Case #1
Input: [[0]],Expected: 0,Actual: 0
Test Case #2
Input: [[1]],Expected: 1,Actual: 1
Test Case #3
Input: [[1,0,1,0]],Expected: 2,Actual: 2
Test Case #4
Input: [[1,0,1,0],[0,1,1,1],[0,0,1,0]],Expected: 2,Actual: 2
Test Case #5
Input: [[1,0,1,0],[0,1,1,1],[0,0,1,0],[1,1,0,0],[0,1,0,1]],Expected: 4,Actual: 4
Test Case #6
Input: [[0,1,0,1,0],[0,0,1,1,1],[1,0,0,1,0],[0,1,1,0,0],[1,0,1,0,1]],Expected: 6,Actual: 6
Test Case #7
Input: [[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]],Expected: 1,Actual: 1


texts: Creating chart from data fetched from backend

texts:
I have a javascript function written which I think is horrible for multiple reasons (which I have tried to mention in the comments in code below).
I want to give it a rewrite following some best practises in general.

  I am trying to solve following two problems.

  Do I need to include multiple try-catch statements in this code &
  break it into multiple smaller functions?
  If there is an exception or error thrown I can't show the exact
  error to the user as the error might be from the backend (consider wrong
  data format passed) so, I will just show "some error occurred alert"
  but while debugging I need to catch these errors and do not want to manually insert in every exception block. so how do I do this?

I considered this solution:
disable console.log in production code but againg my code will be filled wth console.log statements everywhere which I dont thiink is good idea.

I think this is a common problem and how is it usually handled?

The idea of this function is to fetch data from backend API & create charts and a table to display data. I have commented where execptions might occur.
But do I have to handle them individually or is there a better way to rewrite this function? Maybe breaking this down in to multiple individual functions?

  function getData() {

    var url = "/some-url/";

    $.getJSON(url, function(data) {
      //assign data key inside data to a local variable . what if data doesnt have data key??
      var bulkData = data.data;

      //assign data key inside table_data to a local variable . what if data doesnt have table_data key??
      var dayByDaymetrics = data.table_data;

      var commaSeperatedVals = JSON.parse(JSON.stringify(self.dayByDaymetrics));

      // do some computation
      for (index = j = 0, len = commaSeperatedVals.length; j < len; index = ++j) {
        i = commaSeperatedVals[index];
        for (idx = l = 0, len1 = i.length; l < len1; idx = ++l) {
          x = i[idx];
          formatedVal = self.formatNumberValues(x);
          commaSeperatedVals[index][idx] = formatedVal;
        }
      }

      var data_points = [];

      var ref = dayByDaymetrics;
      for (m = 0, len2 = ref.length; m < len2; m++) {
        i = ref[m];

      // what i[1] & i[0] are hardcoded , very difficult to read and understand.
        data_points.push(i[1]);
        self.xlabelsDayByDayChart.push(i[0]);
      }
      var chartLoadComplete = true;
      var dailyTableDataLoaded = true;

      series = [];

      // again there is hard-coding of value headers[1].
      series.push({
        'name': data.headers[1],
        'data': data_points
      });

      //call some external funciton to create the chart
      createChart("dayBydayChart", series, self.xlabelsDayByDayChart, 'column');

      brk = data["size"] / 2;
      self.first_row = [];
      self.second_row = [];
      self.headers = data["headers"];
      daily_table_headers = [];
      ref1 = data.headers;
      for (n = 0, len3 = ref1.length; n < len3; n++) {
        i = ref1[n];
        daily_table_headers.push({
          title: i
        });
      }

      //call some external function to create a table dynamically
      yy = $('#dailytable').DataTable({
        'bFilter': false,
        'bInfo': false,
        'bLengthChange': false,
        data: commaSeperatedVals,
        columns: daily_table_headers
      });

      return results;
    })


texts:
My application controller keeps growing with small helper methods that I use in both my controller and views, is it okay? or what do you recommend doing?

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  helper_method :resource_name, :resource, :devise_mapping, :resource_class, :is_admin?, :is_representative?, :is_shipper?,
    :is_agent?, :is_operation_completed?, :is_fcl_exw?, :is_fcl_exw_info_stage_completed?, :is_fcl_exw_info_requested?, :is_fcl_exw_info_confirmed?,
    :is_pricing_representative?, :is_fcl_exw_quotation_confirmed?

  # Roles detection helpers
  def is_admin?
    current_role == 'admin' ? true : false
  end

  def is_representative?
    current_role == 'representative' ? true : false
  end

  def is_shipper?
    current_role == 'shipper' ? true : false
  end

  def is_agent?
    current_role == 'agent' ? true : false
  end

  def is_pricing_representative?
    current_role == 'pricing_representative' ? true : false
  end

  # Devise helpers
  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def resource_class
    User
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end

  # Operation helpers
  def is_operation_completed?(operation_id)
    GeneralCargoInfo.find_by(operation_id: operation_id).nil? ? false : true
  end

  # FCL-EXW helpers
  def is_fcl_exw_info_stage_completed?(operation_id)
    FclExwCargoInfo.find_by(operation_id: operation_id).nil? ? false : true
  end

  def is_fcl_exw?(operation_id)
    Operation.find(operation_id).modality == 'FCL - EXW' ? true : false
  end

  def is_fcl_exw_info_requested?(operation_id)
    Operation.find(operation_id).fcl_exw_info_requested
  end

  def is_fcl_exw_info_confirmed?(operation_id)
    Operation.find(operation_id).fcl_exw_info_confirmed
  end

  def is_fcl_exw_quotation_confirmed?(operation_id)
    Operation.find(operation_id).fcl_exw_quotation_confirmed
  end

  private
    def current_role
        current_role = current_user.nil? ? 'Not logged in' : Role.find(current_user.role_id).name
    end

    def require_new_operation_permission
      check_permission('representative', 'agent')
    end

    def check_permission(*roles)
      unless roles.include? current_role
        flash[:alert] = "Access denied"
        redirect_back(fallback_location: authenticated_root_path)
      end
    end

end


texts:
I'm learning C++ and algorithms myself, and as training I had to write quicksort by myself.All feedback on coding style/clarity and concepts are welcomed!

int QuickSort(int *Array, int start, int end)//Recursive function that sorts array
{
    int Wall = start;//Variable that will hold pivot position before recursive calls and tracks indexes
    int Temp = 0;   //Variable used for swaping array members
    if (start < end)//Exit condition
    {
        for (int Index = start; Index < end; Index++)
        {
            if (Array[Index] <= Array[end])
            {
                Temp = Array[Wall];
                Array[Wall] = Array[Index];
                Array[Index] = Temp;
                Wall++;
            }
        }
        Temp = Array[end];
        Array[end] = Array[Wall];
        Array[Wall] = Temp;
    QuickSort(Array, start, --Wall);//Calling racursion for left of the pivot
    QuickSort(Array, ++Wall, end);//Calling recursion for right of the pivot
    }
 return 0;
}