texts:
I would like my form generator class to be reviewed. I want to know about the following topics:

Is this efficient?
Does this have any flaws?
Is this using the concepts in the proper way?
Are there any security issues?
Is my coding style correct?

<?php
class FormBuilder
{
    public function buildForm($method, $action, $name = null, array $fields)
    {
        $form  = "<form method=\"$method\" action=\"$action\"";
        $form .= empty($name) ? ">" : " name=\"$name\">\n";
        for($i = 0; $i < count($fields); $i++) {
            $form .= $this->buildField($fields[$i]['field'],
                                       $fields[$i]['type'],
                                       $fields[$i]['name'],
                                       empty($fields[$i]['placeholder']) ? '' : $fields[$i]['placeholder'],
                                       empty($fields[$i]['style']) ? '' : $fields[$i]['style'],
                                       empty($fields[$i]['options']) ? '' : $fields[$i]['options'],
                                       empty($fields[$i]['value']) ? '' : $friends[$i]['value']
            );
        }
        $form .= "</form>";
        return $form;
    }
    public function buildField($field, $type, $name, $placeholder = null, $style = null, $options = null, $value = null)
    {
        switch($field)
        {
            case 'input':
                $fieldHTML  = " <input type=\"$type\" name=\"$name\"";
                $fieldHTML .= empty($placeholder) ? "" : " placeholder=\"$placeholder\" ";
                $fieldHTML .= empty($style) ? "" : " style=\"$style\" ";
                $fieldHTML .= ">\n";
                break;
            case 'textbox':
                $fieldHTML  = " <textbox type=\"$type\" name=\"$name\"";
                $fieldHTML .= empty($placeholder) ? "" : " placeholder=\"$placeholder\" ";
                $fieldHTML .= empty($style) ? "" : " style=\"$style\" ";
                $fieldHTML .= "></textbox>\n";
                break;
            case 'submit':
                $fieldHTML  = " <input type=\"$type\" name=\"$name\"";
                $fieldHTML .= empty($style) ? "" : " style=\"$style\" ";
                $fieldHTML .= empty($value) ? "" : " value=\"$value\" ";
                $fieldHTML .= ">\n";
                break;
            default:
                $fieldHTML = "Failed to Build Field. Please make sure that you have set the field properties correctly.<br />";
                break;
        }
        return $fieldHTML;
    }
}

Example:

$formBuilder = new FormBuilder();

echo $formBuilder->buildForm('post',
                        '',
                        'some_name',
                        array(
                            array(
                                'field' => 'input',
                                'type'  => 'text',
                                'name'  => 'name',
                                'placeholder' => 'placeholder',
                                'style' => 'color: red;',
                                'options' => ''
                            ),
                            array(
                                'field' => 'submit',
                                'type'  => 'submit',
                                'name'  => 'send',
                                'placeholder' => '',
                                'style' => 'color: red;',
                                'options' => ''
                            )
                        )
);

?>


texts:
I am working on a program in which 10000 random non-repeating numbers are selectively sorted into ascending order"

import java.util.Random;

public class Sorting {
    public static void main (String[] args){
        //Here, we initiate an array with the integers
        //1 through 10,000 in order.
        Random rgen = new Random();
        int[] intArray = new int[10000];
        for (int i=0; i<10000; i++) {
            intArray[i] = i+1;
        }
        //Here, we randomize the positions.
        for (int i=0; i<10000; i++) {
            int randomPosition = rgen.nextInt(10000);
            int temp = intArray[i];
            intArray[i] = intArray[randomPosition];
            intArray[randomPosition] = temp;
        }
        //Here, we check for the maximum in the
        //unsorted section of the list.
        int max;
        for (int i=9999; i>=0; i--) {
            max = i;
            for (int j=i-1; j>=0; j--)
                if (intArray[j]>intArray[max]) {
                    max = j;
                }
            //Here, we swap the positions of the
            //maximum and the last value in the
            //unsorted section of the list.
            if (max != i) {
                int tmp = intArray[i];
                intArray[i] = intArray[max];
                intArray[max] = tmp;
            }
        }
        //Here, we output the result.
        for (int k=0; k<10000; k++) {
            System.out.println(intArray[k]);
        }
    }
}


texts:
I was trying to solve the Diwali Lights challenge on HackerRank.

  Problem Statement

  On the eve of Diwali, Hari is decorating his house with a serial light
  bulb set. The serial light bulb set has N bulbs placed sequentially on
  a string which is programmed to change patterns every second. If
  atleast one bulb in the set is on at any given instant of time, how
  many different patterns of light can the serial light bulb set
  produce?

  Note: Lighting two bulbs *-* is different from **-

  Input Format

  The first line contains the number of test cases T, T
  lines follow.  Each line contains an integer N, the number of bulbs in
  the serial light bulb set.

  Output Format

  Print the total number of patterns modulo 105

  Constraints

  1 <= T <= 1000
  0 < N < 104

  Sample Input

2
1
2

  Sample Output

1
3

The Code I had written is

#include<stdio.h>
# define MAX 10000 // assuming we need first 100 rows
unsigned long long triangle[MAX + 1][MAX + 1];

void makeTriangle() {
    int i, j;

    // inietialize the first row
    triangle[0][0] = 1; // C(0, 0) = 1

    for(i = 1; i < MAX; i++) {
        triangle[i][0] = 1; // C(i, 0) = 1
        for(j = 1; j <= i; j++) {
            triangle[i][j] = (triangle[i - 1][j - 1] + triangle[i - 1][j]) %100000;
        }
    }
}

unsigned long long C(int n, int r) {
    return triangle[n][r];
}
/*long long C(int N, int R)
    {
        if(R > N/2) R = N - R;
        int i;
        unsigned long long ans = 1;
        for(i=1; i<=R; i++)
        {
            ans *= N-R+i;
            ans /=i;
        }
    //  printf("N=>%d R=>%d ANS=>%lld\n", N, R, ans);
        return ans;
    }
 */
int main()
{
    makeTriangle();
    int T;
    scanf("%d", &T);
    while(T--)
    {
        int N;
        scanf("%d", &N);
        //  int copy = N;
        int i;
        unsigned long long int answer =0;
        switch (N)
        {
        case 1:
            printf("1\n");
            break;
        case 2:
            printf("3\n");
            break;
        default:
        {
            int limit = N%2==0? (N /2) -1:(N/2);    // Caluculate nCr till N/2 and multiply by 2
            int n_even =0;
            if( N%2 ==0)            // calculate nC(n/2) only when N is Even
            {
                n_even = C(N,N/2);
            }
            for(i=1;i<=limit;i++)
            {
                answer +=(2*C(N,i));
                answer %= 100000;
            }
            printf("%lld\n", (answer+ 1+ n_even) % 100000); //+1 is for nCn which is 1 always
            break;
        }
        }
    }
    return 0;
}

The answer is pretty straightforward as it can be obtained by the summation of nCr. But there were a few hiccups when I tried to implement the same.

In my first attempt I had used the commented function C(N,R) to calculate the nCr each and every time for all the test cases. But this approach gave me a TLE error. So I decided I'd compute the values for nCr for all the values in with the makeTriangle() function and then whenever I called this function it would return me the computed value by looking up the array in O(1) time.

However, even this approach gave me a Time limit Exceeded error. Hence I was wondering if there could be any other optimizations that I could do with this code or a possible different approach to this problem :)


texts:
Based on some code on internet, I implemented a dynamic array of structures in C.

I am really interested in some feedback on this.  Maybe there are some places where it can cause memory leaks or other pitfalls? (I am also concerned if there can be situation that I free a pointer twice in my case, and how to avoid that)

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    int ID;
    char * name;
} Student;

// array of structs
typedef struct
{
    Student *array;
    size_t used;
    size_t size;
} Array;

void initArray(Array *a, size_t initialSize)
{
    // Allocate initial space
    a->array = (Student *)malloc(initialSize * sizeof(Student));

    a->used = 0;           // no elements used
    a->size = initialSize; // available nr of elements

    // Initialize all values of the array to 0
    for(unsigned int i = 0; i<initialSize; i++)
    {
        memset(&a->array[i],0,sizeof(Student));
    }
}

// Add element to array
void insertArray(Array *a, Student element)
{
    if (a->used == a->size)
    {
        a->size *= 2;
        a->array = (Student *)realloc(a->array, a->size * sizeof(Student));
    }

    // Copy name
    a->array[a->used].name = (char*)malloc(strlen(element.name) + 1);
    strcpy(a->array[a->used].name, element.name);

    // Copy ID
    a->array[a->used].ID=element.ID;

    a->used++;
}

void freeArray(Array *a)
{
    // Free all name variables of each array element first
    for(int i=0; i<a->used; i++)
    {
        free(a->array[0].name);
        a->array[0].name=NULL;
    }

    // Now free the array
    free(a->array);
    a->array = NULL;

    a->used = 0;
    a->size = 0;
}

int main(int argc, const char * argv[])
{

    Array a;
    Student x,y,z;

    x.ID = 20;
    x.name=(char*)malloc(strlen("stud1") + 1);
    strcpy(x.name,"stud1");

    y.ID = 30;
    y.name=(char*)malloc(strlen("student2") + 1);
    strcpy(y.name,"student2");

    z.ID = 40;
    z.name=(char*)malloc(strlen("student3") + 1);
    strcpy(z.name,"student3");

    // Init array
    initArray(&a, 5);

    // Add elements
    insertArray(&a, x);
    insertArray(&a, y);
    insertArray(&a, z);

    // Print elements
    printf("%d\n", a.array[0].ID);
    printf("%s\n", a.array[0].name);
    printf("%d\n", a.array[1].ID);
    printf("%s\n", a.array[1].name);
    printf("%d\n", a.array[2].ID);
    printf("%s\n", a.array[2].name);
    printf("%d\n", a.array[3].ID);
    printf("%s\n", a.array[3].name);

    // Free array
    freeArray(&a);

    free(x.name);
    free(y.name);
    free(z.name);

    return 0;
}


texts: Proper cellForRowAtIndexPath cell return in Swift

texts:
So I have started creating a UITableView with multiple prototype cells. I currently have the below code setup, which works fine

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell: UITableViewCell?

    if indexPath.row == tableView.numberOfRowsInSection(0) - 1 {
        cell = tableView.dequeueReusableCellWithIdentifier("AddSetCell")
    } else {
        cell = tableView.dequeueReusableCellWithIdentifier("SetCell") as! SetTableViewCell
    }

    return cell!
}

I have learned to avoid using ! as much as possible when dealing with optionals. However, I also don't like creating an if let statement a thousand times. In theory, cell should never be nil because
my code only allows cell to be one of the identifiers above. However it still makes me nervous in terms of bad practice.

If I do var cell = UITableViewCell, I have to unwrap both of the calls to dequeueReusableCellWithIdentifier or XCode gets mad at me.

Which is the best approach for this case?


texts: Validating initial inputs then a joint validation test

texts:
The code works as intended but I believe it is very inefficient. The calculation of weights is simple, but I imagine this would be silly, for example, a 100 asset portfolio. The first problem is that my code returns to the beginning of the loop if the weight for y is entered incorrectly. Help with this would be amazing.
Secondly, as alluded to above, this is an inefficient approach. Someone entering 100 weights would not repeat this process. Any ideas where I could find some help for this approach would be great.
r_x=0.15
r_y=0.21
while True:
    try: w_x=float(input("Enter the weight of stock x in your portfolio: "))
    except ValueError:
        print("Please enter the weight using numbers")
        continue
    else:
        if w_x<0 or w_x>1: #seperating it instead of doing it altogether corrected this error for me
            print("Please enter the number as a decimal. Remember, your maximum investment is 100%.")
            continue
    try: w_y=float(input("Enter the weight of stock y in your portoflio: "))
    except ValueError:
        print("Please enter the weight using numbers")
    else:
        if w_y<0 or w_y>1:
            print("Please enter the numbers as a decimal. Remember, your maximum investment is 100%.")
            continue
        else:
            if w_x+w_y<0 or w_x+w_y>1:
                print("Remember, the total weight of the portfolio is 100%. The weights should add to 1.")
                continue
            else:
                r_p=r_x*w_x+r_y*w_y
                r_p=r_p*100
                print("The total return on your portoflio is %.2f"%r_p +"%")
                break


texts: Simulated race among three robots making random steps

texts:
At a job interview, I was asked to code the following algorithm:

Given are three robots which advance across a 1km lane at a different pace respectively. Each pace made by a robot is of a random distance.
All three robots stop once one of them is one pace away from reaching 1km. Once they stop, the robots' steps nearest to the middle of the lane are compared, and depending whose step throughout the journey was closest to the middle while exceeding it, a winner is declared. The winner robot's color is then printed out.

It took me a while to wrap my head around this quirky task, but I emerged with this solution:

var robot = function(color) {
    this.color = color;

    this.d1 = 0;
    this.robo1 = 0;
    this.a1 = [];
    while (this.robo1 < 1000 && this.d1 != -1) {

        // all robots begin at 0
        this.robo1 = this.robo1 + this.d1;

        // add starting point to array
        this.a1.push(this.robo1);

        // generate new deltas
        this.d1 = Math.floor(Math.random() * 100);

        // check if adding delta to new robos would exceed 1000
        // to determine whether the next iteration
        this.d1 = (this.d1 + this.robo1 > 1000) ? -1 : this.d1;

    }
    // log all arrays
    console.log(this.a1);

    // determine which element of a1 is closest to half of path
    console.log('smallest distance for a1:');
    this.smallestDistanceFromMiddle = 1000; // setting initial state

    this.cleanedA1 = [...this.a1];
    this.cleanedA1 = this.a1.filter(item => item > 500); // ###
    //console.log('cleanedA1 is \t' + this.cleanedA1);

    this.cleanedA1.forEach((index, item) => {
        this.iteratedValue = Math.abs(500 - this.cleanedA1[item]);
        this.smallestDistanceFromMiddle = this.iteratedValue < this.smallestDistanceFromMiddle ? this.iteratedValue : this.smallestDistanceFromMiddle;
        //console.log(iteratedValue);
    });
    console.log(this.smallestDistanceFromMiddle);
    return this.smallestDistanceFromMiddle;
}

let robot1 = new robot('red');
let robot2 = new robot('purple');
let robot3 = new robot('blue');

console.log("the robots' smallest distance to the middle is:");
console.log(robot1.color, robot1.smallestDistanceFromMiddle + '\n' +
    robot2.color, robot2.smallestDistanceFromMiddle + '\n' +
    robot3.color, robot3.smallestDistanceFromMiddle + '\n');

let nearestRobot = Math.min(robot1.smallestDistanceFromMiddle, robot2.smallestDistanceFromMiddle, robot3.smallestDistanceFromMiddle);

switch (nearestRobot) {
    case robot1.smallestDistanceFromMiddle:
        console.log(robot1.color, 'robot wins! \n');
        break;
    case robot2.smallestDistanceFromMiddle:
        console.log(robot2.color, 'robot wins! \n');
        break;
    case robot3.smallestDistanceFromMiddle:
        console.log(robot3.color, 'robot wins! \n');
        break;
    default:
        console.log('no robots defined');
}

Nevertheless, I feel like there is a more eloquent, easy on the eyes solution and I would very dearly appreciate improvement feedback.


texts: Rust: calculating mean, median, and mode for numbers from stdin

texts:
This quiz is on The Rust Programming Language online ebook.

  Given a list of integers, use a vector and return the mean (the average value), median (when sorted, the value in the middle position), and mode (the value that occurs most often; a hash map will be helpful here) of the list.

As a novice Rust programmer, I'd like get my code reviewed and learn more about programming Rust.

There are a couple of things I'd like to know:

getting input using io::stdin().read_line() is ok for this case,
if there's better looping (user-input) and quitting pattern,
handling user input errors with helpful error message (Your input is invalid. Please enter whitespace-separated integers.) then re-ask with prompt, instead of panicking,
whether type casting using as is commonly-used (ex: i32 -> f32),
implementation of get_median() and get_mode() can be simpler than now

Here's my code:

use std::collections::HashMap;
use std::io::{self, prelude::*};

fn main() {
    let stdin = io::stdin();

    'mainloop: loop {
        print!("Enter space-separated numbers (q for quit)> ");
        io::stdout().flush().expect("flush failed");

        let mut line = String::new();
        stdin.read_line(&mut line).expect("Failed to read line");

        if line == "q\n" {
            break 'mainloop;
        }

        // TODO: handling ParseIntError
        let nums: Vec<i32> = line
            .split_whitespace()
            .map(|s| s.parse::<i32>().unwrap())
            .collect();

        let mean = nums.iter().sum::<i32>() as f32 / nums.len() as f32;

        println!(
            "numbers: {:?}, mean: {}, median: {}, mode: {}",
            nums,
            mean,
            get_median(&nums),
            get_mode(&nums)
        );
    }
}

fn get_median(v: &Vec<i32>) -> f32 {
    if v.len() < 1 {
        return 0.0;
    }

    let mut vec = v.clone();
    vec.sort();
    if vec.len() % 2 == 1 {
        return *vec.get(vec.len() / 2).unwrap() as f32;
    }
    return (*vec.get(vec.len() / 2 - 1).unwrap() + *vec.get(vec.len() / 2).unwrap()) as f32 / 2.0;
}

fn get_mode(v: &Vec<i32>) -> i32 {
    let mut map = HashMap::new();
    for num in v {
        let count = map.entry(num).or_insert(0);
        *count += 1;
    }
    return **map.iter().max_by_key(|(_, v)| *v).unwrap().0;
}

This code is on GitHub also.
I found there are similar questions related to the same quiz on Code Review, but the implementations differ. So I think they're not duplicated question.


texts: Function for creating unique strings for urls

texts:
I wrote this function in order to create unique url's for my site. Using these urls, visitors could demo site functionality without having to create a login.  The function was intended to return a unique string of characters which could be added to a url like this:

http://www.mysite.com?temp_user=dd5vbrk4ax4v4o09l2bm

My function had the following criteria:

Every call must generate a unique string of alpha numeric characters.
Most important: Zero chance of string duplication.
It should be 20 characters long (secure, but not awkwardly long.)
Repeat calls should reflect a high degree of dissimilarity.
Character usage should appear as random as possible.

Here is my code

function url_code(){

  $letters =  "1234567890abcdefghijklmnopqrstuvwxyz";
  $microtime = microtime();
  $time_array = explode(' ', substr($microtime,2));
  $code = '';

  $time_array[0] = substr($time_array[0],0,6);
  $time_array[0] .= strrev($time_array[0]);
  $time_array[2] = strrev($time_array[1]);

  for($i = 0; $i <10; $i++){

    $num = ((int)$time_array[1][$i]);
    $num += ((int)$time_array[2][$i])*10;
    $num += ((int)$time_array[0][$i])*100;

    $mult   = (int)($num / 36);
    $mod    = $num - ($mult * 36);

    $code  .= $letters[$mult].$letters[$mod];

  }

  return $code;

}

Please let me know if there are any simple improvements I could make or if I missed any serious problems with string repetition.

One interesting note on character randomness: currently, characters generated by the $mult variable (the first, third, fifth, and other odd character in the code string) will never be t,u,v,w,x,y, or z. How can I fix this so that [t-z] are also used?

Possible fix (all characters will be used. However, [8-9a-s] are twice as likely to appear as the other characters, [0-7t-z]):

$mult   = (int)($num / 36);
$mod    = $num - ($mult * 36);
if($mult < 9 && mt_rand(0,1)){$mult += 27;}

$code  .= $letters[$mult].$letters[$mod];

Note, Scalability issue found:  If this function is run on more than one server, there is a tiny chance that two users could send a request at exactly the same time and get a duplicated code.


texts: Counting the number of days worked for all commiters to a git repo

texts:
I wrote this script to collect evidence of the number of days worked for the purpose of claiming some government tax credits.

I'm looking for some ways to clean it up. I'm especially wondering if there is a cleaner way to uniqueify a list than list(set(my_list) and maybe a better way to do:

d = dict(zip(commiters, [0 for x in xrange(len(commiters))]))

import os
from pprint import pprint

lines = os.popen('git log --all').read().split('\n')

author_lines = filter(lambda str: str.startswith('Author'), lines)
date_lines = filter(lambda str: str.startswith('Date'), lines)
author_lines = map(lambda str: str[8:], author_lines)
date_lines = map(lambda str: str[8:18].strip(), date_lines)

lines = zip(author_lines, date_lines)

lines = sorted(list(set(lines)), key = lambda tup: tup[0])

commiters = list(set(map(lambda tup: tup[0], lines)))

d = dict(zip(commiters, [0 for x in xrange(len(commiters))]))

for item in lines:
    d[item[0]] += 1

pprint(d)


texts: Simple Todo CLI APP in Python with SQLalchemy

texts:
I wanted to ask you a favor.
I am recruiting for the position of Junior Python Developer (my first try in IT) and I got a task to create a script to manage the task list.
https://github.com/Lok3rs/Todo-CLI
Could you please give me some feedback about that script? I will be very grateful!
Thanks in advance, keep your fingers crossed!

init.py

import os
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.ddl import CreateTable
from sqlalchemy_utils import database_exists, create_database
from sqlalchemy.exc import OperationalError

from tasks.model.model import Task
from tasks.model.validators import Validator
from tasks.view.terminal import View

engine = create_engine("mysql+mysqldb://{}:{}@{}/{}".format(
    os.environ.get("MYSQL_USERNAME"),
    os.environ.get("MYSQL_PASSWORD"),
    os.environ.get("MYSQL_HOST"),
    os.environ.get("MYSQL_DB")
))

meta = MetaData()
meta.bind = engine
Session = sessionmaker(bind=engine)
session = Session()

view = View()
validator = Validator()

tasks_table = Task.__table__

try:
    if not database_exists(engine.url):
        create_database(engine.url)
        meta.create_all()
        engine.connect().execute(CreateTable(tasks_table))
        print(f"Database named {os.environ.get('MYSQL_DB')} created successfully.")
    else:
        engine.connect()
except OperationalError as err:
    print(err)


texts: Class with methods to retrieve data with Linq to sql

texts:
I think here is something wrong with code. I use a class with methods to get tenants from DB:

    public List<CrmTenant> GetAllTenants()
    {
        List<CrmTenant> tenantsList = new List<CrmTenant>();

        try
        {
            var crmTenants =
                 from tenant in context.CrmTenant
                 select tenant;

            if (crmTenants != null)
            {
                foreach (var tenant in crmTenants)
                {
                    tenantsList.Add(tenant);
                }
            }

            return tenantsList;
        }
        catch (Exception ex)
        {
            this.logger.Write("Failed to get all tenants from database.", "Exceptions", TraceEventType.Error, ex);
            return null;
        }
    }

    /// <summary>
    /// Gets Tenant by name.
    /// </summary>
    /// <returns></returns>
    public CrmTenant GetTenantByName(string tenantName)
    {
        CrmTenant crmTenant = null;

        try
        {
            crmTenant =
                 (from customerCrm in context.CrmTenant
                  where customerCrm.TenantName == tenantName
                  select customerCrm).Single();
            return crmTenant;
        }
        catch (Exception ex)
        {
            this.logger.Write(String.Format("Failed to get tenant '{0}' from database.", tenantName), "Exceptions", TraceEventType.Error, ex);
            return null;
        }
    }

    /// <summary>
    /// Gets tenant by Username.
    /// </summary>
    /// <returns></returns>
    public CrmTenant GetTenantByUserName(string userName)
    {
        CrmTenant crmTenant = null;

        try
        {
            crmTenant =
                 (from customerCrm in context.CrmTenant
                  where customerCrm.Username == userName
                  select customerCrm).Single();
            return crmTenant;
        }
        catch (Exception ex)
        {
            this.logger.Write(String.Format("Failed to get tenant by username '{0}' from database.", userName), "Exceptions", TraceEventType.Error, ex);
            return null;
        }
    }

Here is call for methods

// get tenant
var crmTenant = CrmServiceHandlerFactory.GetInstance().Resolve<TenantManager>().GetTenantByUserName(userName);

I am new in programming, could you please help me to improve this code


texts:
I have a bunch of functions that return strings based upon score ranges. Then I have another function that sums everything up and assigns a numeric weight.

@property
def risk_status(self):
    """ This function assigns numeric weight to risks. It returns an over all integer score. """

    # Build a string of risks, ie "High Risk@At Risk@@Extreme Risk"
    raw_string_of_risks = self.si_risk + '@' + self.aggbs_risk + '@' + self.cfimb_risk + '@' + self.cfiab_risk + '@' + self.cei_risk

    # Build a list ["High Risk", "At Risk", "Extreme Risk"]
    risks = raw_string_of_risks.split('@')

    # Formula for over all risk status. ["High Risk", "At Risk", "Extreme Risk"] => 2+1+3 = 6
    status = risks.count("At Risk")*1 + risks.count("High Risk")*2 + risks.count("Extreme Risk")*3

    return status

I'm afraid with a gazillion records this property might slow things down. It will never get a string longer than 65 characters to parse, but will doing this over and over again really slow things down?


texts:
I'm trying to define a new window for use inside a Classic Titanium application for iOS. For the window to work properly, some preprocessing is required. This preprocessing includes the creation of the UI components -- such as labels, tables, and buttons --, the assembling of this components, and the addition of event listeners. However, I don't think this is the best way to do it. Any insight?

function LandingPage() {
    this.prepareForExecution();
}

LandingPage.prototype = {
    constructor: LandingPage,

    _proxy: Ti.UI.createWindow({
        title: "To Do List",
        backgroundColor: "#FFFFFF",
        navBarHidden: false,
        orientationModes: [
            Ti.UI.PORTRAIT,
            Ti.UI.LANDSCAPE_RIGHT,
            Ti.UI.LANDSCAPE_LEFT
        ]
    }),

    get proxy() {
        return this._proxy;
    },

    prepareForExecution: function () {
        this.createUIcomponents();
        this.buildUserInterface();
        this.addEventListeners();
        this.populateTaskTable();
    },

    ...
};


texts:
I'm looking for improvement / advice / reviews on how I can improve this code. I feel like there is a better way or more efficient way of doing this and I am over looking it.

The Plugin I made is very simple:

It stores a list of Postcodes that the admin inputs into a textarea - 1 Per Line.
Plugin creates a text input on the front end that allows their customers to search if their postcode is in the list with Ajax.

The Plugin has a few options to allow the admin to customize the look and functionality of the plugin. Below is the function that takes the postcode and searches the list:

function sapc_ajax_check() {
    $checker_defaults = get_option( 'sapc_checker_settings_options' );
    $found = 0; $msg = ''; $passed = 0;
    if (!empty( $_POST ) && isset($_POST['action']) && strcmp($_POST['action'], 'sapc_ajax_check') === 0) {
            if(isset($_POST['pc'])){
                if(isset($_POST['verify-int']) && $_POST['verify-int'] == 'on'){
                    if(is_numeric($_POST['pc']) && is_int((int)$_POST['pc'])){
                        $passed = 1;
                    }
                }elseif($checker_defaults['verify-int'] == 'on'){
                    $passed = 1;
                }else{$passed = 1;}
                if($passed === 1){
                    $temp_l = $checker_defaults['postcodes'];
                    $postcode_l = explode(PHP_EOL, $temp_l);
                    if(is_array($postcode_l) && !empty($postcode_l)){
                        foreach($postcode_l as $i=>$temp_p){
                            if( strpos($temp_p, ':') !== false) {
                                $v = explode(':', $temp_p);
                                if(strcmp($v[0], $_POST['pc']) === 0){
                                    $found = 1;
                                    $msg .= $v[1] .', ';
                                }
                            }else{
                                if(strcmp($temp_p, $_POST['pc']) === 0){
                                    $found = 1;
                                    $msg .= $temp_p .', ';
                                }
                            }
                        }
                        if($msg != ''){
                            $msg = substr($msg, 0, strlen($msg) - 2);
                        }
                    }else{$msg ='Error: Try Again';}
                }else{$msg ='Error: Invalid Postcode';}
            }else{$msg ='Error: No Postcode';}
    }else{$msg = 'Error: No Data';}

    if($found == 0){
        echo json_encode(array('Error', 'Postcode Not Found'), JSON_FORCE_OBJECT);
    }else{
       echo json_encode(array('Success', $msg), JSON_FORCE_OBJECT);
    }
    die();
}

There are 2 sets of variables.

First set is the default settings from the admin options page, this helps with placing widgets and allows admins to set their own defaults. Postcodes can only be set here.
Second set is from the widget instance which allows admins to personalize each widget if need be.

I'll explain some of the variables.

$_POST['pc'] = Postcode from User

$_POST['verify-int'] = Option to check if postcode is all integers - Passed from Postcode Widget

$checker_defaults['postcodes'] = list of postcodes

Postcode List accepts the following formats:

Postcode:Surbubr
Postcode

(1 per line)

What can I do to make this function more efficient and more cleaner? If you need anything else please let me know I think I've covered everything.


texts:
I wrote this blog post, but received some feedback that there are better ways to handle the situation. I'd like to get some more opinions. Here is the topic:

  Given a list of letters, I want to find the most commonly seen one.

# create the list of letters
my_list = ['b', 'b', 'b', 'c', 'a', 'b']

# simple sentence to make all more "user friendly"
sentence = '\nLetter which repeat the most is: '

# 3 lists declared globally which will store our values
a_list = []
b_list = []
c_list = []

# for loop which control the letters in the list and append them to the respective list
for v in my_list:
    if v == 'a':
        a_list.append(v)

    elif v == 'b':
        b_list.append(v)

    elif v == 'c':
        c_list.append(v)

# create a variable which store the name of the letter and how many times appear in the main list
A = a_list[0], len(a_list)
B = b_list[0], len(b_list)
C = c_list[0], len(c_list)

# variable which store length values
total_list = A[1], B[1], C[1]

# find the max value
largest = max(total_list)

# in this loop we are going to compare each value from total_list to the largest one
for i, val in enumerate(total_list):
    if total_list[i] == largest:
        x = total_list[i]  # assign to "x" this value

        # do a check for all the values
        # if the condition is satisfied, then print the sentence and letter (to uppercase)
        if x == A[1]:
            print(sentence + str(A[0]).upper())
        elif x == B[1]:
            print(sentence + str(B[0]).upper())
        elif x == C[1]:
            print(sentence + str(C[0]).upper())

I've heard that collections.Counter could be used for this, but I'm not sure that the output will be the same. I might be able to use it to replace some of my code above, but will I end up with the same result?


texts: The block should return the user's current_active_role

texts:
def current_active_role
    user_roles.each do |r|
      if r.is_active_role
        return r
      end
    end
    return nil
  end

The block above returns whatever the user's currently active role is.  There are User, UserRoles (lookup table), and Roles tables.

I'm looking for a more concise way to say "go through all their individual roles, find the active one and return it, or implicitly return nil if none of them are the active role."


texts: Checking if numbers in array are sorted or reverse sorted

texts:
I would like to determine is an array of numbers, is always increasing (for all x, x+1 >= x) or always decreasing (for all x, x+1 =< x). If so return true. Another way to state the problem is, return true if the array is sorted or reverse sorted. Here is the code:

public static boolean isAlwaysIncreasingOrDecreasing(int[] arr) {
        //check if decreasing
        int previous = arr[0];
        boolean decreasing = true;
        for(int i = 1; i < arr.length; i++) {
            if(previous < arr[i]) {
                decreasing = false;
                break;
            }
            previous = arr[i];
        }

        //check if increasing
        int previous = arr[0];
        boolean increasing = true;
        for(int i = 1; i < arr.length; i++) {
            if(previous > arr[i]) {
                increasing = false;
                break;
            }
            previous = arr[i];
        }

        //return true if always increasing or decreasing
        if(decreasing || increasing) {
            return false;
        }

        return true;
}

Any tips? Obviously duplicate values are allowed, so inputs such as 1,2,3,3,3,3....3,4,2,5,6 would be tricky.

I ask mainly out of curiosity, as the above solution would take at most 2 iterations through the array and I don't think it is possible to take less than 1, so it's not too bad :)


texts: Using Pexpect for communication between multiple programs via I/O

texts:
I have a Python script that runs three compiled programs and makes them communicate via standard I/O. This is my first time using pexpect. My program runs very slowly. Is there anything that I can do to speed up the program? If not, I can try to do it with C/C++ pipe/fork.

import pexpect
import os

Checker = pexpect.spawn("./checker") # a turn based game
Player = [0,1]
Player[1] = pexpect.spawn("./player1") # same game with computer player
Player[0] = pexpect.spawn("./player2") # same game with computer player

# tell each player wether it is 1st or 2nd player
Player[1].sendline("1") #
Player[1].expect("\n")  # delete input from before
Player[0].sendline("2")
Player[0].expect("\n")  # delete input from before

player = 1
while True:

    Player[player].expect("\n") # wait for current player's move(a line)
    move = Player[player].before.strip() # read current player's move
    print move

    if not Checker.isalive(): # this does not run in usual
        print "endgame checker died"
        break
    Checker.sendline(move)
    Checker.expect("\n") # delete input from before
    Checker.expect("\n") # wait checker's response
    check = Checker.before.strip() # read the response
    if check != "": # checker will send an empty line if move is valid and game didn't end
        print "endgame   ", check # otherwise response is other player's number
        Player[0].kill(0) # kill all
        Player[1].kill(0)
        Checker.kill(0)
        break

    player = (player+1) %2 # change current player
    if not Player[player].isalive(): # this does not run in usual
        print "endgame" + player + "died"
        break

    Player[player].sendline(move)
    Player[player].expect("\n")  # delete input from before


texts:
This is an app wherein you have to find the word that represents the image. It's the same concept as the course app but I did this one myself.

How can I improve this code (put more commentary, put more space, you can add that, etc.)? I finished the second part of app development with Swift. Please explain why I should do the modification. Commentary are in French but I can translate them.

Game Struct

import Foundation
import UIKit
struct Game
{
    var correctWord: String
    var image: UIImage
    var guessedLetter: [Character]
    // création du bon mot par le joueur
    var formatedWord: String
    {
        var formateWord = ""
        let word = correctWord.lowercased()

        for letter in word
        {
            if guessedLetter.contains(letter)
            {
                formateWord += "\(letter)"
            }
            else
            {
                formateWord += "_"
            }
        }

        return formateWord
    }
    // Quand le joueur
    mutating func playerGuessed(_ letter: Character)
    {
        guessedLetter.append(letter)
    }
}

View Controller

import UIKit
//liste de mot et image
var imageAndWord = ["Maison": #imageLiteral(resourceName: "image 1"),"Bateau": #imageLiteral(resourceName: "image2") ,"Train": #imageLiteral(resourceName: "image 3"),"Vase": #imageLiteral(resourceName: "image 4")]
//récupération des clées
var theKey = Array(imageAndWord.keys)
// Nombre de clé
let totalKey = theKey.count + 1
//récupération des valeurs
var theValue = Array(imageAndWord.values)
// comptage d'image trouvé
var imageFindNumber = 0
class ViewController: UIViewController {
    // initialisation des vues
    @IBOutlet var lettersButtons: [UIButton]!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var wordLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!
    //Quand une lettre est pressée
    @IBAction func lettersButtonsPressed(_ sender: UIButton)
    {
        sender.isEnabled = false
        let letter = sender.title(for: .normal)!
        let lowCasedLetter = Character(letter.lowercased())
        currentGame.playerGuessed(lowCasedLetter)
        if currentGame.correctWord == currentGame.formatedWord
        {
            newRound()

        }
        updateUI()
    }
    // Actualisation de l'interface
    func updateUI()
    {
        let word = currentGame.formatedWord.map{String($0)}
        let spacingWord = word.joined(separator: " ")
        wordLabel.text = spacingWord
        imageView.image = currentGame.image
        scoreLabel.text = "Image: \(imageFindNumber)/\(totalKey)"

    }
    var currentGame: Game!
    // Initialisation de l'image et du mot
    func newRound()
    {
        if !theKey.isEmpty && !theValue.isEmpty
        {
        enableOrNotButton(true)
        let word = theKey.removeFirst().lowercased()
        let value = theValue.removeFirst()
        currentGame = Game(correctWord:word, image:value, guessedLetter: [])
        imageFindNumber += 1
        updateUI()
        }
        else
        {
            enableOrNotButton(false)
        }
    }
    //Activation ou désactivation de tout les bouttons
    func enableOrNotButton(_ enable: Bool)
    {
            for button in lettersButtons
            {
                button.isEnabled = enable
            }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        newRound()
        print(currentGame.correctWord)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


texts:
I'm getting address (physical address, not digital) input that's obfuscated, and looks like the following:

  The plaintext version:

'39 Jerrabomberra Ave. Narrabundah Canberra 2604 Australia'

  The obfuscated version:

['39 Jerrabomberra Ave., Narrabundah', 'Canberra', ' ', '2604', ', ', 'Australia', '39 Jerrabomberra Ave., Narrabundah', 'Canberra 2604, ', 'Australia']

Usually the obfuscation is simple duplication and rearranging, which my script catches, however there are a few edge cases that are missed, which I'm working on catching.

However, my solution feels like it could be simplified.

The logic follows this order:

Join the array into one long string with a space as the 'glue' character.
Use re.sub to find all commas and remove them.
Split by space
Add each non-empty component to the components array if it is not already in there.
Join the components together.

import re

...

address = fooGetAddress(foo[bar]) #returns an array
address_components = []
for component in re.sub(",", "", " ".join(address)).split(" "):
    if component not in address_components and component is not "":
        address_components.append(component)
address = " ".join(address_components)


texts: Serialize/deserialize a vector using insertion/extraction operators

texts:
I've never serialized a structure to a file before in C++, so I'm looking for critique on my first try at it.

My main concerns are:

It uses the streams space-delimited behavior. If a vector<char> that contains a space is serialized, it skips the space, which results in an exception. From my tests, it works fine for non-whitespace elements, but I'd like any suggestions on how I could circumvent this problem.
Should I be throwing an exception on bad reads? Am I throwing the right exception?
Should I be clearing the vector before adding to it while reading?
The string formatting for the runtime_errors is ugly. I didn't want to introduce a stringstream just to format the message.

#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>

template <class T>
std::fstream& operator<<(std::fstream& fs, std::vector<T>& v) {
    //Write size of vector
    fs << v.size() << ' ';

    //Write contents
    for (T& t : v) {
        fs << t << ' ';
    }

    return fs;
}

template <class T>
std::fstream& operator>>(std::fstream& fs, std::vector<T>& v) {
    v.clear();

    unsigned int vSize;

    fs >> vSize;

    if (!fs.good()) {
        throw std::runtime_error(
            std::string("Problem reading serialized vector size: ").append(std::to_string(vSize))
        );
    }

    for (unsigned int i = 0; i < vSize; i++) {
        T readT;
        fs >> readT;

        if (!fs.good()) {
            unsigned long errPos = fs.tellg();
            throw std::runtime_error(
                std::string("Problem reading serialized vector content at ").append(std::to_string(errPos))
            );
        }

        v.push_back(readT);

    }
    return fs;
}


texts:
Here's a program I wrote to convert numbers into English words using Haskell.

import Data.Char
import Data.List

type WordNum = String

ones :: (Integral a, Show a) => a -> WordNum
ones 1 = "one"
ones 2 = "two"
ones 3 = "three"
ones 4 = "four"
ones 5 = "five"
ones 6 = "six"
ones 7 = "seven"
ones 8 = "eight"
ones 9 = "nine"
ones n = error (show n ++ " is not a one-digit value")

teens :: (Integral a, Show a) => a -> WordNum
teens 10 = "ten"
teens 11 = "eleven"
teens 12 = "twelve"
teens 13 = "thirteen"
teens 14 = "fourteen"
teens 15 = "fifteen"
teens 16 = "sixteen"
teens 17 = "seventeen"
teens 18 = "eighteen"
teens 19 = "nineteen"
teens n  = error (show n ++ " is not a teen")

tens :: (Integral a, Show a) => a -> WordNum
tens 1 = "ten"
tens 2 = "twenty"
tens 3 = "thirty"
tens 4 = "forty"
tens 5 = "fifty"
tens 6 = "sixty"
tens 7 = "seventy"
tens 8 = "eighty"
tens 9 = "ninety"
tens n  = error (show n ++ " is not a tens place value")

groups :: [WordNum]
groups = ["", " thousand", " million", " billion", " trillion"]

groupToWord :: (Integral a, Show a) => a -> String
groupToWord n
    | n == 0    = ""
    | n < 10    = ones n
    | n < 20    = teens n
    | n < 100   = tens (n `div` 10) ++ ' ' : (groupToWord $ n `mod` 10)
    | n < 1000  = ones (n `div` 100) ++ " hundred " ++ (groupToWord $ n `mod` 100)
    | otherwise = error (show n ++ " is not a 3-digit group")

-- Splits a number into groups in reverse order
splitNum :: (Integral a, Show a) => a -> [a]
splitNum n
    | n <= 999  = [n]
    | otherwise = (n `mod` 1000) : splitNum (n `div` 1000)

numToWord :: (Integral a, Show a) => a -> String
numToWord n
    | n == 0     = "zero"
    | n >= 10^15 = error "Doesn't support numbers bigger than trillions"
    | otherwise  = concat $ intersperse ", " [w ++ g | (w,g) <- reverse (zip wordGroups groups)]
    where
        wordGroups = toWordGroups $ splitNum n

        toWordGroups :: (Integral a, Show a) => [a] -> [WordNum]
        toWordGroups (g:gs) = groupToWord g : toWordGroups gs
        toWordGroups _ = []

It seems like there's a lot of redundancy, and I'm also not very happy with how I had to join the lists. Also, is there a way to do more consing and less appending? I was hoping to cons the groups back together after they were made words so I wouldn't have to reverse the zipped list afterward. Also, as always, I'd really appreciate general comments on improvements to style and best practice.


texts: Reinventing the basic calculator functions

texts:
I decided to reinvent the basic calculator functions using only:

the set of positive integers
greater than, less than, and equality properties
increment and decrement

(in other words, the counting on fingers method)

def is_positive_int(x):
    if type(x) == int and x >= 0:
        return True
    else:
        return False

def add(x,y):
    if is_positive_int(x) and is_positive_int(y):
        for i in range(y):
            x += 1
        return x
    else:
        return False

def multiply(x,y):
    if is_positive_int(y) and is_positive_int(y):
        m = 0
        for i in range(y):
            m = add(m,x)
        return m
    else:
        return False

def power(x,y):
    """ x to the y power """
    if is_positive_int(x) and is_positive_int(y):
        p = 1
        for i in range(y):
            p = multiply(p,x)
        return p
    else:
        return False

def subtract(x,y):
    """ x - y """
    if is_positive_int(x) and is_positive_int(y) and x > y:
        for i in range(y):
            x -= 1
        return x
    else:
        return False

def divide(x,y):
    """ x / y """
    if is_positive_int(x) and is_positive_int(y):
        floor = 0
        remainder = 0
        for i in range(x):
            remainder += 1
            if remainder == y:
                floor += 1
                remainder = 0
        return {'floor':floor, 'modulus':remainder}
    else:
        return False

def floor(x,y):
    """ a // b"""
    return divide(x,y)['floor']

def modulus(x,y):
    """ x % y"""
    return divide(x,y)['modulus']


texts: Implementation of the Access version DBLookup() in VB6

texts:
I've tried to implement the access function DBLookup() in VB6 for a project I'm doing. Does anyone have comments on how well done it is and what could be improved? Take note that the Database connection object cn is only valid for a single query, and it's being initialized whenever you call the other public function, dbConn.

   Public Function cDLookup(TargetField As String, TargetTable As String, cTCondition As String) As String
    'Eigene Implementation von DLookup
    Dim Result As String
    Dim rs As New ADODB.Recordset
    Dim SQL As String
    On Error GoTo Fehlerbehandlung

'Zusammenbauen der Query
SQL = "SELECT " & TargetField & " FROM " & TargetTable & " WHERE " & cTCondition

Call dbConn
'Initiate Database connection object cn

rs.Open SQL, cn
If (rs.RecordCount = 1) Then
Result = cleanString(rs.GetString)
Debug.Print ("[DLOOKUP] Erfolgreich Einen Datensatz gefunden und konvertiert. Output: " & Result)

ElseIf (rs.RecordCount > 1) Then
Result = "#ErrRC"
Debug.Print ("[DLOOKUP] Es wurden " & CStr(rs.RecordCount) & " Datensätze statt einem festgestellt. Dies ist nicht erlaubt")

Else
Result = "#ErrGen"
Debug.Print ("[DLOOKUP] Es ist ein Fehler in der Abfrage aufgetreten")
End If
rs.Close

cDLookup = Result
Exit Function
Fehlerbehandlung:
Debug.Print ("[DLOOKUP] Fehler im Ausführen der Prozedur cDLookup()]")
cDLookup = "#Fehler"
Exit Function
End Function


texts:
I am trying to develop a program which will solve any permutation-based puzzle such as 15 puzzle or Rubik's cube, so there will be a follow-up question about class that actually solves puzzle. Here I ask about the class which is essential to this task: Permutation class.

class Permutation(object):
    @staticmethod
    def get_letter_id(num):
        """
        Returns an identity permutation of first :num: number of
        uppercase ASCII letters.
        """
        letters = string.ascii_uppercase[:num]

        return Permutation(tuple(zip(letters, letters)), "Id" + str(num))

    def __init__(self, perm, label=""):
        """
        :param perm: List of tuples of type (A, B), which shows that in given sequence of symbols
                        symbol A will be replaced by symbol B
        :param label: Label for better (or worse) representation.
        """
        top_symbols = [p[0] for p in perm]
        bottom_symbols = [p[1] for p in perm]

        top_symbols = set(top_symbols)
        bottom_symbols = set(bottom_symbols)

        if top_symbols != bottom_symbols:
            raise Exception("Incorrect Permutation")

        self._perm = list(perm)
        self._perm.sort(key=lambda x: x[0])
        self._label = str(label)

    @property
    def inverse(self):
        p = [(p[1], p[0]) for p in self._perm]
        p.sort(key=lambda x: x[0])
        return Permutation(p, "Inverse({0})".format(self._label))

    @property
    def parity(self):
        return self._inversions % 2

    @property
    def symbols(self):
        return sorted([i for i, j in self._perm])

    @property
    def _inversions(self):
        res = 0
        top = [i for i, j in self._perm]
        bottom = [j for i, j in self._perm]
        for i in range(len(top)):
            for j in range(i, len(top)):
                if bottom[i] > bottom[j]:
                    res += 1
        return res

    def print_carrier(self):
        [print("{0} -> {1}".format(mutation[0], mutation[1])) for mutation in self._perm if mutation[0] != mutation[1]]

    def _find_symbol(self, symbol):
        for i in range(len(self._perm)):
            if self._perm[i][0] == symbol:
                return i
        raise Exception("Can't find given symbol in permutation.")

    def __call__(self, sequence):
        """
        Applies this permutation to the given sequence of symbols.
        For performance reasons this permutation assumed applicable to given sequence.
        """
        return tuple([self._perm[self._find_symbol(symbol)][1] for symbol in sequence])

    def __eq__(self, permutation):
        if type(permutation) != Permutation:
            return False
        condition1 = self.symbols == permutation.symbols
        condition2 = self.__call__(self.symbols) == permutation(self.symbols)
        return condition1 and condition2

    def __mul__(self, permutation):
        first = [mutation[0] for mutation in self._perm]
        second = self.__call__(permutation(first))
        return Permutation(tuple(zip(first, second)), str(self) + " * " + str(permutation))

    def __repr__(self):
        return self._label

Performance should not be ignored too.


texts:
import java.io.IOException;
import java.util.Scanner;

public class Main {

    private static int random = (int) (Math.random() * 100 + 1);
    private static int data;
    private static int go;
    private static int attempt = 10;

    public static void Start() throws IOException {

        Scanner scanInput = new Scanner(System.in);
        data = scanInput.nextInt();

        if (data > 100) {
            System.out.println("Only Enter Numbers Between 0-100");
            Start();
        } else if (data == random) {
            System.out.println("Wow, you guessed it!!");
            scanInput.close();
            System.exit(0);
        } else if (data < random) {
            go += 1;
            if (go == attempt) {
                System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
                scanInput.close();
                System.exit(0);
            }
            System.out.println("Higher");
            Start();
        } else if (data > random) {
            go += 1;
            if (go == attempt) {
                System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
                scanInput.close();
                System.exit(0);
            }
            System.out.println("Lower");
            Start();
        }
    }

    public static void main(String[] args) throws IOException {
        System.out.println("Guess A Number Between 0-100 Within " + attempt + " Goes");
        Start();
    }

}


texts: Using UnitOfWork/Repository pattern in static class/methods

texts:
I know using a UnitOfWork/Repository pattern in a normal class should work fine without any issues but how about using them in a static class/methods (I mean using a private static IUnitOfWork instance, refer CustomerService class). Will this work fine in multiple user scenario without overlapping with other request (I am using asp.net)?

Can anyone please tell me whether the below code looks fine or I will get any issues (overlapping db issues) going forward because of the static IUnitOfWork instance? Also, please advice me if there is any other better way to do this.

public interface IDataRepository<T> where T : class
{
    IQueryable<T> Find(Expression<Func<T, bool>> predicate);
    IQueryable<T> GetAll();
    T GetById(Guid id);
    T GetById(int id);
    void Add(T entity);
    void Update(T entity);
    void Remove(T entity);
}

public class DataRepository<T> : IDataRepository<T> where T : class
{

}

public interface IUnitOfWork
{
    IDataRepository<Customer> CustomerRepository { get; }
    IDataRepository<Product> ProductRepository { get; }

    void SaveChanges();
}

public class UnitOfWork : IUnitOfWork
{
    private readonly SomeContext _context;

    private IDataRepository<Customer> _customerRepository { get; set; }
    private IDataRepository<Product> _productRepository { get; set; }

    public UnitOfWork()
    {
        _context = new SomeContext();
    }

    public IDataRepository<Customer> CustomerRepository
    {
        get
        {
            if (_customerRepository == null)
            {
                _customerRepository = new DataRepository<Customer>(_context);
            }
            return _customerRepository;
        }
    }

    public IDataRepository<Product> CustomerRepository
    {
        get
        {
            if (_productRepository  == null)
            {
                _productRepository = new DataRepository<Product>(_context);
            }
            return _productRepository;
        }
    }
}

public class CustomerService
{
    private static IUnitOfWork _unitOfWork = new UnitOfWork();

    public static List<Customer> GetCustomers()
    {
        _unitOfWork.CustomerRepository.Find(t => t.ID == 123).ToList();
    }

    public static bool IsCustomerExist()
    {
        return (_unitOfWork.CustomerRepository.Find(t => t.ID == 123).Count() > 0);
    }

    public static bool UpdateCustomer(Customer customer)
    {
        .....
        _unitOfWork.SaveChanges();
    }
}


texts:
This code works nicely for my purposes, but I would like to improve it exponentially.

What are some steps I can take?  I'm interested in optimization, refactoring, and clean-code.

  def do_GET(self):
    qs = {}
    path = self.path
    print path
    if path.endswith('robots.txt'):
      self.send_response(500)
      self.send_header('Connection', 'close')
      return
    if '?' in path:
      path, tmp = path.split('?', 1)
      qs = urlparse.parse_qs(tmp)
      print path, qs
    if 'youtube' in path:
     ID = qs.get('vID')
     LTV = qs.get('channelID')
     EMAIL = qs.get('uEmail')
     TIME = qs.get('Time')
     userID = qs.get('uID')
     URL = qs.get('contentUrl')
     channelID = str(LTV)[2:-2]
     print channelID
     uEmail = str(EMAIL)[2:-2]
     print uEmail
     ytID = str(ID)[2:-2]
     print ytID
     ytURL = str("https://www.youtube.com/tv#/watch?v=%s" % ytID)
     print ytURL
     uTime = str(TIME)[2:-2]
     print uTime
     uID = str(userID)[2:-2]
     print uID
     contentUrl = str(URL)[2:-2]
     print contentUrl
     if sys.platform == "darwin":
      subprocess.Popen('./killltv', shell=True)
      sleep(1)
      subprocess.Popen('./killltv', shell=True)
      sleep(1)
      subprocess.Popen('./test.py %s'%ytURL, shell=True)
     elif sys.platform == "linux2":
      subprocess.Popen('./killltv', shell=True)
      sleep(1)
      subprocess.Popen('./test.py %s'% ytURL, shell=True)
    #subprocess.Popen('chromium-browser https://www.youtube.com/tv#/watch?v=%s'% ytID, shell=True)
      sleep(2)
    #subprocess.Popen("./fullscreen", shell=True)
     elif sys.platform == "win32":
      os.system('tskill chrome')
      browser = webbrowser.open('http://youtube.com/watch?v="%s"'% ytID)
      log.warn("'%s':,video request:'%s' @ %s"% (channelID, ytID, time))
    #playyt = subprocess.Popen("/Users/Shared/ltv.ap


texts: Generating a maximal geometric progression of integers

texts:
I'm working on a program that generates a maximal geometric progression of at least 3 integers when given a number that the greatest value shouldn't exceed.

My current code works, and it's quick(ish) with small numbers, but anything past 100 takes far longer than I'd like, as I need to calculate numbers in ranges from \$10^7\$ to \$10^{20}\$.

If possible, I'd like to eliminate using Threads, as Python's are known for their lackluster performance.

from itertools import izip,islice,tee,takewhile
from threading import Thread
from Queue import Queue

#initialize the queue
g=Queue()

#checks that all values end with `.0`
def int_check(l):
    for i in l:
        if i-int(i)!=0: return False
    return True

#checks if a generated list fits the criteria
def check(obj):
    cpy0,cpy1=tee(obj)
    iter0,iter1=tee(float(x)/y for x,y in izip(cpy0,islice(cpy1,1,None)))
    return all(x==y for x,y in izip(iter0,islice(iter1,1,None))) and len(obj)>2 and int_check(obj)

#thread target
def calc(s,n,q):
    for r in xrange(125,n*100+1,5):
        t=[s]
        while t[-1]<=n:
            t.extend([t[-1]*((0.0+r)/100)])

        if check(t):
            q.put(takewhile(lambda i: i<=n,t))

#starts threads, calculates final value, and manages queue
def geo_prog(n):
    #Queue -> list
    def dump_queue(q):
        q.put('EOQ')
        res=[]
        return (i for i in iter(q.get,'EOQ'))

    for s in xrange(int(n/4),int(n*0.8)+1):
        t=Thread(target=calc,args=(s,n,g))
        t.start()
        t.join()

    return max(map(sum,dump_queue(g)))

#ex usage
print geo_prog(100)

Examples

geo_prog(4) -> 7.0
geo_prog(10) -> 15.0
geo_prog(12) -> 21.0
geo_prog(100) -> 240.0


texts: Testing the process of assigning offers to a customer

texts:
I asked a similar question yesterday, which was criticised because I posted the test without the supporting code.  Therefore I deleted the question yesterday as it was not clear enough.  I am now going to post it again with the supporting code. Please see the test code below:

[TestFixture]
public class CustomerTest
{
    private IList<Product> _products;
    private Concor _concor;
    private Chestnut _chestnut;

    private IOfferCalculator _offerCalculator;

    [OneTimeSetUp]
    public void OneTimeSetUp()
    {
        _offerCalculator = new OfferCalculator();
    }

    [SetUp]
    public void Setup()
    {
        _concor = new Concor();
        _chestnut = new Chestnut();
        _products = new List<Product>();
        _products.Add(_concor);
        _products.Add(_chestnut);
    }

    [Test]
    public void Should_receive_a_for_concor()
    {
        var expectedConcor = new List<Product>();
        expectedConcor.Add(_concor);
        var gender = "F";
        var expenditure = 1500M;
        var Customer = new Customer(gender,expenditure);
        //Act
        Customer.AssignOffers(_offerCalculator, _products);
        //Assert
        CollectionAssert.AreEqual(Customer._assignedProducts, expectedConcor);
    }
}

Here is the supporting code:

public class Concor : Product
    {
        public override bool Check(Customer customer)
        {
            if (customer._expenditure > 100 && customer._gender == "F")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    public class Chestnut : Product
    {
        public override bool Check(Customer customer)
        {
            if (customer._expenditure >  100 && customer._gender =="M")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    public abstract class Product
    {
        public abstract bool Check(Customer customer);
    }

    public interface IOfferCalculator
    {
        IEnumerable<Product> Calculate(Customer customer, IList<Product> products);
    }

    public class Customer
    {
        public string _gender { get; protected set; }
        public decimal _expenditure { get; protected set; }
        public IList<Product> _assignedProducts = new List<Product>();

        public Customer(string gender, decimal expenditure)
        {
            _gender = gender;
            _expenditure = expenditure;
        }

        public void AssignOffers(IOfferCalculator offerCalculator, IList<Product> products)
        {
            foreach (var product in offerCalculator.Calculate(this, products))
            {
                if (!_assignedProducts.Contains(product))
                {
                    _assignedProducts.Add(product);
                }
            }
        }
    }

    public class OfferCalculator : IOfferCalculator
    {
        public IEnumerable<Product> Calculate(Customer customer, IList<Product> products)
        {
            foreach (var product in products)
            {
                if (product.Check(customer))
                {
                    yield return product;
                }
            }
        }
    }

I would like some feedback about the quality of the test.  The company like to use BDD, however I am conscious that I asserting state rather than behaviour (arguing that I am testing calculations rather than orchestrations).  I would also like some feedback about my use of the: OneTimeSetup attribute and Setup attribute.  Also How would I test for a Chestnut? Add a new method or use an attribute for the test cases?


texts: Java: Only log first error occurrence (with hourly reset)

texts:
I have a redis caching server. If that caching server is down, my app will query the database directly.

I want to know from the logs if my caching server is not reachable. However, if I add a log error, it would completely spam my logfiles if a high amount of users would try to access data.

As a result, I would like to only log the very first error occurrence, resetting only if no errors occurred for an hour.

Is this a feasable approach at all? If so, please review my implementation:

public class CustomCacheErrorHandler implements CacheErrorHandler {

   private Logger logger = LoggerFactory.getLogger(this.getClass());
   private long errorOccurred;
   private final long ONEHOUR = 3600000;

   public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
      if (errorOccurred < (System.currentTimeMillis() - ONEHOUR))
         logger.error("Error while getting cache " + cache.getName() + " for Key " + key);
      errorOccurred = System.currentTimeMillis()
   }
}

Using currentTimeMillis over System.nanoTime() and a final long ONEHOUR over TimeUnit.HOURS.toMillis(1) for performance.

Thanks in advance!


texts: Retrieving a message from a cryptocurrency daemon

texts:
The objective of this piece of code is to get a message from a cryptocurrency daemon through RPC and extract the transactions object to pass it to the view. Is there a simpler / less ugly way of doing this?

$transaction_pool = json_decode($rpc->getTransactionPool(), false);

if(isset($transaction_pool->transactions)){
    $transaction_pool = $transaction_pool->transactions;
}else{
    $transaction_pool = (object)NULL;
}

View partial:

@forelse ($transaction_pool as $transaction)
<?php $transaction_json = json_decode($transaction->tx_json); ?>

{{ $transaction->id_hash }}

        @if ($transaction_json->version == 2)

&nbsp;confidential

        @else

@coin($transaction_json->amount)

        @endif

@coin($transaction->fee)

    @empty

No transactions

@endforelse

    Transactions ({{ count($transaction_pool) }})


texts:
I have code that zips 3 lists, finds a maximum and extracts part of the max tuple. Isn't there a shorter way to do this in F#?

let Triplets = List.zip3 A B C
let T1 (x, _, _) = x
let T2 (_, x, _) = x
let T3 (_, _, x) = x
let Best = List.maxBy T3 Triplets
T1 Best,T2 Best // return to C# code


texts:
I have zones

public class Zone
{
     public string Caption { get; set; }
     public IList<Module> Contents { get; set; }
}

public class Zone1 : Zone
{
}
public class Zone2 : Zone
{
}
public class Zone3 : Zone
{
    public enum Direction
    {
        Up = 1,
        Down = 2,
        Left = 3,
        Right = 4
    }
    public Direction Direction { get; set; }
}

I have json string [{"Caption":"Tab1","IDs":[4,6]},{"Caption":"Tab2","IDs":[9]}] that corresponds to the regular zones like Zone1,Zone2

{"Caption":"Tab1","IDs":[4,6]} means that the name of this zone is Tab1 and it will contain Modules #4 and #6.

I have default parser that will create modules according to IDs(4,6 AND 9).

public interface IZoneParser<T>
{
    IList<T> Parse(string json);
}
public abstract class ZoneParserBase : IZoneParser<Zone>
{
    public virtual IList<Zone> Parse(string json)
    {
        IList<Zone> zones = new List<Zone>();
        try
        {
            IList<ZoneJson> parsedZones = json.FromJSON<IList<ZoneJson>>();

            foreach (var parsedZone in parsedZones)
            {
                var zone = new Zone
                {
                    Caption = parsedZone.Caption,
                    Contents = new List<Module>()
                };
                foreach (var id in parsedZone.IDs)
                {
                    var module = currentPage.CreateModule(id);
                    zone.Contents.Add(module);
                }
                zones.Add(zone);
            }

            return zones;
        }
        catch
        {
            return null;
        }
    }
}

So, in order to parse the above json I'll need some class like

[DataContract]
private class ZoneJson
{
     [DataMember]
     public string Caption { get; set; }
     [DataMember]
     public IList<int> IDs { get; set; }
}

If I'll need to parse Zone3 with json string [{"Caption":"Tab1","IDs":[4,6],"Direction":"1"},{"Caption":"Tab2","IDs":[9]},"Direction":"3"], so I'll create

public class ZoneParserA : ZoneParserBase
{
   publice override IList<Zone3> Parse(string json)
   {
       ....
       IList<Zone3Json> parsedZones = json.FromJSON<IList<Zone3Json>>();

       foreach (var parsedZone in parsedZones)
       {
           var zone = new Zone3
           {
                Caption = parsedZone.Caption,
                Direction = parsedZone.Direction,
                Contents = new List<Module>()
           };
           foreach (var id in parsedZone.IDs)
           {
                var module = currentPage.CreateModule(id);
                zone.Contents.Add(module);
           }
           zones.Add(zone);
       }
       ....
   }
}

and

[DataContract]
[KnownType(typeof(Direction))]
public class Zone3Json : ZoneJson
{
    public Direction Direction { get; set; }
}

So, for each type of Zone(Zone,Zone1,Zone2,Zone3...) I'll need some kind Zone(X)Json that will differ from Zone(X) just with IList<int> IDs property. I can add this property to class Zone, but I don't want that anybody could access it from outside.

In addition, the functionality of method Parse is more or less the same for ZoneParserA and ZoneParserBase.

Is there way to avoid Zone(X)Json classes and/or maybe there are any suggestions to rewriting ZoneParsers?

I hope I explained myself properly.

Thank you


texts: Web API CRUD Demo with Console App and MVC Web Application

texts:
I have created a simple CRUD method using Web API project which consumed by 2 platform: Console App and MVC Web Application. The EntityModel project is mainly the entity and the DAL layer. Is my architecture/structure okay in regards to implementing Web Api? Should I have this DTO thingy or do without? There is only one entity which is the Employee class.

using EntityModel;
using EntityModel.DAL;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;

namespace WebApi.Controllers
{
public class EmployeeController : ApiController
{
    private AppDbContext db = new AppDbContext();

    // GET api/Employee
    public IQueryable<Employee> GetEmployees()
    {
        return db.Employees;
    }

    // GET api/Employee/5
    [ResponseType(typeof(Employee))]
    public IHttpActionResult GetEmployee(int id)
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return NotFound();
        }

        return Ok(employee);
    }

    // PUT api/Employee/5
    public IHttpActionResult PutEmployee(int id, Employee employee)
    {

        if (id != employee.EmployeeID)
        {
            return BadRequest();
        }

        db.Entry(employee).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!EmployeeExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST api/Employee
    [ResponseType(typeof(Employee))]
    public IHttpActionResult PostEmployee(Employee employee)
    {

        db.Employees.Add(employee);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
    }

    // DELETE api/Employee/5
    [ResponseType(typeof(Employee))]
    public IHttpActionResult DeleteEmployee(int id)
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return NotFound();
        }

        db.Employees.Remove(employee);
        db.SaveChanges();

        return Ok(employee);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool EmployeeExists(int id)
    {
        return db.Employees.Count(e => e.EmployeeID == id) > 0;
    }
}

}

Full solution source code is available in my git - https://github.com/ngaisteve1/WebAPIDemo

I just check on Microsoft article on Domain-Driven Design. I think I have combined Domain layer and Infrastructure layer, right?


texts: Download the contents of an HttpURLConnection while generating metadata

texts:
Working on a web crawler (again), except now I've had a lot more time to hone my skills.  The largest bottleneck in my program, as is to be expected, is the actual downloading of the data, so I'd love some feedback on improving this section specifically.

The Response Object is simply a container for an optional JSoup Document (generated by buildDocument(HttpURLConnection, String, String)), the URI queried, the SHA-256 digest of the data, the content type, the size of the data, the connection speed, and the date fetched.

isInfiniteStream(HttpURLConnection) uses crude heuristics to try to figure out if the stream is infinite.  I can post it if people are interested, but it's not very exciting.

BrokenConnectionExceptions are handled up the chain and are thrown when a previously accessible connection is no longer accessible.

protected Response download(HttpURLConnection connection, InputStream stream)
        throws NoSuchAlgorithmException, URISyntaxException, BrokenConnectionException{
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    if(isInfiniteStream(connection))
        return new Response(null, connection.getURL().toURI(), digest.digest(),
                connection.getContentType(), -1, 0, new Date());
    if(Runtime.getRuntime().maxMemory() < connection.getContentLengthLong())
        return new Response(null, connection.getURL().toURI(), digest.digest(),
                connection.getContentType(), connection.getContentLengthLong(), 0, new Date());

    StringBuilder content;
    long size = 0;
    long duration = System.currentTimeMillis();

    try{
        content = new StringBuilder(Math.max(connection.getContentLength(), stream.available()));
        try(BufferedReader in = new BufferedReader(new InputStreamReader(new DigestInputStream(stream, digest)),
                8192)){
            int read;
            for(char[] buffer = new char[8192]; (read = in.read(buffer)) != -1; size += read){
                if(Thread.interrupted()){
                    InterruptedIOException iIOE =
                            new InterruptedIOException("Interrupted while reading stream into buffer");
                    iIOE.bytesTransferred = (int)Math.min(size, Integer.MAX_VALUE);
                    throw iIOE;
                }
                content.append(buffer, 0, read);
            }
        }catch(InterruptedIOException e){
            throw new BrokenConnectionException("Connection interrupted by Thread#interrupt().", e);
        }catch(IOException e){
            throw new BrokenConnectionException("Failure while reading stream into buffer.", e);
        }
    }catch(IOException e){
        throw new BrokenConnectionException("Failure while getting stream availability.", e);
    }

    duration = System.currentTimeMillis() - duration;
    long speed = Math.round((double) size / ((double) duration / 1000));
    String type = connection.getContentType().trim().toLowerCase().intern();

    Document document = buildDocument(connection, content.toString(), type);

    return new Response(document, connection.getURL().toURI(), digest.digest(),
            type, size, speed, new Date());
}

I tried using Java 8 Streams, but things like BufferedReader#lines() were giving me inaccurate byte counts, and performance is actually higher when recycling a char[].  I'm not sure about the 8KB buffer size; is this optimal, and if not, what is?


texts:
I wrote a script that gives a "generalized" function of an arbitrary dice. Is this any good? How can it improve so to make it cleaner?

import random
def roll(die):
    number = random.randint(0,len(die)-1)
    b = die[number]
    return b

Die1 = [1,2,3,4]
Die2 = [1,2,3,4,5,6] #num lists

def inptchacc():
    ending_conditions = ['stop','Stop','quit','Quit']
    end = False
    inpu = input('what number would you like to add to the new face of the Die? (to end the die please type "stop or Stop or quit or Quit to finish the DIE" )')
    while end == False:
        if not(inpu in ending_conditions):
            try:
                retr = int(inpu)
                return retr
            except:
                string = 'invalid input please try again'
                inpu = input('invalid input please try again ')
        else:
            stop = 'stop'
            return stop

def deeper(IDie):
    list = []
    Adding = True
    while Adding:
        print('The Die ' + IDie + ' is currently ' + str(list) )
        toadd = inptchacc()
        if toadd != 'stop':
            list.append(toadd)
        else:
            Adding = False
    return list

def chance_overlap(Die1,Die2):
    highnumber = 1000
    counter = 0
    for n in range(highnumber):
        x = roll(Die1)
        y = roll(Die2)
        if x == y:
            counter += 1
    chance = counter/highnumber
    return chance

chance = chance_overlap(Die1,Die2)

print(chance)
Doing = True
while Doing:
    try:
        IDie1 = deeper('IDie1')
        IDie2 = deeper('IDie1')
        chance2 = chance_overlap(IDie1,IDie2)
        Doing = False
    except:
        print ('incompatible options selected returning....... ')

print(chance2)


texts: Using Statement for OleDB - Is this overkill?

texts:
I am still trying to wrap my head around good programming practice and just wrote this routine to read in an Excel file and return all the sheets into a dataset:

Public Shared Function ReadExcelIntoDataSet(ByVal FileName As String, Optional ByVal TopRowHeaders As Boolean = False) As DataSet
    Try
        Dim retval As New DataSet

        Dim strConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
                                        FileName & ";Extended Properties=""Excel 12.0;IMEX=1;" & _
                                        "HDR=" & If(TopRowHeaders, "Yes", "No") & """;"

        Using oleExcelConnection = New OleDb.OleDbConnection(strConnString)
            oleExcelConnection.Open()

            Using oleExcelCommandString = New OleDb.OleDbCommand("", oleExcelConnection)

                Using oleExcelAdapter = New OleDb.OleDbDataAdapter(oleExcelCommandString)
                    Dim dtSchema As DataTable = oleExcelConnection.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, Nothing)
                    For Each dr As DataRow In dtSchema.Rows
                        Dim Sheetname As String = dr.Item("TABLE_NAME").ToString

                        If Sheetname.EndsWith("$") Then
                            oleExcelCommandString.CommandText = "Select * From [" & Sheetname & "]"
                            oleExcelAdapter.Fill(retval, Sheetname)
                        End If
                    Next

                    Return retval

                End Using

            End Using

        End Using

    Catch ex As Exception
        Dim ErrorData As String = "Unable to Read in Data from the Excel File " & FileName & vbCrLf & _
                                   "Module: Utility > ReadExcelIntoDataSet"
        Throw New Exception(ErrorData & vbCrLf & "ERROR Data:" & vbCrLf & ex.Message)
    End Try
End Function

My first questions are:

Is the use of the Using statements good or is it some kind of over-kill and should this maybe be handled in a Finally statement in stead?
Is this the best method to read in an Excel File (Given that they can be either .xls or .xlsx) in the fastest possible way?
What is the best way to pass the error up to the calling code? Did my Catch statement do that well enough??


texts:
I am preparing for ACM-TCPC (Tunisia). So I started solving problems from past ACM-ACPC versions. But I got stuck in the Problem I from 2014.

The problem consists of finding the number of non-equivalent passwords in list of passwords. Two passwords, A and B, are equivalent if len(A) == len(B)  and |A[i] -B[i]| is the same for i in [0..len(A)] (len is the length of the password and |x| is the absolute value of x).

Examples:

Input:

000
111
222

Output:

1

Input:

1111
123
214
2222

Output:

2

Input

43434
54545
45454

Output:

2

My code works fine and it solves the Judges I/O, However it takes a plentiful amount of time!

The code I wrote:

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Password {
    public static void main(String[] args){
        String[] str_tab ;
        HashMap<Integer, Integer> hm = null;
        List<String> l = null;
        try {
            int[] tab = null;
            BufferedReader br = new BufferedReader(new FileReader(new File("./password.in")));
            PrintWriter wr = new PrintWriter("./passwrd.out");
            int T = Integer.parseInt(br.readLine().toString());
            for (int i = 0; i < T; i++) {
                l = new ArrayList<String>();
                int N = Integer.parseInt(br.readLine().toString());
                for (int j = 0; j < N; j++) {
                    l.add(br.readLine().toString());
                }
                wr.println("Case "+(i+1)+": " +solve(l));
            }
            wr.close();

        }catch(Exception e){
            e.printStackTrace();
        }
}
    public static int solve(List<String> l){
        List<String> ls = new ArrayList<String>();
        ls.add(l.get(0));
        int j= 0;
        for (int i = 1; i < l.size(); i++) {
            j = 0;
            while(j<ls.size() && !isEq(l.get(i),ls.get(j))) j++;
            if(j == ls.size()) ls.add(l.get(i));
        }

        return ls.size();
    }
    public static boolean isEq(String p1, String p2){
        if(p1.length() != p2.length()) return false;
        int diff = Math.abs(p1.charAt(0) - p2.charAt(0));
        for (int i = 1; i <p1.length(); i++) {

            if(Math.abs(p1.charAt(i) - p2.charAt(i)) != diff){
                return false;
            }
        }
        return true;
    }
}

Did I get it wrong? Is there advice that could help me improve my code? (performance, organization or anything)


texts: Return n largest nonzero entries of an array

texts:
For something I'm working on, I need a function that takes in a one-dimensional array vec of integers and returns a boolean array of the same shape indicating where the n largest entries of vec are located.
For example,

nlargest([0, 1, 3, 5], 2) should yield [0, 0, 1, 1].
nlargest([0, 0, 4, 0, 3, 6], 2) should yield [0, 0, 1, 0, 0, 1].
nlargest([2, 1, 4, 3], 1) should yield [0, 0, 1, 0].

I have decided it's worthwhile to write my own function to do this, because the input data in this case has a few "nice" properties:

n is always strictly smaller than the number of nonzero entries in vec and greater than zero
The nonzero entries are all positive integers and there are no ties among them

Here is a working Julia function that does this:
function nlargest(vec, n)
    # Boolean vector shaped like input indicating n largest entries
    inp = copy(vec)
    out = zeros(Bool, length(vec))
    for i in 1:n
        am = argmax(inp)
        out[am] = true
        inp[am] = -1
    end
    return out
end

I am more interested in the design of the algorithm itself than the specific Julia implementation, so here is equivalent pseudocode:

Initialize: out ← a array of boolean 0s shaped like vec
Repeat n times:

j ← argmax(vec)
Set the jth entry of out to 1
Set the jth entry of vec to -1 (*)

Return out

(*) is taking advantage of the fact that all the nonzero entries are positive, but it feels like a bit of a hack to me. An alternative idea I had for this step was to "pop" the jth entry out of vec so that argmax(vec) has shorter input on the next loop. But it seems to me that the time savings there are offset by then having to adjust subsequent j values based on the new length of vec. Is this reasoning sound, or is there something clever I can do here?
Have I taken full advantage of the structure of my input data? Can I do better than the default argmax() function?
Of course, feedback on the Julia implementation is also welcome.


texts: Find minimum value in a BST: using boolean operators, and using conditionals

texts:
I've been studying the BST code in Paul Graham's ANSI Common Lisp.

He provides (my comments):

(defun bst-min (bst)
  (and bst                               ; [3]
       (or (bst-min (node-l bst)) bst))) ; [4]

(defun bst-max (bst)
  (and bst                               ; [5]
       (or (bst-max (node-r bst)) bst))) ; [6]

;; [1] How do you find min and max of a bst?
;;     Recall, the core point is that all items in left subtree are lower,
;;     and all items in right subtree are higher, & this holds for the whole
;;     tree, -otherwise binary search would miss-, and not just within a
;;     single parent child relationship.
;; [2] Therefore, to find min, we just need to go left until we can go left
;;     no more, & that's the min. If the above property didn't hold, you
;;     might go left, then right, then left, and that final one there
;;     could be as low as you like; but no, it must be greater than its
;;     ancestor of which it is a right child.

;; [3] A null node has no min. The base case. Returns nil if bst is empty.
;; [4] For a non null node, the min is either the min of its left node, or
;;     if that's null, then it's this node, instead.
;; [5] A null node has no max. The base case. Returns nil if bst is empty.
;; [6] For a non null node, the max is either the max of its right node, or
;;     if that's null, then it's this node, instead.

I find this code more or less fine, but I still find it not easy to read or cognitively process.

I'm wondering whether that subjective fact is a feature of the code itself (i.e., is the code really hard to read), or whether it's something I need to stick with and then it will become very natural; remembering Hickey's advice about lisp that it is simple but not easy.

So, I produced this version by translating from a java implementation.
It's easier for me to read (currently).

(defun bst-min (bst)
  (if (null (node-l bst))
      bst
      (bst-min (node-l bst))))

(defun bst-max (bst)
  (if (null (node-r bst))
      bst
      (bst-max (node-r bst))))

Is the first version somehow a relic of former days?
Would anyone program like that now?

Question I would like to ask helpful peeps here is: which version would you favour and why?


texts:
I am computing address string form the JS object. I am using EmberJS. I wanted to review my code and tell me how we can improve the computation of address, or is there any better way to it?

const {
  get,
  computed,
} = Ember;

// other properties.
completeAdress: computed({
    let address = '';
    if (get(this, 'title')) {
        address = `${address},${get(this, 'title').toString()}`;
    }
    if (get(this, 'number')) {
        address = `${address},${get(this, 'number').toString()}`;
    }
    if (get(this, 'street')) {
        address = `${address},${get(this, 'street').toString()}`;
    }
    if (get(this, 'city')) {
        address = `${address},${get(this, 'city').toString()}`;
    }
    if (get(this, 'region')) {
        address = `${address},${get(this, 'region').toString()}`;
    }
    if (get(this, 'state')) {
        address = `${address},${get(this, 'state').toString()}`;
    }
    if (get(this, 'country')) {
        address = `${address},${get(this, 'country').toString()}`;
    }
    if (get(this, 'zipcode')) {
        address = `${address},${get(this, 'zipcode').toString()}`;
    }
    if (get(this, 'phone')) {
        address = `${address},${get(this, 'phone').toString()}`;
    }
    if (address.length > 0) {
        address = address.substring(1, address.length);
    }
    return address;
}),
// other properties

Basically is there any way to avoid too many if conditions.

{
  title: 'MacD',
  street: '49'
  // rest of the properties are related to address only
};
// This is example address object


texts: Spread values to an object (Computed property names)

texts:
I would like to get a review of something,

I have a function that creates an array of objects for a Drop-Down component (react-select).

The function gets data, valueKey, labelKey and otherInfo from an object,
and creates the array of objects based on the valueKey and the labelKey.

const createOptions = ({data, valueKey, labelKey, ...otherInfo}) => {
  return data.map(item =>
    ({
      value: item[valueKey],
      label: item[labelKey],
      ...appendOtherInfo(item, otherInfo)
    })
  );
}

most of the time, valueKey and labelKey are enough, but there are some cases where there is additional info to add to each object, which is otherInfo, which is an object as well.

appendOtherInfo() function creates an object which is then appended to each object that map iteration returned.

const appendOtherInfo = (item, otherInfo) => {
  return Object.entries(otherInfo).reduce((total, [key, value]) => {
    total[key] = item[value];

    return total;
  }, {});
}

for example, after calling createOptions() with the array:

const people = [
  {id: '123', name: 'Dani', type: 'a', city: 'Rome'},
  {id: '222', name: 'John', type: 'a', city: 'London'},
  {id: '333', name: 'David', type: 'b', city: 'Madrid'}
]

and the rest of the info to create the new array,

createOptions({
  data: people,
  valueKey: 'id',
  labelKey: 'name',
  type: 'type',
  capitalCity: 'city'
});

The result is:

[
  {
    "value": "123",
    "label": "Dani",
    "type": "a",
    "capitalCity": "Rome"
  },
  {
    "value": "222",
    "label": "John",
    "type": "a",
    "capitalCity": "London"
  },
  {
    "value": "333",
    "label": "David",
    "type": "b",
    "capitalCity": "Madrid"
  }
]

In the appendOtherInfo() function, I used Object.entries and reduce to create the additional info for each object.
It's working as expected, but I'd like to know if there is a better/easier way to achieve the same result.


texts: Code organization: interacting with SQLAlchemy from inside class

texts:
I don't like the way my code is written, but at the moment, I don't see, how I should do it better.

I have a class (let's say MyInvoiceType), which needs to save data to preexisting database. The database is now mapped with SqlAlchemy (initially was just created via SQL interface).

I would have certain Table classes mapped via reflection and for one I need to specify PKs myself, therefore (as I understand) I had to create custom class:

from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine,Table

Base=automap_base()
class Batches(Base):
    __tablename__="batches"
    __table__ = Table(__tablename__, Base.metadata, autoload=True, autoload_with=engine)
    __mapper_args__ = {'primary_key': [__table__.c.composite_pk1,__table__.c.composite_pk2]}

sql_conn='my://db@connection'
engine=create_engine(sql_conn)
Base.prepare(engine, reflect=True)

Clients=Base.classes.clients
Invoices=Base.classes.invoices
InvoiceLines=Base.classes.invoicelines
Session=sessionmaker(bind=engine)

class MyInvoiceType(object):
    def __init__(self):
        self.session=Session() # actual DB session
    # here go functions which read data from pandas dataframe, check it
    # and push it out into respective DB tables for invoice data, invoice lines data,
    # and batches for each invoice line.
...

Now, MyInvoiceType is the only place where I use the mapped table classes (Clients,Invoices,InvoiceLines and Batches). What happens is, I get invoice data, check it, and feed it into the 3 invoice data tables, which make up the real invoice.

I feel it is ugly to have so much preparatory things happen outside the class, which would be executed whenever I load this module file, even if I did it by mistake and never instantiated MyInvoiceType. In particular, I don't like sql_conn variable dangling outside any class/function.

Is there a better way to organize this code so that database interaction happens as much as possible only when I try to create a new MyInvoiceType() object? Would it be good or on the contrary, bad? In particular, can (and should I) move all the engine creation and Invoices,etc class creation to inside MyInvoiceType? Can I/Should I do something like self.Clients=Base.classes.clients? What about Batches?


texts: Implementation of the Selection Sort Algorithm

texts:
I have tried to implement the Selection Sort Algorithm in two different ways, and I was just wondering if that is considered to be a valid implementation of that algorithm. Would that be also considered an efficient implementation of the algorithm, or are there different and more efficient ways?

Here are my implementations:

Implementation Attempt #1

def selection_sort(L: List[int]) -> List[int]:
    for i in range(len(L) - 1):
        j = i
        smallest_num = L[i]
        while j < len(L) - 1:
            if smallest_num > L[j + 1]:
                smallest_num = L[j + 1]
            j += 1
        L[L.index(smallest_num)], L[i] = L[i], L[L.index(smallest_num)]
    return L

Implementation Attempt #2

def selection_sort(L: List[int]):
    for i in range(len(L) - 1):
        j = i
        while j < len(L) - 1:
            swap_min(L, i)
            j += 1
    return L

def swap_min(L: List[int], n: int) -> None:
    smallet_num = min(L[n:])
    sm_indx = L.index(smallet_num)
    L[n], L[sm_indx] = L[sm_indx], L[n]


texts:
I'm implementing a (hopefully) efficient MSB Radix Sort in Java. My current implementation isn't efficient enough for my use-case (see bottom for a brief performance comparison against Arrays.sort).

Please rip me to shreds over any general improvements you can suggest; I am currently most interested in suggestions for performance improvements, though.

I do use recursion, as I'm only copying references in each stack frame (so I don't think I'm going to be taking much of a hit there). I allocate two buffers and each layer in the recursion tree uses one arrays as an input and one as an output - each node on each layer sorts a different bucket within the input, storing its results in the output before recursing.

// Sort "amount" integers from "input" and write them to "output".
protected void radicsSort(DataInputStream input, DataOutputStream output, int amount) throws IOException
{
    // Read in our buffer to memory
    int[] inputBuffer = new int[amount];
    for (int x = 0; x < inputBuffer.length; ++x)
        inputBuffer[x] = input.readInt();

    // Allocate an output buffer as big as the input one
    int[] outputBuffer = new int[amount];

    //// Sort the input  buffer
    radicsSort(inputBuffer, outputBuffer, 0, amount, Integer.SIZE - 1);

    // Input and output are swapped each layer of recursion, and we recurse as many times
    // as there are bits in an integer, so ensure the final output is in outputBuffer.
    // Commented out at the moment as we get a warning as technically we already know the result...
    //if (Integer.SIZE % 2 == 0)
        outputBuffer = inputBuffer;

    // Write the output to the file
    for (int x = 0; x < outputBuffer.length; ++x)
        output.writeInt(outputBuffer[x]);
}
// Sort the integers in "inBuffer" at indices between "start" inclusive and "end" exclusive,
// by the value of the bit at "bit", storing the results in "outBuffer" in the same
// interval as they were taken from
protected void radicsSort(int[] inBuffer, int[] outBuffer, int start, int end, int bit)
{
    // TODO: Check negative numbers are sorted correctly with this
    int zeroIndex = start; // Counts up from the start
    int oneIndex = end; // Counts down from the end

    for (int x = start; x < end; ++x)
    {
        if (((inBuffer[x] >> bit) & 1) == 0) // Bit is 0
            outBuffer[zeroIndex++] = inBuffer[x];
        else // Bit is 1
            outBuffer[--oneIndex] = inBuffer[x];
    }

    if (bit > 0)
    {
        // Recurse to sort the two sub-regions, moving one bit towards the LSB.
        // Swap the input/output buffers
        radicsSort(outBuffer, inBuffer, start, oneIndex, bit - 1);
        radicsSort(outBuffer, inBuffer, oneIndex, end, bit - 1);
    }
}

Performance comparison with Arrays.sort, times given in milliseconds:

Number of integers        Arrays.sort        Above implementation
1024                      1                  8328
1048576                   1221               19367

I understand that radix sort has a high constant overhead, but I thought it would have overcome that by the time we're sorting 4MiB of data.

The things I can think of to tweak are:

Use iteration instead of recursion (don't think this will change much).
Sort by eg. decimal digit instead of binary digit. Again, don't know how much of a performance impact this'll have.
Switch to eg. insertion sort after a threshold. I believe this is normally done to overcome the overhead of allocating new structures when you're working with small buckets. I think my implementation avoids this overhead anyway, by using a common output buffer and swapping input/output buffers, so I don't think this'll have much of an impact.


texts:
Due to my needing to use C libraries inside C++, I kept finding myself wanting to be able to ensure that the free function got called, even if an exception got thrown. UTILS_SCOPE_EXIT ensures that the function will be called at the end of scope. External documentation shows how to use it, and also clarifies that it is not allowed to have multiple calls on the same line (because __COUNTER__ is not always supported):

utils.hpp

#pragma once
#include <functional>

namespace utils { namespace internal {

class ScopeExit_ {
public:
    ScopeExit_(std::function<void()> callback)
        : callback_{ callback }
    {}
    ~ScopeExit_()
    {
        callback_();
    }
private:
    std::function<void()> callback_;
};

#define UTILS_INTERNAL_CAT_HELPER(x, y) x ## y
#define UTILS_INTERNAL_CAT(x, y) UTILS_INTERNAL_CAT_HELPER(x, y)
#define UTILS_SCOPE_EXIT(...) utils::internal::ScopeExit_ UTILS_INTERNAL_CAT(utils_internal_ScopeExit_, __LINE__){ __VA_ARGS__ }

} }

This can be used like so:

#include <iostream>

int main()
{
    UTILS_SCOPE_EXIT([]{ std::cout << "1" << std::endl; });
    UTILS_SCOPE_EXIT([]{ std::cout << "2" << std::endl; });
    UTILS_SCOPE_EXIT([]{ std::cout << "3" << std::endl; });
    std::cout << "4" << std::endl;
    std::cout << "5" << std::endl;
}

Outputs:

4
5
3
2
1