texts: a beginner's approach & confusion bash script

texts:
I've started learning bash today, but I knew basics of javascript.
It would be very nice if anyone can point me at least a few advices on the code.
Because there are so many details in bash, I hope you won't be too harsh.
Expected behavior
The code is supposed:

to set the value of a variable named 'charge' from the input files
create a few directories and subdirectories based on the input files

Concrete Example
Let's say there is a mol2 file named glucose-minus1.mol2.

I expect the code to set up a variable charge with value -1, so charge="-1". So you can see there is a translation from minus1 --> -1
If the filename is 'wrong' the user should be notified "we can't find the charge value in the filename" or something like that.
And to create a directory named glucose-minus1 (without the
extension) plus the 3 sub-directories "solv" "sin-solv" and "thermo".
All this if the directories are do no exist already.

#!/bin/bash
touch "mol-minus1.mol2" "mol-minus2.mol2"
molecules=(*.mol2)
subdirs=("solv" "sin-solv" "thermo")

setCharge () {
        #input molfile
        #if it finds any chargeLabel in molfile, sets the charge value (and we use it later).
        chargeLabels=( "minus3" "minus2" "minus1" "cero" "plus1" "plus2" )
        charges=("-3" "-2" "-1" "0" "+1" "+2")
        echo "${chargeLabels[*]}"
        for index in "${!chargeLabels[@]}"
        do
                if [[ "$1" == *"${chargeLabels[index]}"* ]]
                then
                        charge="${charges[index]}"
                        echo "$charge"
                else
                        echo "Im not setting charges..."
                        continue
                fi
        done
}

createDir(){
        #pass dir as an argument.
        if [ ! -d "$1" ]
        then
                mkdir "$1"
        else
                printf " %s is already there " "$1"
        fi
}
for mol in "${molecules[@]}"
do
        [ -f "$mol" ] || exit 0
        #sets the carge variable to a value included in molfile.
        echo "$mol"
        setCharge "$mol"
        #acreate molecule directory if not there.
        IFS="." read -ra splitted <<< "$mol"
        if [[ ! -d "${splitted[0]}" ]]
        then
                mkdir "${splitted[0]}"
                printf "directory %s has been created. Molecule charge is %s" "${splitted[0]}" "$charge"
        else
                printf "directory %s already exists. Molecule charge is %s" "${splitted[0]}" "$charge"
                continue
        fi

        #create subdirectories if not there.
        cd "${splitted[0]}" || printf "No directory with name %s" "${splitted[0]}" && exit 0
        for dir in "${subdirs[@]}" #create subdirs if not there.
        do
                createDir "$dir"
        done
        cd '../' #single quotes for string literals.
        cp "$mol" "${splitted[0]}/sin-solv/"
        #python -c'import flexo_api.py; flexo_api.flexo("$)'
done

```


texts: Find the year when the user will turn 100

texts:
I moved to Python today after doing a little of c++. The following code works as intended, but I want to know if I should add the if __name__ == "__main__" statement. Any other improvements?

import datetime

def inputInfo() :
    userName = input("Who are you?")
    userAge = input("How old are you?")
    return (userName , userAge)

def findYearWhenAge100(name , age) :
    currentTime = str(datetime.datetime.now())
    currentYear = int(currentTime[0: 4])
    age = 100 - int(age)
    currentYear += age
    print( name ,"is going to be 100 by", currentYear)

if __name__ == "__main__":
    userName , userAge = inputInfo()
    print(findYearWhenAge100(userName , userAge))


texts: Searching JSON recursively for an item with a "selected" attribute

texts:
I have the following function, which I believe could be improved with functional-programming.

        function findSelectedInList(list){
        for(var i=0;i<=list.length;i++){
            var currentItem = list[i];
            if(currentItem.selected === "selected"){
                return currentItem;
            }
            var selectedNode = findSelectedInList(currentItem.children)
            if(selectedNode){
                return selectedNode;
            }
        }
        return void 0;
    }

Here are some sample inputs:

    var treeList = [ { "roleName": "User",
                   "roleId": "role1",
                   "children": [ { "roleName": "subUser1", "roleId": "role11", "children": [], "selected": "selected" }]
                 }];

    var treeList2 = [ { "roleName": "User", "roleId": "role1", "children": [],"selected":"selected"}];


texts: Inefficient (slow) loop with calculations in worksheet

texts:
I am looking for best practice help. Slow loops seem to be a recurring problem for me and I'd like to learn a better way.  The code itself works as it should, except it is far too slow.

The problem is the worksheet needs to calculate after each B & i value is dropped into "N13" so that "U12", "V12", and "W12" update before being deposited into wsRepository. If I turn Calculation on Manual then my values are no good because they are contingent upon the other worksheet formulas updating (calculating). I think I can copy my worksheets "off-screen", calculate, and then paste my values back "on-screen", but I am not sure how to do this. I've used variants in the paste to do similar things, but I not comfortable with them. There may even be more efficient ways of achieving my desired result that I am unaware of.

Application.ScreenUpdating = False

Dim wsRepository As Worksheet
Dim wsInput As Worksheet
Dim i As Integer

Set wsRepository = ThisWorkbook.Sheets("Repository")
Set wsInput = ThisWorkbook.Sheets("Input")

For i = 4 To 2004

           'add investment amount
           wsInput.Range("N13").Value = wsRepository.Range("B" & i).Value

           'copy back amounts
           wsRepository.Range("E" & i).Value = wsInput.Range("U12").Value
           wsRepository.Range("C" & i).Value = wsInput.Range("V12").Value
           wsRepository.Range("D" & i).Value = wsInput.Range("W12").Value

    Next i

wsInput.Activate


texts: Check if string is or can be made into a "valid string"

texts:
The Challenge:

  A valid string is one in which all distinct characters occur the same
  number of times. Given a string S, check if the string can be made
  valid by removing less than or equal to one character. If yes, output
  "YES". Otherwise output "NO".

  Constraints:

  \$1 \le \lvert S \rvert \le 10^5\$
  String S contains lowercase letters only (a-z)

I'd appreciate any comments and suggestions as to how my code can be improved.

function processString(str) {
    if(str.length === 1){
        console.log("YES");
    }
    else{
        const letterCount = buildCount(str.trim());
        console.log(checkValid(letterCount) ? "YES" : "NO");
    }
}

function buildCount(str){
    const letterCount = {};
    const len = str.length;
    for (let i = 0; i < len; i++) {
        letterCount[str[i]] = (letterCount[str[i]] || 0) + 1;
    }
    return letterCount;
}

function checkValid(letterCount){
    const totals = [];
    for(let key of Object.keys(letterCount)){
        totals.push(letterCount[key]);
    }
    //only one can be different- and it has to be more than the others
    //if always compare to the first,
    //  doesn't work if that is the one that is more
    const compareVal = Math.min(totals[0], totals[1]);
    const diffOnes = totals.filter(function(val){
        return val !== compareVal;
    });
    if(diffOnes.length > 1
        || diffOnes[0] > (compareVal + 1)){
        return false;
    }
    return true;
}


texts:
I was in need to sort Colors, so the first thing that I tried was this:

Arrays.sort(new javafx.scene.paint.Color[] {Color.ALICEBLUE},Color.AZURE,Color.BLUEVIOLET,Color.AQUA,...);

But unfortunately Arrays.Sort is not compatible with javafx.scene.paint.Color, so I ended up with this:

public static void main(String[] args) {
    final String[] colors = {"AQUA", "LAWNGREEN", "LIGHTBLUE", "CYAN", "CHOCOLATE", "GREEN",
        "RED", "YELLOW", "GAINSBORO", "YELLOWGREEN"};

    final Function<String, ? extends Color> valueMapper = (final String name) -> {
        try {
            return (Color) Color.class.getField(name).get(null);
        } catch (final IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e) {
            throw new RuntimeException(e);
        }
    };
    final Map<String, Color> map = Arrays.stream(colors).collect(
            Collectors.toMap(Function.identity(), valueMapper));

    map.entrySet().stream().sorted(Comparator.comparing(Entry::getKey)).forEach((Entry<String, Color> entry) -> {
        System.out.println(entry.getKey() + " = " + entry.getValue());
    });

}

Now let me know if this code can be improved and optimized.


texts: Most efficient way to check if user is allowed to update an object

texts:
So I have an user which can create his own Locations.

I implemented a webservice in order to add and update locations. If the user is not the owner of the location i want to throw an appropriate exception so that the user knows whats wrong.

The current method looks like this:

private void updateLocation(String loginToken, MapLocation ml) throws Exception{
    String username = this.getUsernameBySingInToken(loginToken); //throws exception is wrong token, otherwise returns username

    PreparedStatement stmt = conn.prepareStatement("SELECT username FROM Location WHERE idLoc=?");
    stmt.setInt(1, ml.getLocationId());
    ResultSet rs = stmt.executeQuery();
    String actuallUsername = null;
    while (rs.next()) {
       actuallUsername=rs.getString("username");
    }
    if(actuallUsername==null)
        throw new Exception("no location found!!"); //appropriate exception

    if(!username.equals(actuallUsername) || !username.equals(ml.getUsername()))
        throw new Exception("you are not the creator of this location!"); //appropriate exception

    PreparedStatement stmtVerification = conn.prepareStatement("UPDATE Location SET positionX=?,positionY=?"
            + " WHERE idLoc=?");
    stmtVerification.setDouble(1, ml.getPosX());
    stmtVerification.setDouble(2, ml.getPosY());
    stmtVerification.setInt(3, ml.getLocationId());
    stmtVerification.executeUpdate();

    disconnectFromMySQL();
}

The second method I implemented is shorter but the errors are not clear:

private void updateLocationV2(String loginToken, MapLocation ml) throws Exception{
    String username = this.getUsernameBySingInToken(loginToken);
    if(!username.equals(ml.getUsername()))
        throw new Exception("username is not the same as username of maplocation object"); //not sure if neccesary

    PreparedStatement stmtVerification = conn.prepareStatement("UPDATE Location SET positionX=?,positionY=?"
            + " WHERE idLoc=? and username=?");
    stmtVerification.setDouble(1, ml.getPosX());
    stmtVerification.setDouble(2, ml.getPosY());
    stmtVerification.setInt(3, ml.getLocationId());
    stmtVerification.setString(4, username);

    int executeUpdate = stmtVerification.executeUpdate();
    if(executeUpdate==0)
        throw new Exception("update failed. either wrong username or idLocation is wrong"); //not clear what is the error BUT shorter
    disconnectFromMySQL();
}

So yeah, now I have two methods which update my location but I am not sure which of them is the best. The first method has the advantage that the errors are clear but its slower since I have two queries (select and update). the second method is faster but the errors are not clear. WHich one of them is better, or is there even a better solution?

EDIT: This is my webservice method which calls the update function:

@PUT
@Path("/update")
@Consumes({MediaType.APPLICATION_JSON})
public Response update(String token, MapLocation ml) {
    Response r = Response.status(Response.Status.OK).entity("location updated").build();
    try {
        isUpdated = db.updateLocation(token,ml);
    } catch (Exception ex) {
        r = Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
    }
    return r;
}


texts: What improvements are needed in this class to fill DropDown using PetaPoco?

texts:
Below is the class which I am using to fill multiple DropDowns on ASP.NET Page Load event:

public sealed class getBlocks
{
    public getBlocks(DropDownList dropDownName, string districtId)
    {
        returnBlocks(dropDownName, districtId);
    }

    public void returnBlocks(DropDownList DropDownName, string DistrictId)
    {
        var DB = new PetaPoco.Database("cnWebDems");
        string Query = "SELECT distinct blockname, blockid FROM hab_master WHERE distid = '" + DistrictId + "' ORDER BY blockname";
        var result = DB.Fetch<hab_master>(Query);
        DropDownName.DataSource = result;
        DropDownName.DataTextField = "blockname";
        DropDownName.DataValueField = "blockid";
        DropDownName.DataBind();
        DropDownName.Items.Insert(0, "-- Select --");
        DB.Dispose();
    }

Suggest further improvements.


texts:
I want to combine elements in different lists.
For example, here are 3 lists.

list_a : [ 1,2,3 ]
list_b : [ 4,5,6 ]
list_c : [ 7,8 ]

Selecting elements from list_b and list_c is mutually exclusive.  When including an element from list_b, I'd like to also include an element from list_bb; when including an element from list_c, I'd like to also include an element from list_cc.

list_bb : [ 14,15,16 ]
list_cc : [ 17,18 ]

I wrote this code:

global sum_list=[]
for a in list_a:
    for b in list_b:
        for bb in list_bb:
            sum_list.append([a,b,bb])
for a in list_a:
    for c in list_c:
        for cc in list_cc:
           sum_list.append([a,c,cc])

Is there any better way to get the same result?


texts: read an excel that contains population data of counties and compute summaries by state, county

texts:
As part of the exercise in the book "Automate the boring stuff with Python" chapter 13 on Excel, I had the following exercise:

Reads the data from the Excel spreadsheet
Counts the number of census tracts in each county
Counts the total population of each county
Prints the results

Here is the structure of the spreadsheet

Here is my code and I would like to get reviews on how I can improve this code as I am quite new to Python.

from collections import Counter
import openpyxl

wb = xl.load_workbook("support files/censuspopdata.xlsx")
sheet = wb.active

#Create a unique list of all state names from the state column (which is 2nd column)
states = set()
for cell in list(sheet.columns)[1][2:]:
    states.add(cell.value)

#Initiate the countie_in_state dict to hold a set for each state key as it would be populated when the Excel is read row-by-row
counties_in_state ={}
for state in states:
    counties_in_state[state]=set()

# counter counts the number of census tracts(rows) and counter_pop holds the cumulative population
counter = Counter()
counter_pop = Counter()

#Skip the first row as it contains column names
for row in range(2,sheet.max_row+1):
    #Each row represents a census tract
    state  = sheet.cell(row,2).value
    county = sheet.cell(row,3).value
    pop = sheet.cell(row,4).value

    counties_in_state[state].add(county)
    counter[county] += 1
    counter_pop[county] += pop

# Sort the counties in each state
for state,county_set in counties_in_state.items():
    counties_in_state[state] = sorted(county_set)

print("State","County", "Count", "Pop", sep="\t")
for state,county_set in counties_in_state.items():
    for county in county_set:
        print(state, county, counter[county], counter_pop[county], sep="\t")


texts: Bash delete folder if not present in other folder

texts:
imaging a folder structure like:

Peter
|- Cats
   |- Mini
   |- Maunz
   |- Tippsi
|– Dogs
   |- Brutus

Eva
|- animals
   |- Mini
   |- Brutus

I'd like to delete all subfolders in Peter/*/ if they not present in Eva/animals/  (Maunz and Tippsi).
This is what I have so far. It's working but it feels as my combination of loop and find is not the best solution:

for dir in ./Peter/*/*/
do
   dir=${dir%*/}
   if find './Eva/animals' -type d -name ${dir##*/} -exec false {} +
   then
      echo "${dir%*/} not found and deleted"
      rm -rf ${dir%*/}
    fi
done

For learning, can this code be optimized?


texts: Maxwell's distribution using Box-Muller transform

texts:
I am given the following problem to solve (This text is translated from Russian. So, there may be some translation issues):

  ... Another method to draw from the normal distribution is to draw two independent random numbers from the uniform distribution x1, x2 ∈ [0:0, 1:0). Then apply the following transformation:

  \$n_1 = \sqrt{-2\log{x_1}}\cos{2\pi x_2}\$

  \$n_2 = \sqrt{-2\log{x_1}}\sin{2\pi x_2}\$

  resulting in two randomly independent numbers n1, n2 from a normal distribution with zero expected value and unit variance.

  To change the distribution parameters to other parameters, e.g. the expected value for and the variance to, you should multiply the result of the draw by and add, i.e.

  \$N(\mu, \sigma) = \sigma N(0, 1) + \mu\$

  In the equation above, N(μ, σ) is a random variable with normal distribution with expected value μ and variance σ.

  According to the Maxwell distribution, each component (x, y or z) of the velocity vector v is a random variable from a normal distribution with zero expected value, and variance \$\sqrt{\dfrac{k_B T}{m}}\$
  where m is the mass of the molecule, T is the temperature in Kelvin, kB is Boltzmann constant.

  Your task: Draw 10,000 velocity vectors for the N2 nitrogen molecule at 300K. Calculate the average length of these vectors, and therefore the average value of the speed of the nitrogen molecule, using the formula:

  \$\bar{v} = \dfrac{1}{N}\sum_{i=1}^N\sqrt{v_{x_i}^2 + v_{y_i}^2 + v_{z_i}^2}\$

using System;

public class CommonDistributions
{
    public static int Uniform(Random random, int n)
    {
        return (int)(random.NextDouble() * n);
    }

    public static double Uniform(Random random, double lo, double hi)
    {
        return lo + random.NextDouble() * (hi - lo);
    }

    public static double Gaussian(Random random)
    {
        double r, x, y;
        do
        {
            x = Uniform(random, -1.0, 1.0);
            y = Uniform(random, -1.0, 1.0);
            r = x * x + y * y;
        }
        while (r >= 1 || r == 0);

        return x * Math.Sqrt(-2 * Math.Log(r) / r);
    }

    public static double Gaussian(Random random, double mu, double sigma)
    {
        return sigma * Gaussian(random) + mu;
    }
}

public class MaxwellBolzman
{
    static double KB = 1.38064852e-23;

    static double MaxwellVariance(double mass, double temperature)
    {
        return Math.Sqrt(KB * temperature / mass);
    }

    static double MaxwellComponent(Random random, double mass, double temperature)
    {
        double mu = 0.0;
        double sigma = MaxwellVariance(mass, temperature);

        return CommonDistributions.Gaussian(random, mu, sigma);
    }
    public static double Maxwell(Random random, double mass, double temperature)
    {
        double one = MaxwellComponent(random, mass, temperature);
        double two = MaxwellComponent(random, mass, temperature);
        double thr = MaxwellComponent(random, mass, temperature);

        return Math.Sqrt(one * one + two * two + thr * thr);
    }
}

public static class MainClass
{
    public static void Main(String[] args)
    {
        Random random = new Random();

        const int N = 10000;
        const int T = 300;//300K
        const double mass = 28.02;//28.02 g/mol

        double sum = 0.0;

        for (int i = 1; i < N; i++)
        {
            sum = sum + MaxwellBolzman.Maxwell(random, mass, T);
        }

        Console.WriteLine($"Maxwell-Boltzman Vector = {sum/N}");

        string str = string.Empty;
    }
}

Kindly, review the implementation.

I am not sure about the values of temperature and the mass of Nitrogen 2.


texts: PHP associative array with two properties

texts:
I'm moving a system over to PDO and since the queries are parameterized, I need to specify both the type and value of each parameter when preparing them.

Right now I have a prepare method to create the PDOStatement object:

/**
 * Prepares a statement
 * @param string $sql The query
 * @param array $data The data to bind
 * @param array $types The types of data
 * @return \PDOStatement
 */
private function prepare($sql, array $data, array $types) {
    if (sizeof(array_diff_key($types, $data)) || sizeof(array_diff_key($data, $types))) {
        throw new \InvalidArgumentException('Keys of data and types arrays do not match.');
    }

    $stmt = $this->pdo->prepare($sql);
    foreach ($data as $key => $value) {
        $stmt->bindValue($key, $value, $types[$key]);
    }
    return $stmt;
}

Places where the code is called look like this:

$sql = "UPDATE table_name SET col1 = :param1, col2 = :param2, col3 = :param3 WHERE primary_key = :id;";

$data = array('param1' => $param1, 'param2' => $param2, 'param3' => $param3, 'id' => $id);
$types = array('param1' => \PDO::PARAM_STR, 'param2' => \PDO::PARAM_STR, 'param3' => \PDO::PARAM_INT, 'id' => \PDO::PARAM_INT);

static::$db->prepare($sql, $data, $types)->execute();

It feels a bit cumbersome to specify the data and types in two separate arrays. Is there any way I can improve this?

I could make a SQLParameter class like this:

class SQLParameter {
    public $name;
    public $value;
    public $type;

    public function __construct($name, $value, $type) {
        $this->name = $name;
        $this->value = $value;
        $this->type = $type;
    }
}

But this would make the situation even worse.


texts: Web component design, attribute or content HTML?

texts:
Which one of these web components is designed better?

Option 1 contains an a tag within the custom element.

  <bootstrap-social service="github" size="lg">
    Sign in with Github
  </bootstrap-social>

Option 2 the custom element has an href tag and the inner text is within the element.

  <bootstrap-social service="github" size="lg" href="http://github.com/reggi">
    Sign in with Github
  </bootstrap-social>


texts:
I wrote a "foreach" implementation for std::tuple:

#pragma once

#include <tuple>
/**
 * Callback example:

struct Call{
    float k=0;

    template<typename T, int Index>        // lambda function not efficient than this. Tested -O2 clang, gcc 4.8
    inline void call(T &&t){
        std::cout << t.h << " ; " << "id = " << Index << std::endl;
    }
};
*/

namespace TUPLE_ITERATOR{
    template<typename Tuple, int index, int size>
    struct LOOP{
        template <typename Callback>
        static inline void wind(Tuple&& tuple, Callback&& callback){
            callback.template call<decltype(std::get<index>(tuple)), index> (std::get<index>(tuple));
            LOOP<Tuple, index+1, size>::wind( std::forward<Tuple>(tuple), std::forward<Callback>(callback) );
        }
    };

    template<typename Tuple, int size>
    struct LOOP_BACK{
        template <typename Callback>
        static inline void wind_reverse(Tuple&& tuple, Callback&& callback){
            callback.template call<decltype(std::get<size>(tuple)), size>( std::get<size>(tuple) );
            LOOP_BACK<Tuple, size-1>::wind_reverse( std::forward<Tuple>(tuple), std::forward<Callback>(callback) );
        }
    };

    // stop specialization
    template<typename Tuple, int size>
    struct LOOP<Tuple, size, size> {
        template <typename Callback>
        static inline void wind(Tuple&& , Callback&& ){
            // end
        }
    };
    template<typename Tuple>
    struct LOOP_BACK<Tuple, -1>{
        template <typename Callback>
        static inline void wind_reverse(Tuple&& , Callback&& ){
            // end
        }
    };
}

template<typename Tuple, typename Callback>
static void inline iterate_tuple(Tuple&& tuple, Callback&& callback){
    TUPLE_ITERATOR::LOOP< Tuple, 0, std::tuple_size< typename std::decay<Tuple>::type >::value >
            ::template wind<Callback>( std::forward<Tuple>(tuple), std::forward<Callback>(callback) );
}

template<typename Tuple, typename Callback>
static void inline iterate_tuple_back(Tuple&& tuple, Callback&& callback){
    TUPLE_ITERATOR::LOOP_BACK< Tuple, std::tuple_size< typename std::decay<Tuple>::type >::value-1 >
            ::template wind_reverse<Callback>( std::forward<Tuple>(tuple), std::forward<Callback>(callback) );
}

// Call:
// iterate_tuple(Callback(), std::make_tuple(1,2,3,"asdaa"));

But I look at how other folks do that, and I see that they do this in another way. They get an array of indices, and then recursively call the callback function. Is my implementation worse than that? I ask this because if I call tuple_iterator twice, with the same parameters, the compiler starts to use asm "calls". Look HERE, on the red.

void TUPLE_ITERATOR::LOOP<std::tuple<std::pair<int, Data>,
std::pair<int, Data> >, 0, 2>:


texts:
I have a couple of nested objects, where A is always a part of B.

May I use the following code to access owner's properties and methods?

function A( owner ) {
  this.value = function () { return owner.value() + 1 };
}

function B() {
  this.value = function () { return 1; };
  this.a = new A( this );
}

var b = new B();
alert( b.a.value() );

Actually, it works. But I would like to know whether it is correct or not.


texts: Caret color and movement animation in Swing

texts:
I'm developing a new Look and Feel that is based on animation ,
so I've decided to make animated text caret too !
The caret works as expected every thing is fine except that am worried about how I defined my animation rules in making the babySteps method and repaint in the movementTimer not the caret one but the component one !!

at the installation of the Caret I add PropertyChangeListener witch invokes prepareColorsList if the property is "caretColor" with the new value

private void prepareColorsList(Color c) {
        Color end = reFactorAlphaBy(c, 0);
        ar.clear();
        ar.add(c);
        while (!ColorsEquals(c, end)) {
            ar.add((c = step(c, end)));
        }
    }

ar is a List<Color> and reFactorAlphaBy just returns a new color with same red,green and blue but with the specified int as alpha .
the stepColor just call the babySteps method on each value of the color and return the new color .
I did this because I didn't want to invoke the step method in the timer , am afraid this will be bad practice.

The stepsColor(int from, int to, int max) provide the maximum addition to add it to from to be to but the return will be less than max

public static int babySteps(int from, int to, int max) {
        int ret = 0;
        if (from > to) {
            for (int j = 0; j <= max; j++) {
                if (from >= to + j) {
                    ret = -j;
                } else {
                    break;
                }
            }
        } else if (from < to) {
            for (int j = 0; j <= max; j++) {
                if (from + j <= to) {
                    ret = j;
                } else {
                    break;
                }
            }
        }
        return ret;
    }

I'm afraid of the usage of the for loops (I haven't faced a performance issue with them in any project yet but if this project made it to the light it gonna have a lot of users and i need to predict if it's gonna be issue).

Last thing, it's also about the babySteps as am using it in the movement timer too.
This is a brief explanation of what I am doing:

I have two Rectangle objects: one to draw and the other to get the location of where that drawing rect should go .
I have overridden the setDot method to change the second rect bounds .
The movement timer has an ActionListener that moves the bounds of the first rect to the other one using the babySteps method

@Override
        public void actionPerformed(ActionEvent e) {
            draw.height += babySteps(draw.height, follow.height, 2);
            draw.width += babySteps(draw.width, follow.width, 2);
            draw.x += babySteps(draw.x, follow.x, 2);
            draw.y += babySteps(draw.y, follow.y, 2);
            getComponent().repaint();
        }

Here I am calling the component repaint instead of the class one because the class repaint implementation will repaint the caret rect only witch it will lead in the old carets stick to the screen !!

Am just afraid of the for loops that is inside Timer objects would make an heavy effect to ui and making crashes if the user have a lot of JTextComponent and I don't know even how to predict what will happen.


texts: Use Scrapy to find duplicate images across pages

texts:
I'm trying to use scrapy to find image URLs that are used more than once on a website across all pages.

This is my spider:

# -*- coding: utf-8 -*-
from collections import defaultdict

import scrapy
from scrapy import signals
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class ExampleSpider(CrawlSpider):
    handle_httpstatus_list = [403, 404]
    name = 'Example'
    allowed_domains = ['url.com']
    start_urls = ['http://url.com/']
    custom_settings = {
      'LOG_LEVEL': 'INFO'
    }
    count_image_occurrences = defaultdict(int)

    rules = (
        Rule(LinkExtractor(tags='a', attrs='href', unique=True),
             callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        # Remember images.
        for image in response.xpath('//img/@src').extract():
            self.count_image_occurrences[image] += 1

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        spider = super(ExampleSpider, cls).from_crawler(crawler, *args, **kwargs)
        crawler.signals.connect(spider.spider_closed,
                signal=signals.spider_closed)

        return spider

    def spider_closed(self, spider):
        spider.logger.info(self.count_image_occurrences)

Is there a more (speed / memory / code length) efficient way to do this?


texts:
I was following this tutorial from official python documentation site, but found its examples quite simplistic, so I've built my own wrapper.
It does what I intend it to do, but I wonder if this code is good or how it can be improved.

app.h

#pragma once

#include <iostream>
#include <string>

#include <Python.h>

class App {
public:
  App();
  ~App();

  void Run();

private:
  static const std::string PY_CLASS_NAME;
  static const std::string PY_MODULE_NAME;

  static std::string _GetString(PyObject* obj);

  PyObject* _counter;
};

app.cc

#include "app.h"

const std::string App::PY_CLASS_NAME = "Counter";
const std::string App::PY_MODULE_NAME = "lib";

App::App() {
  Py_SetProgramName(Py_DecodeLocale("App", NULL));
  Py_Initialize();
  PyRun_SimpleString("import sys");
  PyRun_SimpleString("sys.path.append(\".\")");

  PyObject* name = PyUnicode_DecodeFSDefault(PY_MODULE_NAME.data());
  PyObject* module = PyImport_Import(name);

  PyObject* consturctor = PyObject_GetAttrString(module, PY_CLASS_NAME.data());
  _counter = PyObject_CallObject(consturctor, NULL);
  std::cout << _GetString(_counter) << "\n";

  Py_XDECREF(consturctor);
  Py_XDECREF(module);
  Py_XDECREF(name);
}

App::~App() {
  Py_Finalize();
}

void App::Run() {
  PyObject* res;
  for (auto i=0; i<10; i++) {
    PyObject_CallMethod(_counter, "Inc", NULL);
    res = PyObject_CallMethod(_counter, "GetValue", NULL);
    std::cout << _GetString(res) << "\n";
  }
  PyObject_CallMethod(_counter, "Drop", NULL);
  res = PyObject_CallMethod(_counter, "GetValue", NULL);
  std::cout << _GetString(res) << "\n";
}

std::string App::_GetString(PyObject* obj) {
  PyObject* repr = PyObject_Repr(obj);
  PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~");
  const char* bytes = PyBytes_AS_STRING(str);

  Py_XDECREF(repr);
  Py_XDECREF(str);
  return std::string(bytes);
}

lib.py

class Counter(object):
    def __init__(self):
        super().__init__()

        self._c = 0

    def __repr__(self):
        return "Simple Counter" + str(self._c)

    def Drop(self):
        self._c = 0

    def GetValue(self):
        return str(self._c)

    def Inc(self):
        self._c += 1


texts: Re-arrange a string into a { consonant, vowel, consonant, vowel ... } sequence

texts:
I was prompted to give someone advice about the following problem:

Given a string with equal amount of vowels and consonants, re-arrange it so that it follows the sequence { consonant, vowel, consonant, vowel, ... }
For Example given "abed" modify it to be "bade".  The order of the vowels and consonants must be the same, "dabe" nor "beda" are acceptable answers.

It was a "first year" type question, no std::string, no strlen, no copying the characters somewhere else, ...

Anyway, I came up with this.  Basically, while iterating through the string, if the character isn't what we're looking for, move another pointer forward until it finds one.  Once found, store it and then shift each character one to the right to make space for the character that we want:

#include <iostream>

bool isVowel( const char ch )
{
  return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

void rearange( char *str )
{
  bool on_consonant = true;

  while ( *str )
  {
    bool is_vowel = isVowel( *str );

    if ( ( on_consonant && is_vowel ) || ( !on_consonant && !is_vowel ) )
    {
      char *ptr = str + 1; // we don't get here with a valid string
      while ( isVowel( *ptr ) == is_vowel )
        ++ptr;

      // ptr now points to the first type we are looking for
      char swap = *ptr;

      // move each character up the line
      while ( ptr != str )
      {
        *ptr = *( ptr - 1 );
        --ptr;
      }

      *str = swap;

    }
    ++str;
    on_consonant = !on_consonant;
  }

}

int main( int argc, char *argv[] )
{
  if ( argc != 2 )
  {
    std::cout << "please enter a valid string as an argument\n";
    return 0;
  }

  std::cout << argv[1] << '\n';
  rearange( argv[1] );
  std::cout << argv[1] << '\n';

  return 0;
}

I realize that the \$O\$ notation of this isn't very good, we are going to be going back and forth across this string many times.  I really couldn't think of a better way to do it with the constraints that were given.  I was trying to do it in linear time, but the problem is that you never know how far forward the correct character will be and it is possible to overwrite data that hasn't even been looked at.

I offered another solution, which I do believe is linear \$( 2 * n )\$, using no constraints.

void rearange( std::string& str )
{
  std::vector< char > vowels( str.length() / 2 );
  std::vector< char > consonents( str.length() / 2 );

  size_t v_idx = 0;
  size_t c_idx = 0;

  for ( char ch : str )
    isVowel( ch ) ? vowels[ v_idx++ ] = ch : consonents[ c_idx++ ] = ch ;

  str.clear();
  for ( size_t i = 0; i < consonents.size(); ++i )
  {
    str += consonents[i];
    str += vowels[i];
  }
}

Am I correct that this is a linear operation?  Are there any other ideas that could speed this up?  ( Though, I'm not too worried about it, it currently takes twice as long to even make the random string ).


texts: Given a date and a duration, calculate the future date

texts:
The question is basically like this:
Given year, month, day and duration, calculate the future date based on given data and duration. The given date guarantees to be after 1900-01-01, and the duration k is between [0, 10000].

For example:
Input:
2016 10 1 100(meaning given 2016-10-1, what is the future date after 100 days)
Output:
2017-01-09

Another example:
Input:
2017 1 1 10
Output:
2017-01-11

I have done my solution, but it is trivial and ugly. The most frustrating part is line 44 - 47, where I have to handle special cases on month and year. I feel like this special and trivial handling is due to my design of calculating month, but I cannot figure out a more universal/clear solution except for current solution.

Love to hear your advice! Thank you!

Code with line indication and better format fyi : https://paste.ubuntu.com/24765263/

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std; // I know global namespace is bad practice. Just to save time.

int getMonthDays(int y, int m){
    unordered_map <int, int >daysMap = {{1,31}, {2,28}, {3,31}, {4,30}, {5,31}, {6,30}, {7,31}, {8,31}, {9,30}, {10,31}, {11,30}, {0,31}};
    if (m == 2){
        if (y % 400 ==0 || (y % 100 != 0&& y % 4 == 0)){
            return 29;
        }
        else{
            return 28;
        }
    }
    else{
        return daysMap[m];
    }
}

int main (){

    int year, month, day, duration;
    cin >> year >> month >> day >> duration;

    int res_year;
    string res_month, res_day;

    int days = getMonthDays(year, month) - day;
    while ( days < duration ){
        month++;
        if(days + getMonthDays(year + month/12, (month - 12 * (month/13))% 12) > duration){
            break;
        }
        else{
            days += getMonthDays(year + month/12, (month - 12 * (month/13))% 12);
        }

    }

    res_year = year + month / 12 ;
    res_month = (month - 12 * (month/13))% 12 >= 10 ? to_string((month - 12 * (month/13))% 12) : "0" + to_string((month - 12 * (month/13))% 12);
    if (res_month == "00"){
        res_month = "12"; // dont have set month "12", so if get month as "00", convert it to "12"
        res_year -= 1; // if the result month is "12", year minus 1 coz Month December is still in this year.
    }

    if (duration - days > 0 ){
        if (duration - days >= 10){
            res_day = to_string(duration - days);
        }
        else{
            res_day = "0" + to_string(duration - days);
        }
    }
    else{
        res_day = to_string(day + duration);
    }
    cout << res_year << "-" << res_month << "-" << res_day;

}


texts:
I wrote this converter code. It can convert a number from 1-100 into words. It works perfectly, but it seems to be too complicated to me.

Can you tell me whether it's okay or not?

#include <iostream>

int main()
{
    int number;
    int first_digit;
    int second_digit;
    std::cout << "Enter the number: ";
    std::cin >> number;
    first_digit = number/10;
    second_digit = number%10;
    if(number >= 11 && number <= 20)
    {
        switch(number)
        {
            case 11:
                std::cout<<"eleven";
                break;

            case 12:
                std::cout<<"twelve";
                break;
            case 13:
                std::cout<<"thirteen";
                break;
            case 14:
                std::cout<<"fourteen";
                break;
            case 15:
                std::cout<<"fifteen";
                break;
            case 16:
                std::cout<<"sixteen";
                break;
            case 17:
                std::cout<<"seventeen";
                break;
            case 18:
                std::cout<<"eighteen";
                break;
            case 19:
                std::cout<<"nineteen";
                break;
        }
    }
    else
    {
        switch(first_digit)
        {
            case 1:
                if(second_digit == 0)
                    std::cout<<"ten";
                break;
            case 2:
                std::cout<<"twenty";
                break;
            case 3:
                std::cout<< "thirty";
                break;
            case 4:
                std::cout<<"fourty";
                break;
            case 5:
                std::cout<<"fifty";
                break;
            case 6:
                std::cout<<"sixty";
                break;
            case 7:
                std::cout<<"seventy";
                break;
            case 8:
                std::cout <<"eighty";
                break;
            case 9:
                std::cout <<"ninety";
                break;
            case 10:
                std::cout <<"one hundred";
                break;
        }
        if(first_digit > 1 && number != 100) std::cout<<"-";
        switch(second_digit)
        {
            case 1:
                std::cout<<"one";
                break;
            case 2:
                std::cout<<"two";
                break;
            case 3:
                std::cout<<"three";
                break;
            case 4:
                std::cout<<"four";
                break;
            case 5:
                std::cout<<"five";
                break;
            case 6:
                std::cout<<"six";
                break;
            case 7:
                std::cout<<"seven";
                break;
            case 8:
                std::cout<<"eight";
                break;
            case 9:
                std::cout<<"nine";
                break;
            default:
                break;

        }
    }
    return 0;
}


texts: Speeding up loop-rich Matlab function to calculate temperature distribution

texts:
I would like to speed up this function as much as possible in Matlab.
This is part of a bigger simulation project, and as it is one of the most called functions within the simulation, this is crucial.

For now, I tried generating a MEX file, but the speed was not better.

Vectorizing seems difficult (but would be beneficial due to the nested loops), given the non-linear operations.

What I'm trying to compute with this is the degree of temperature mixing between water layers, given by these equations:

$$\begin{align}
T_j =&\ r\ T_{j+1} + (1-r)\ T_j\quad&\textrm{for } j \in [i,\ i+\Delta i]\\
T_{j+1} =&\ (1-r)\ T_{j+1} + r\ T_j
\end{align}$$

and \$n\$ is the total number of water layers. This must be calculated for all \$j\$, this is for all the layers, at all timesteps.

function y = mixing(T,dis,rr,n)
%% ===================================================================
%  input: temperature of cells array T, distance array dis, number of cells
%         n, mixing ratio r
%
%  output:  new temperature array
%
%  purpose: calculates the temperature array of next timestep
%  ===================================================================

for j = 1:n
    i = 1;
    r = rr;
    while i < dis(j)+1 && j+i <= n
        if (dis(j) < i)
            r = r*(dis(j)-floor(dis(j)));
        end
        d = T(j+i-1);
        T(j+i-1) = r*T(j+i) + (1-r)*T(j+i-1);
        T(j+i) = r*d + (1-r)*T(j+i);
        i = i + 1;
    end
end

y = T;
end

Inputs: T is a 10 × 1 double, dis is a 10 × 1 double, rr is a 1 × 1 double, and n is a 1 × 1 integer value.


texts: Program for activity selection exceeds time limit

texts:
I've been trying to solve this problem for some while and the solution I have come up with exceeds the lime limit by 1-3 ms and 2 out of 10 tests get a memory issue error. Why is that? This is the code for my solution:

#include <fstream>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

ifstream in("planificare.in");
ofstream out("planificare.out");

struct show {
    int start, finish, used = 0;
};

bool end_time (show lhs, show rhs) {
    if (lhs.finish == rhs.finish) return lhs.start < rhs.start;
    return lhs.finish < rhs.finish;
}

int main() {
    int participants, tv_chan;
    vector<show> prog;
    in >> participants >> tv_chan;
    for (int i = 1; i <= participants; i++) {
        show a;
        in >> a.start >> a.finish;
        prog.push_back(a);
    }
    sort(prog.begin(), prog.end(), end_time);
    int maxActivities = 0;
    int unused = 0;
    for (int i = 1; i <= tv_chan; i++) {
        while (prog[unused].used)
            unused++;
        int lastFinish = prog[unused].finish;
        prog[unused].used = 1;
        maxActivities ++;
        for (int j = 0; j < prog.size(); j++) {
            if (prog[j].start >= lastFinish && prog[j].used == 0) {
                maxActivities++;
                lastFinish = prog[j].finish;
                prog[j].used = 1;
            }
        }
    }
    out << maxActivities;
}

Planificare - InfoArena

  Talent Day is coming soon at the Blomkvist TV channel and the CEO Mike
  needs you to make the program grid. \$N\$ participants have enrolled
  to expose their talents, each communicating the amount of time it
  needs. Mike's TV Chain consists of \$K\$ stations, (Blomkvist 1, Blomkvist 2,
  ... Blomkvist K) that transmit independently of each other. Due to the
  fact that all \$K\$ stations are all just as popular as the other, the participants are indifferent
  to which they will appear.

  Knowing that at any given moment any station
  will broadcast a single show, determining the maximum number of shows
  that can be televised.

  Input data

  The input file planificare.in will contain on the first line \$2\$ natural numbers: \$N\$
  and \$K\$. On each of the following \$N\$ lines there will be 2 values,
  the starting time and the end time, representing the time interval during which the
  participant performs its activity.

  Output data

  The output file planificare.out will contain the number requested by Mike on
  the first line.

  Restrictions and clarifications

  \$1 \le N \le 100,000\$

  \$1 \le K \le 100,000\$

  \$1 \le \text{start}_i \le \text{stop}_i \le 1,000,000,000\$

  Time limit: 0.2 seconds

  For 30% of the tests, \$N\$ ≤ 2000 and for another 10% of the tests, \$K\$ = 1.
     At each channel, a show can start at the same time that the previous one is over.

  Example

  planificare.in

2 1
1 4
4 8

  planificare.out

2


texts:
I've written a function to prettify a json object, as if it were using JSON.stringify.

I'm only focused on strings and other objects, nothing else.

Is there a better way of doing this? perhaps using a data structure?

const exampleJson = {"name":"Jon","facts":{"car":"Ford","address":{"city":"New York"},"watch":"Casio","other": {}}};

function prettyPrint(data) {
  let tabbify = n => Array(n).fill(' ').join('');

  let traverse = (data, tab = 1) => {
    let output = "",
        open   = `{\n`,
        close  = `\n${tabbify(tab - 1)}}`;

    output += open;

    Object.entries(data).forEach(([key, val], i, {length}) => {
      if (typeof val === 'string') {
        output += `${tabbify(tab)} "${key}": "${val}"`;
      } else if (typeof val === 'object') {
        if (Object.keys(val).length > 0) {
          output += `,\n${tabbify(tab)} "${key}": ${traverse(val, tab+2)}${i === length - 1 ? '' : ',\n'}`;
        } else {
          output += `,\n${tabbify(tab)} "${key}": {}`;
        }
      }
    })

    output += close;
    return output;
  }

  return traverse(data);
}

Output

{
    "name": "Jon",
    "facts": {
        "car": "Ford",
        "address": {
            "city": "New York"
        },
        "watch": "Casio",
        "other": {}
    }
}


texts:
I have written this function to perform a binary search on an array, given begin/end indices and a value to look for in the supplied array:

def binarySearch(array, beginIndex, endIndex, value):
    while (beginIndex < endIndex):
        mid = (beginIndex + endIndex) / 2
        if array[mid] < value:
            beginIndex = mid + 1
        elif array[mid] > value:
            endIndex = mid - 1
        else: #equal
            return mid

    if array[beginIndex] == value:
        return beginIndex
    else:
        return -1

Test cases / output:

print binarySearch([2,3], 0, 1, 2)
 0
print binarySearch([2,3], 0, 1, 3)
 1
print binarySearch([2,3], 0, 1, -1)
-1
print binarySearch([2,3,3,3,4,5], 0, 5, 3)
 2

So it works as intended. I'm interested in feedback mostly from a functional perspective, but I'm open to anything else that might catch your eye.


texts: Custom exception for each invalid input value

texts:
I have backend project in which there's own "parent-to-all exception" exists, something like this (also I have InvalidArgumentException derived from this exception):

class CaliException extends \Exception {
    private $caliCode;

    public function __construct(string $message = "", string $caliCode = self::UNDEFINED_CODE,
                                int $code = 0, Throwable $previous = null) {
        parent::__construct($message, $code, $previous);

        $this->caliCode = $caliCode;
    }

    function getCaliCode(): string {
        return $this->caliCode;
    }
}

It's clear from code above, that purpose of custom class is ability to keep string codes. Why do I need string codes? Because I have HTTP API which works in the following way:

Get JSON request
Do something
Produce JSON output with 'state' field which contains either code of a thrown exception or the "200" response. These state codes are quite useful for client which can distinguish different problems and react to them accordingly.

So there's a problem. System above produces code like this:

class UsernameFormatException extends InvalidArgumentException {
    public const USERNAME_FORMAT_UNDEFINED_CODE = "DM:USERCA:0001";

    public function __construct(string $message = "", string $calistoCode = self::USERNAME_FORMAT_UNDEFINED_CODE,
                                int $code = 0, \Throwable $previous = null) {
        parent::__construct($message, $calistoCode, $code, $previous);
    }
}

class PasswordFormatException extends InvalidArgumentException {
    public const PASSWORD_FORMAT_UNDEFINED_CODE = "DM:USERCA:0002";

    public function __construct(string $message = "", string $calistoCode = self::PASSWORD_FORMAT_UNDEFINED_CODE,
                                int $code = 0, \Throwable $previous = null) {
        parent::__construct($message, $calistoCode, $code, $previous);
    }
}

class InvalidLastActivityTimestampException extends InvalidArgumentException {
    public const INVALID_TIMESTAMP = "DM:USERCA:0003";

    public function __construct(string $message = "", string $calistoCode = self::INVALID_TIMESTAMP,
                                int $code = 0, \Throwable $previous = null) {
        parent::__construct($message, $calistoCode, $code, $previous);
    }
}

class InvalidCreationTimestampException extends InvalidArgumentException {
    public const INVALID_TIMESTAMP = "DM:USERCA:0004";

    public function __construct(string $message = "", string $calistoCode = self::INVALID_TIMESTAMP,
                                int $code = 0, \Throwable $previous = null) {
        parent::__construct($message, $calistoCode, $code, $previous);
    }
}

As seen, for each invalid-argument-case I create new CaliException-derived exception. I consider it as not cool. Is it good? How can I improve the code?

Bonus question: I read that I should throw \InvalidArgumentException when it's a programmer's mistake, so an exception must be not caught. But in my code there's no \InvalidArgumentException only my own version of this. Is it acceptable in the context of best practices and so on? And how to distinguish when it's a programmer's mistake and when it's mistake of user (invalid user input)? (After all, any invalid values passed to a function are invalid inputs relatively to this function)


texts: Should this container be a struct or a class?

texts:
I have a class that serves purely as a data container for passing values from a parsing class to a class responsible for saving the data. I have been wondering whether it would be more appropriate as a struct. The class definition is below.

internal class DataContainer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public Guid PersonId { get; set; }

    public string Address { get; set; }

    public string PhoneNumber { get; set; }

    public string Sensor1Name { get; set; }

    public IEnumerable<Tuple<double?, int>> Sensor1Readings { get; set; }

    public string Sensor2Name { get; set; }

    public IEnumerable<Tuple<double?, int>> Sensor2Readings { get; set; }
}

The parser uses an iterator block to turn a large csv file into approximately 6000 DataContainers. As they are created, each DataContainer is passed to the SaveContainer. The SaveContainer immediately reads the values and discards each object. Finally, the SaveContainer saves all the values to the database:

internal class FileParser
{
    // Much yak shaving...

    private IEnumerable<DataContainer> GetFileData()
    {
        using (StreamReader readFile = new StreamReader(this.FilePath))
        {
            string tableData = null;
            while ((tableData = readFile.ReadLine()) != null)
            {
                var sensor1Data = readFile.ReadLine();
                var sensor2Data = readFile.ReadLine();

                DataContainer currentData = this.CreateDataContainer(tableData, sensor1Data, sensor2Data);
                yield return currentData;
            }
        }
    }

    private void CollectData()
    {
        SaveContainer saveContainer = new SaveContainer();
        foreach (var data in this.GetFileData())
        {
            saveContainer.AddData(data);
        }

        saveContainer.Save();
    }
}

I have read Microsoft's Choosing Between Class and Struct guidelines and I think that I mostly understand them (enough to say that this type does not meet the qualifications). I've also read some related Stack Overflow answers including this and this. They seem to offer a wide variety of opinions on the matter.

I have no specific need to change the type definition, but its use is so particular and basic that a class seems unnecessarily complex. Would changing this class to a struct offer any compelling advantages or disadvantages?


texts: Tic-Tac-Toe code using Python with Tkinter

texts:
`I made this Tic-Tac-Toe game first, by using user input in the console here:
https://pastebin.com/6zLjrWcf
, and now new and improved using Tkinter:

import tkinter as tk
from tkinter import ttk
import time

def create_button(relx, rely):
    button = tk.Button(width=10, height=2, command=lambda: callback(button))
    button.place(relx=relx, rely=rely)
    return button

def check_win():
    if (buttons[0]['text'] == buttons[1]['text'] == buttons[2]['text'] != '') or \
            (buttons[3]['text'] == buttons[4]['text'] == buttons[5]['text'] != '') or \
            (buttons[6]['text'] == buttons[7]['text'] == buttons[8]['text'] != '') or \
            (buttons[0]['text'] == buttons[3]['text'] == buttons[6]['text'] != '') or \
            (buttons[1]['text'] == buttons[4]['text'] == buttons[7]['text'] != '') or \
            (buttons[2]['text'] == buttons[5]['text'] == buttons[8]['text'] != '') or \
            (buttons[2]['text'] == buttons[4]['text'] == buttons[6]['text'] != '') or \
            (buttons[0]['text'] == buttons[4]['text'] == buttons[8]['text'] != ''):
        return True
    else:
        return False

def callback(button):
    global turn, x
    if x == 1:
        time.sleep(1)
        game.quit()
    invalid['text'] = ''
    if button['text'] != '':
        invalid['text'] = 'Invalid space try again'
        return
    button['text'] = turn
    if check_win():
        invalid['text'] = 'Player ' + turn + ' WINS!!!!!'
        x = 1
    turn = ('0' if turn == 'X' else 'X')
    label_button['text'] = 'PLAYER ' + turn + '\'S TURN.'

x = 0
turn = 'X'
game = tk.Tk()
game.title('TicTacToe')
game.geometry('700x500')
buttons = []
for i in range(1, 10):
    button_created = create_button(0.25 if i / 3 <= 1 else 0.45 if i / 3 <= 2 else 0.65, 0.2 if i in [1, 4, 7] else
                                   0.4 if i in [2, 5, 8] else 0.6)
    buttons.append(button_created)
label_button = ttk.Button(game, text='PLAYER ' + turn + '\'S TURN.', style='Fun.TButton', width=20, state='disabled')
label_button.pack(pady=30)
invalid = tk.Label(text='')
invalid.place(relx=0.4, rely=0.12)
game.mainloop()

My main question is if there is a way to compact check_win()?
Also please review the rest of the code.


texts: Factor script to change case of all filenames in a directory

texts:
In the absence of a full-fledged tutorial, I am teaching myself to program in the Factor language by writing a bunch of functions that I will eventually use in command-line scripts.

One common operation I like to perform is to change the case of names of files contained in a given directory to uppercase or lowercase.  I wrote the following code to perform this operation in Factor:

USING: fry kernel io.directories sequences unicode.case ;
IN: util.directories

: move-each-directory-file>lower ( pathname -- )
    [ dup >lower ] move-each-directory-file ;

: move-each-directory-file>upper ( pathname -- )
    [ dup >upper ] move-each-directory-file ;

: each-directory-file ( pathname quot -- )
    '[ [ @ ] each ] with-directory-files ; inline

: move-each-directory-file ( pathname quot -- )
    '[ @ move-file ] each-directory-file ; inline

I have tried to factor as much code as possible into a reusable vocabulary.  I look forward to suggestions for improvement.


texts:
I've developed a small memory game, the game contains a function to flip cards for every turn. I'm looping thru the array containing the images every time to pick one card. I'm sure there's away to optimize this function so I don't have to loop through the array every time in order to just turn one card. But I'm a bit clueless how to proceed and would like to get some guidance of how I possibly could optimize this function with vanilla javascript and without objects.

function flipCards() {
  var i; // Loopvariabel

  // For loop
  for (i = 0; i < cardsElems.length; i++) {
    if (this == cardsElems[i]) {
      if (cardsCounter > 1) {
        return;
      }

      cardsElems[i].className = "brickFront";
      cardsElems[i].src = "pics/" + allCards[i] + ".png";
      removeListener(cardsElems[i], "click", flipCards);
      if (cardsCounter < 1) {
        card1 = i;
      } else {
        card2 = i;
      }
      cardsCounter += 1;
    }
  }

  if (cardsCounter < 2) {
    nextBtn.disabled = true; // Avaktivera knapp
  }

  if (cardsCounter == 2) {
    turns += 1;
    turnNr.innerHTML = turns;
    nextBtn.disabled = false; // Aktivera knapp
  }

  if (brickBack.length == 0) {
    endGame();
  }
} // End flipCards


texts:
I've written a method to render a polygon in C# using the SharpDX libraries and would like a review of my code's maintainability and the documentation around it. The method works fine as is, but I feel that perhaps the documentation could be improved, or that there could be simpler and more maintainable method of executing the algorithm.

/// <summary>
/// Render an n-sided polygon from a list of allowed polygons.
/// </summary>
/// <param name="context2D">The 2D context used to render the polygon.</param>
/// <param name="polygon">The n-sided polygon to render.</param>
/// <param name="center">The central position of the polygon in 2D space</param>
/// <param name="radius">The radius of the polygon.</param>
/// <param name="rotation">The global rotation of the polygon (in degrees).</param>
public void RenderPolygon(DeviceContext context2D, PolygonType polygon, Vector2 center, float radius, float rotation) {
    float numberOfPoints = (float)polygon;
    Vector2? firstPoint = null, previousPoint = null, currentPoint = null;
    for (int n = 0; n < numberOfPoints; n++) {
        float theta = ((360.0f / numberOfPoints) * n + rotation) * (float)Math.PI / 180.0f;
        currentPoint = center + new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * radius;

        if (previousPoint != null && currentPoint != null)
            context2D.DrawLine((Vector2)previousPoint, (Vector2)currentPoint, brush);

        previousPoint = currentPoint;
        if (firstPoint == null)
            firstPoint = currentPoint;
    }

    if (firstPoint != null && currentPoint != null)
        context2D.DrawLine((Vector2)currentPoint, (Vector2)firstPoint, brush);
}

With regards to the PolygonType argument, this is an enum with int values for each type; for example:

public enum PolygonType {
    Trigon = 3,
    Tetragon = 4,
    Pentagon = 5
}

There are a total of 30 polygon types offered stopping at Chiliagon which has 1000 sides.

The things I am most interested in are:

Ensuring documentation provides as much detail as possible (while remaining concise).
Ensuring that the algorithm is easy to follow and maintain.

The one thing I don't currently like about the algorithm:

Casting from Vector2? to Vector2 seems redundant (though required in the current case).

Since Vector2's default value is 0, 0, I'm not sure I should use it and have chosen to use null; but since Vector2 is not a nullable type, I have to cast back to the normal Vector2 prior to using my variables.


texts: jQuery conditional statement to check if a select option has either of 4 values selected

texts:
I am working on this project that has a reservation form which allow users specify which sort of service they require. I have a select menu with eight (8) options and I have two divs which would either show/hide depending on the value of the option been selected. Seen below is the select element:

<select name="serviceChoice" id="serviceChoice">
  <option value="A">Option A</option>
  <option value="B">Option B</option>
  <option value="C" selected="selected">Option C</option>
  <option value="D">Option D</option>
  <option value="E">Option E</option>
  <option value="F">Option F</option>
</select>

I have several form fields

I have several form fields

I have written my jQuery code to alternate between these divs, however I would like to know if there is a shorter better way to get this done. I would also like to clear the values of any input elements in a div which has been hidden due to the choice of the user. My code is as follows:

(function($){
    $('#field_1').show();
    $('select[name=serviceChoice]').change(function(){
        if( $('select[name=serviceChoice] option:selected').val() == 'A' ) {
            $('.optionBox').hide();
            $('#dropOff').show();
        } else if ( $('select[name=serviceChoice] option:selected').val() == 'B' ) {
            $('.optionBox').hide();
            $('#pickUp').show();
        } else if ( $('select[name=serviceChoice] option:selected').val() == 'C' ) {
            $('.optionBox').hide();
            $('#pickUp').show();
        } else if ( $('select[name=serviceChoice] option:selected').val() == 'D' ) {
            $('.optionBox').hide();
            $('#pickUp').show();
        } else {
            $('.optionBox').show();
        }
    });
})(jQuery);


texts:
I'm using Java 7.

private Long difference;
public Long timeDifference(String weboutput) {
    try {
        Calendar calendar = GregorianCalendar.getInstance();
        Calendar today = new GregorianCalendar();
        Date inputTime;
        if (weboutput.length() <= 11) { // for data fetched for current date.
            DateFormat formatter = new SimpleDateFormat("hh:mm:ss a", Locale.US);
            inputTime = formatter.parse(weboutput);
            calendar.setTime(inputTime);
            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            today.setTime(new Date());
            today.set(Calendar.HOUR, hour);
            today.set(Calendar.MINUTE, minute);
            today.set(Calendar.SECOND, second);
        } else {
            if (weboutput.length() <= 15) { // for data for earlier date in same year or month.
                DateFormat formatter = new SimpleDateFormat("MMM dd hh:mm a", Locale.US);
                inputTime = formatter.parse(weboutput);
                calendar.setTime(inputTime);
                int hour = calendar.get(Calendar.HOUR);
                int minute = calendar.get(Calendar.MINUTE);
                int month = calendar.get(Calendar.MONTH);
                int date = calendar.get(Calendar.DATE);
                today.setTime(new Date());
                today.set(Calendar.HOUR, hour);
                today.set(Calendar.MINUTE, minute);
                today.set(Calendar.MONTH, month);
                today.set(Calendar.DATE, date);
            } else { // for data with different year.
                DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
                inputTime = formatter.parse(weboutput);
                calendar.setTime(inputTime);
                int hour = calendar.get(Calendar.HOUR);
                int minute = calendar.get(Calendar.MINUTE);
                int second = calendar.get(Calendar.SECOND);
                int month = calendar.get(Calendar.MONTH);
                int date = calendar.get(Calendar.DATE);
                int year = calendar.get(Calendar.YEAR);
                today.setTime(new Date());
                today.set(Calendar.HOUR, hour);
                today.set(Calendar.MINUTE, minute);
                today.set(Calendar.SECOND, second);
                today.set(Calendar.YEAR, year);
                today.set(Calendar.MONTH, month);
                today.set(Calendar.DATE, date);
            }
        }
        Date retrivedDate = today.getTime();
        Calendar cal = Calendar.getInstance();
        Date currentDate = cal.getTime();
        difference = currentDate.getTime() - retrivedDate.getTime();
        System.out.println(retrivedDate);
        System.out.println(currentDate);
        System.out.println(difference);

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return difference;
}

public boolean alarmValue(Long alarmTime) {
    if (alarmTime <= 1800000) // change this value for Alarm duration, currently 30 min = 30* 60 s = 1800 * 1000 ms = 1800000 ms.
        return false;
    else
        return true;
}


texts:
Working through CodeEval's Interrupted Bubble Sort, I have a working algorithm, but there's a speed issue.  I'm trying to do this with Ruby and I keep getting an error that it's timing out after 10 seconds.  I'm not sure what else I could be doing here to speed things up.

def bubble(arr, interrupt)

    i = 0
    while i < interrupt
        for x in 1..arr.length-1
            if arr[x-1] > arr[x]
                arr[x-1], arr[x] = arr[x], arr[x-1]
            end
        end
        i += 1
    end

end

File.open(ARGV[0]).each_line do |line|

    line = line.chomp.split(" ");
    interrupt = line.pop.to_i
    line.pop

    line.map do |x| x = x.to_i end
    bubble(line, interrupt)
    puts line.join(" ")

end


texts: Scraping GitHub for security vulnerabilities

texts:
I haven't done much Python programming, but I really like the language so I've been using it for side projects that I work on.  The problem with this is that I don't have the opportunity to have my peers review my code and give suggestions.

I've been working on a project that will be scraping GitHub looking for security vulnerabilities.  I've created a separate file in the project that contains all functions that interact with GitHub's API.

import requests
import re
import base64
import os

def getRepos(since=0):
  url = 'http://api.github.com/repositories'
  data = """{
    since: %s
  }""" % since
  response = requests.get(url, data=data)
  if response.status_code == 403:
    print "Problem making request!", response.status_code
    print response.headers
  matches = re.match(r'<.+?>', response.headers['Link'])
  next = matches.group(0)[1:-1]
  return response.json(), next

def getRepo(url):
  response = requests.get(url)
  return response.json()

def getReadMe(url):
  url = url + "/readme"
  response = requests.get(url)
  return response.json()

# todo: return array of all commits so we can examine each one
def getRepoSHA(url):
  # /repos/:owner/:repo/commits
  commits = requests.get(url + "/commits").json()
  return commits[0]['sha']

def getFileContent(item):
  ignoreExtensions = ['jpg']
  filename, extension = os.path.splitext(item['path'])
  if extension in ignoreExtensions:
    return []
  content = requests.get(item['url']).json()
  lines = content['content'].split('\n')
  lines = map(base64.b64decode, lines)
  print 'path', item['path']
  print 'lines', "".join(lines[:5])
  return "".join(lines)

def getRepoContents(url, sha):
  # /repos/:owner/:repo/git/trees/:sha?recursive=1
  url = url + ('/git/trees/%s?recursive=1' % sha)
  # print 'url', url
  response = requests.get(url)
  return response.json()

The code is run from here:

import github
import json

def processRepoContents(repoContents):
  # for each entry in the repo
  for tree in repoContents['tree']:
    contentType = tree['type']
    print 'contentType --- ', contentType
    # if type is "blob" get the content
    if contentType == 'blob':
      github.getFileContent(tree)
      print '***blob***'
    elif contentType == 'tree':
      print '***tree***'
      # if type is "tree" get the subtree

if __name__ == '__main__':
  repos, next = github.getRepos()
  for repo in repos[0:10]:
    # repoJson = github.getRepo(repo['url'])
    sha = github.getRepoSHA(repo['url'])
    repoJson = github.getRepoContents(repo['url'], sha)
    processRepoContents(repoJson)

I was hoping to get some feedback as to whether or not I am doing anything that would be considered not a best practice.

Also - I have all these functions in a file called github.py and I then include it by using import github wherever I need it.  I'm assuming that it would not make sense to create a class to wrap these functions, since there is never any state for the class to keep track of that the functions would require.  Does this reasoning make sense or should I wrap these functions in a class?

If anyone is interested they can see all of the code in the repo here - I would love to get feed back on the rest of the code (there isn't much more), but didn't think it would all fit in this question.


texts: Loading settings from a file to a dictionary

texts:
Today I coded a class to get settings from a file and to load them in to a dictionary.

Please post and feedback, improvements and changes, no matter how big or small, as long as they are actual improvement and not disadvantages.

using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Sahara.Application.Base.Core.Settings
{
    class Settings
    {
        /// <summary>
        /// Holds a list of settings.
        /// </summary>
        private Dictionary<string, string> allSettings;

        /// <summary>
        /// log4net instance
        /// </summary>
        private ILog myLogger;

        /// <summary>
        /// syncRoot object
        /// </summary>
        private object syncRoot;

        /// <summary>
        /// Creates a new instance of Settings
        /// </summary>
        public Settings()
        {
            allSettings = new Dictionary<string, string>();
            myLogger = LogManager.GetLogger(typeof(Settings));
            syncRoot = new object();

            if (!loadSettings("settings.ini"))
                throw new Exception("Failed to load settings.");
        }

        /// <summary>
        /// Loads the settings from the settings file
        /// </summary>
        /// <param name="file">Settings file path</param>
        /// <returns>bool loadSettings</returns>
        private bool loadSettings(string file)
        {
            try
            {
                allSettings.Clear();

                lock (syncRoot)
                {
                    allSettings = File.ReadLines(file)
                    .Where(isValidLine)
                    .Select(line => line.Split('='))
                    .ToDictionary(line => line[0], line => line[1]);
                }

                return true;
            }
            catch (Exception exception)
            {
                myLogger.Error(exception);
                return false;
            }
        }

        /// <summary>
        /// Checks if the line is a comment.
        /// </summary>
        /// <param name="line">Line to check</param>
        /// <returns>bool isValidLine</returns>
        private bool isValidLine(string line)
        {
            return !line.StartsWith("#") && line.Contains("=");
        }

        /// <summary>
        /// Returns a setting with the specified key.
        /// </summary>
        /// <param name="key">Key to search for</param>
        /// <returns>Setting</returns>
        public string getSetting(string key)
        {
            if (allSettings == null)
                throw new NotImplementedException("Config data has not get been implemented.");

            lock (syncRoot)
                return this.allSettings[key];
        }
    }
}


texts:
I'm trying to do Project Euler Problem 12, which reads as:

  The sequence of triangle numbers is generated by adding the natural
  numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7
  = 28. The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

  1: 1

  3: 1,3

  6: 1,2,3,6

  10: 1,2,5,10

  15: 1,3,5,15

  21: 1,3,7,21

  28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have over five
  divisors.

  What is the value of the first triangle number to have over five
  hundred divisors?

My code is as follows:

import math
from time import time
t = time()
def divisors(n):
    number_of_factors = 0
    for i in range(1, int(math.ceil(math.sqrt(n)))):
        if n % i == 0:
            number_of_factors +=2
        else:
            continue
    return number_of_factors

x=1
for y in range(2,1000000):
    x += y
    if divisors(x) >= 500:
        print x
        break
tt = time()-t
print tt

My code takes 3.8 seconds to run, and I know this can be done in around 0.2 seconds in Java. Any suggestions on how to make this run faster?


texts: Processing a list to build an ip in a string format

texts:
The point of this code is to build an ip from a list of type ushort.

var ip = new StringBuilder();
List<ushort> ipList = new List<ushort>(4) {192, 168, 1, 1};

ipList.ToList().ForEach(x => ip.Append(x + "."));

return ip.Remove(ip.Length - 1, 1).ToString();

The code works and outputs an ip as expected, but the formatting I give it leaves to be desired, having to delete the last element of the string does not look like a reliable solution or at least, I don't feel like it is.

The code above would output, before returning, the following string:

"192.168.1.1."

And after removing the last character it will look like this:

"192.168.1.1"


texts: Which Java string value is preferred to return: blank or null?

texts:
I came across this snippet and am wondering if I should return blank in this case.

Which is more practical to return: blank or null?

public String getInfo() {
    String result = "";
    String uri = clientConfiguration.getUri();
    String regex = "http://(.*)/consolidate";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(uri);
    if (matcher.find()) {
        result = matcher.group(1);
    }
    return result;
}

Edit: Should I change it to:

 if(matcher.find()) {
   return matcher.group(1);
 }
 return null;


texts: Sorting strings in a one dimensional array

texts:
What are the better solutions possible?

I have a character array with different strings. There is a max size for the strings. In case a string is smaller than max size remaining places are filled with '-'.
Sorting has to be done on this.

  Example:

  maxStringSize = 5

  totalStrings = 4

  InputArray: w,a,t,e,r, c,a,t,-,-, f,i,v,e,-, b,a,l,l,-,-

  outputArray: b,a,l,l,-,-, c,a,t,-,-, f,i,v,e,-, w,a,t,e,r

-

public class QuestionOne {

char[] mInput = {'w','a','t','e','r','c','a','t','-','-','f','i','v','e','-','b','a','l','l','-','-'};
int mBlockSize = 5;
int mTotalBlocks = 4;

public void init(char[] input, int blockSize, int totalBlocks)
{
    mInput = input;
    mBlockSize = blockSize;
    mTotalBlocks = totalBlocks;
}

public char[] sort()
{

    for(int i=0; i < mTotalBlocks; i++)
    {
        for(int j=i+1; j<mTotalBlocks; j++)
        {
            for(int count = 0; count < mBlockSize; count++ )
            {
                if(mInput[i*mBlockSize+count]>mInput[j*mBlockSize+count])
                {
                    swapBlocks(i,j);
                    break;
                }
                else if(mInput[i*mBlockSize+count]<mInput[j*mBlockSize+count])
                    break;
            }
        }
    }
    return mInput;
}

private void swapBlocks(int blockOne, int blockTwo)
{
    for(int i=0; i<mBlockSize; i++)
    {
        swap(blockOne*mBlockSize+i,blockTwo*mBlockSize+i);
    }
}

private void swap(int one, int two)
{
    char temp = mInput[one];
    mInput[one] = mInput[two];
    mInput[two] = temp;
}

}

What are the better solutions possible?


texts: Can you make this Key-interable view of a List of Maps better?

texts:
I have a list of map entries, and I need an iterable that returns the keys.

Of course, we could be naive and copy over into a new collection of the desired type, but that's inefficient.

So let's see if we can provide a view of the existing structure using generics.  Yes, I was able to do that, but it's not perfect: it gives unchecked conversions when it's passed to a function expecting Iterable<K>.  Could it be improved to avoid these warnings?

Perhaps it could implement Iterable<K> similar to the commented out line which is the path I attempted but couldn't complete.  Can you figure out the similar but correct (no warnings on usage) generic implementation?

This should help demonstrate how the ListKeyIterable is used:

List&LT; Map.Entry &LT; Long,String &GT; &GT; list;

void traverse( Iterable&LT;Long&GT; ) {}

traverse( new ListKeyIterable&LT;List&LT;Map.Entry&LT;Long,String&GT;&GT;&GT;( list );

Here is the working code, but it gives unchecked conversion warning on the call to traverse().

class ListKeyIterable&LT;T extends List&LT;? extends Map.Entry&LT;?,?&GT;&GT;&GT; implements Iterable
//class ListKeyIterable&LT;T extends List&LT;? extends Map.Entry&LT;K,?&GT;&GT;&GT; implements Iterable&LT;K&GT;
{
    T list;

    public ListKeyIterable( T list ) { this.list = list; }

    class ListKeyIterator&LT;K&GT; implements Iterator&LT;K&GT; {
        Iterator&LT;Map.Entry&LT;K,?&GT;&GT; iterator;

        public ListKeyIterator( Iterator&LT;Map.Entry&LT;K,?&GT;&GT; iterator ) { this.iterator = iterator; }
        @Override public boolean hasNext() { return iterator.hasNext(); }
        @Override public K next() { return iterator.next().getKey(); }
        @Override public void remove() { throw new RuntimeException( "ValueListIterator remove() not implemented." ); }
    }

    @Override public Iterator iterator() { return new ListKeyIterator( list.iterator() ); }
    //@Override public &LT;K&GT; Iterator&LT;K&GT; iterator() { return new ListKeyIterator( list.iterator() ); }
}


texts: Convert list of dictionaries to iterable list

texts:
Due to another module coupled to my function, I can only receive the input to my part in the form of a JSON object structured roughly like this:

[{'id':0, 'y':4, 'value':25},{'id':0, 'y':2, 'value':254}]

Note that I do know that the data will arrive in exactly that format. Now, I need to cast this to lists such that I can pass it to the constructor of scipy.sparse.coo_matrix().
Since I have frequent incoming calls, I want to perform this cast as quickly as possible, which is why I am concerned with the optimization of this operation. Below are three different approaches that come up with this type of question. Note that the casting itself has been frequently addressed on Stackoverflow, even with respect to performance in some cases (mostly in terms of list comprehension), but I could not find anything that would give me an optimal solution.

To quickly address the three different methods I use:

evaluate each line as a tuple of the dictionary values. Comparable in speed with something like [[el['id'], el['y'], el['values']] for el in x].
Let pandas do the casting for you. Extremly slow.
Cast three separate lists. Since the allocation of lists in list comprehensions is way slower (compare [[el['id']] for el in x] to [el['id'] for el in x]), this seems to be the currently best-performing solution.

According to the articles I found, list comprehensions outperform any python-native method using .append(), but I might add an example and timing for that later.

The benchmarks are as follows:

import timeit as ti
# 2.107 seconds
print(ti.timeit("z = [tuple(el.values()) for el in x]",
          setup="import random;  x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*60000",
          number=100))

# 8.93 seconds
print(ti.timeit("z = pd.DataFrame(x)",
          setup="import pandas as pd; import random;  x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*60000",
          number=100))

# 0.717 seconds
print(ti.timeit("z1 = [el['id'] for el in x]; z2 = [el['y'] for el in x]; z3 = [el['value'] for el in x]",
          setup="import random;  x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*60000",
          number=100))

I also include the "raw code" for the three snippets:

import random
import pandas as pd

if __name__ == "__main__":
    # ignore the fact that this actually isn't random for individual values
    x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*60000
    # first method
    z1 = [tuple(el.values()) for el in x]
    # second method
    z2 = pd.DataFrame(x)
    # third method
    z_3a = [el['id'] for el in x]
    z_3b = [el['y'] for el in x]
    z_3c = [el['value'] for el in x]

The question is whether there is any significant improvement on this (maybe by using a specialized library I don't know of, or any trick with numpy, etc.) to easily improve the speed on this. I'm currently assuming that, following the 80/20 principle, it is unlikely I'll get more performance out of this without spending a lot more effort on it...


texts: Use of metaclass python to override __init__ and instantiate the class later on

texts:
I m writting some API which would use configuration-like arguments.

Here is an example configuration which will be used by my API

quail.run(
    quail.SolutionPacked(path='Allum1'),
    quail.Installer(
        name='Allum1',
        icon='icon.jpeg',
        binary='allum1',
        console=True
    ),
    quail.builder.Builder(
        quail.builder.CmdIcon('icon.ico'),
        quail.builder.CmdZip(solution_path, 'solution.zip')
    )
)

The only problem with that: we will always instantiate, even when we won't use the instance, (for example if we want to uninstall we won't use the install class)

One way around I have found is to use metaclass and override __call__ to get an "EggInstance" so I can instantiate the actual class later on.

Example implementation:

import six

class InstanceEgg:
    def __init__(self, cls, *args, **kwargs):
        self._cls = cls
        self._args = args
        self._kwargs = kwargs

    def __call__(self):
        return self._cls(_get_instance=True, *self._args, **self._kwargs)

class Egg(type):
    def __call__(cls, *args, **kwargs):
        get_instance = kwargs.pop("_get_instance", False)
        if get_instance:
            return super().__call__(*args, **kwargs)
        return InstanceEgg(cls, *args, **kwargs)

@six.add_metaclass(Egg)
class Test:
    def __init__(self, a, b):
        print("init %d %d" % (a, b))

Example use:

egg = Test(1, 2)
print("got egg")
f = egg()

Output:

got egg
init 1 2

Do you think it is acceptable to use metaclass for this purpose?

And what do you recommend?


texts: Should I copy list both in constructor and in getter?

texts:
I have a simple immutable class:

public class ColumnsWrapper implements Columns {
    private final List<String> columnNames;

    public ColumnsWrapper(List<String> columnNames) {
        this.columnNames = new ArrayList<String>(columnNames);
    }

    @Override
    public List<String> getNames() {
        return new ArrayList<String>(columnNames);
    }

}

Should I always save a copy of passed list in constructor and return copy of saved list in getter?

This class from library project and can be used in several projects in the future.

The purpose of this class is only to store immutable list of column names.


texts:
I have two methods I'd like to improve using optional and any other tool,

 @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            return user;
        }
    }

    public void changePassword(String oldPassword, String newPassword) {

        Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
        String username = currentUser.getName();

        if (authenticationManager != null) {
            LOGGER.debug("Re-authenticating user '"+ username + "' for password change request.");

            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword));
        } else {
            LOGGER.debug("No authentication manager set. Can't change Password!");

            return;
        }

        LOGGER.debug("Changing password for user '"+ username + "'");

        User user = (User) loadUserByUsername(username);
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);

    }

First solution was to do
Optional.ofNullable(user).orElseThrow() but I couldn't use the string format here for the UsernameNotFoundException. I don't want to lose the message I have written in the exceptions.

Any suggestions on how to improve this code?


texts:
I am trying to implement strings tokenizer in Excel via UDF using C# and Excel-Dna. Personally I found the mIRC's function $gettok pretty useful due to the lack of string functions in Excel.

Examples

getTok("Aquel que no espera vencer ya esta vencido",   1, 32) -> "Aquel"
getTok("Aquel que no espera vencer ya esta vencido",  -1, 32) -> "vencido"
getTok("Aquel que no espera vencer ya esta vencido", 2-4, 32) -> "que no espera"
getTok("Aquel que no espera vencer ya esta vencido",   0, 32) -> "Aquel que no espera vencer ya esta vencido"

Code

[ExcelFunction(Category="String Utilities", Name = "getTok")]
public static string getTok(string text, string token, int delimiter)
{
    int from = 0;
    int to = 0;

    string tokenPatter = @"(\d+)(-)(\d+)?";
    string[] tokens = text.Split(new char[] { (char)delimiter });

    Regex tokenRegex = new Regex(tokenPatter, RegexOptions.IgnoreCase);
    Match tokenMatch = tokenRegex.Match(token);

    if (tokenMatch.Success)
    {
        StringBuilder sb = new StringBuilder();
        from = short.Parse(tokenMatch.Groups[0].Value);

        if (tokenMatch.Groups.Count == 1) to = from;
        else if (tokenMatch.Groups.Count == 2) to = (short)tokens.Length;
        else to = short.Parse(tokenMatch.Groups[2].Value);

        for (int i = from; i <= to; i++)
        {
            sb.Append(tokens[i - 1] + ((char)delimiter));
        }

        return sb.ToString();
    }

    int index = int.Parse(token);
    if (index > 0) return tokens[index - 1];
    else return tokens[tokens.Length + index];
}

Questions

What would you improve on?
Have you tried something similar with Excel?


texts: Optimizing puzzle game involving sequence numbers

texts:
I am currently developing a puzzle game that has sequence numbers. The player has to fill the grid with sequence numbers in ascending order. Starting from 1 the player can move horizontally or across and can skip a square in between if it is empty or blocked.

To generate the puzzle automatically, my code is doing the following process:

Make some of the squares blocked.
Select a random position for 1 and calculate the possible moves for 2.
Select a move from possible moves of 2 and store other possible moves in an array so that they can be used for while backtracking if I don't get the solution.
Proceed and backtrack if I don't get a solution.

The grid of puzzle can be anywhere between 4x4 and 9x9.

$possibleMoves = getPossibleMoves($rowForOne,$columnForOne,$solution,$value);
$puzzleSolvedFlag = false;

while($value <= $maximumNumberToBeEntered) {
    $randomMove = array_rand($possibleMoves);
    $position = explode(",",$possibleMoves[$randomMove]);
    unset($possibleMoves[$randomMove]);
    array_push($moves,$possibleMoves);
    $solution[$position[0]][$position[1]] = $value;
    $value++;
    $possibleMoves = getPossibleMoves($position[0],$position[1],$solution,$value);
//  echo $value;
    //print_r($possibleMoves);
    while(count($possibleMoves)==0 && $value<=$maximumNumberToBeEntered) {
        $possibleMoves = array_pop($moves);
        //print_r($possibleMoves);
        $value--;

        foreach ($solution as &$v1) {
            foreach ($v1 as &$v2) {
               if($v2 >= $value) {
                    $v2 = -1;
                }
            }
        }
        if(count($possibleMoves) > 0) {
            break;
        }
    }
    //print_r($possibleMoves);
}

The solution is the array grid. Before the above code I just selected a random move for 1 and the $value will be 2. getPossibleMoves() returns possible moves for 2.

$maximumNumberToBeEntered is the maximum value in the grid (e.g. for a 4x4 grid, if 3 squares are blocked, then the maximum value will be 16-3 = 13).

Can someone help me to optimize the above code? It involves a lot of backtracking.


texts:
I have a Class with a List of objects, and those objects contain a list which has lists to objects in the first class, and I'm trying to quickly index them.  Simplified:

class Person
{
    public IEnumberable<HistoricalEvent> Events
    {
        get
        {
            return World.HistoricalEvents.Values.Where(x=>x.PeopleInvolved.Contains(this));
        }
    }
}

Also

class HistoricalEvent
{
    public virtual IEnumerable<HistoricalFigure> PeopleInvolved
    {
        get { return Enumerable.Empty<People>(); }
    }
...
}

and a subclass

class HistoricalEventSubclass : HistoricalEvent
{
    Person person1 = new Person("Alice");
    Person person2 = new Person("Bob");

    public override IEnumerable<Person> PeopleInvolved
    {
        get
        {
            yield return person1;
            yield return person2;
        }
    }
    ...
}

The Events class is called from a method using: frm.grpHistoricalFigureEvents.FillListboxWith(frm.lstHistoricalFigureEvents, Events);

    internal static void FillListboxWith(this GroupBox groupbox, ListBox listbox, IEnumerable<object> objects)
    {
        if (objects == null || !objects.Any())
        {
            groupbox.Visible = false;
            return;
        }
        groupbox.Visible = true;
        listbox.BeginUpdate();
        listbox.Items.Clear();
        listbox.Items.AddRange(objects.ToArray());
        listbox.EndUpdate();
        listbox.SelectedIndex = 0;
        var title = groupbox.Text.Split('(')[0].Trim();
        groupbox.Text = string.Format("{0} ({1})", title, listbox.Items.Count);
    }

The problem is that calling Events takes a long time (as World.HistoricalEvents can be a very big List).  Is there a more time-efficient way of doing this?

Part of the slowdown is that Events is converted ToArray() and shoved into a listbox, and so I'll also be pursuing an alternative such as a listbox which can handle an IEnumberable directly.


texts: HaxeFlixel 2 player game: make input code cleaner

texts:
I'm makeing two-player game. player1 can play with the WASD keys, and player2 can play with the arrow keys.

PlayState.hx

package;

import flixel.FlxState;

class PlayState extends FlxState
{
    //basic global varible
    var WindowWidth:Int = 640;
    var WindowHeight:Int = 480;

    //sprites
    var player1:Player;
    var player2:Player;

    override public function create():Void
    {

        player1 = new Player(50, WindowHeight / 2 - 50);
        add(player1);

        player2 = new Player(590, WindowHeight / 2 - 50);
        add(player2);

        super.create();
    }

    override public function update(elapsed:Float):Void
    {
        player1.update();
        player2.update();
        super.update(elapsed);
    }
}

Player.hx

package;

import flixel.FlxSprite;
import flixel.FlxG;
import flixel.util.FlxColor;

class Player extends FlxSprite
{
    public function new(X:Float,Y:Float)
    {
        super(X,Y);
        makeGraphic(20,100,FlxColor.WHITE);
    }

    override public function update(elapsed:Float):Void
    {

        super.update(elapsed);
    }
}

In this code, I made a player class. This class is used by both player1 and player2 instances.

Currently both players are moved by the arrow keys. But I want to make two players using different keys (arrow keys and WASD keys).

I'm considering two solutions, but I think the both ways are not perfect. It smells of bad code.

Solution 1:
Make player1 and player2 classes. They extend the Player class and override the update() method.

class Player1 extends Player
{
    override public function update(elapsed:Float):Void
    {
        //make player1 move by wasd keys.
        super.update(elapsed);
    }
}
class Player1 extends Player
{
    override public function update(elapsed:Float):Void
    {
        //make player2 move by arrow keys.
        super.update(elapsed);
    }
}

But if I add the code in update(), there will be duplicated code. I want to make two player is completely identical, only different location and keyboard.

Solution 2:
Receive argument in update() function which key will use, and use it.

override public function update(elapsed:Float, upkey, downkey, rightkey, leftkey):Void
{
    //I will write it psuedo code
    if(upkey.pressed):
        move up
    if(downkey.pressed):
        move down
    if(leftkey.pressed):
        move left
    if(rightkey.pressed):
        move right
    super.update(elapsed);
}

But it have to additional argument in the update() function. And I think it makes the code more complex.

To me, both seem like bad code. What can I do?


texts: More efficient conversion of tab-formatted nested data structure to json

texts:
I have data that looks like the "Input" below and need to convert it into JSON.  My solution works by parsing the text to find a level for each data point.  Then I use a recursive structure to build a JSON tree (or maybe its not JSON, but its much more useful than the original format).

First, I transform the input in the following way.

Input:

person:
    address:
        street1: 123 Bar St
        street2:
        city: Madison
        state: WI
        zip: 55555
    web:
        email: boo@baz.com

First-step output:

[{'name':'person','value':'','level':0},
 {'name':'address','value':'','level':1},
 {'name':'street1','value':'123 Bar St','level':2},
 {'name':'street2','value':'','level':2},
 {'name':'city','value':'Madison','level':2},
 {'name':'state','value':'WI','level':2},
 {'name':'zip','value':55555,'level':2},
 {'name':'web','value':'','level':1},
 {'name':'email','value':'boo@baz.com','level':2}]

This is easy to accomplish with split(':') and by counting the number of leading tabs:

def tab_level(astr):
    """Count number of leading tabs in a string
    """
    return len(astr)- len(astr.lstrip('\t'))

Then I feed the first-step output into the following function:

def ttree_to_json(ttree,level=0):
    result = {}
    for i in range(0,len(ttree)):
        cn = ttree[i]
        try:
            nn  = ttree[i+1]
        except:
            nn = {'level':-1}

        # Edge cases
        if cn['level']>level:
            continue
        if cn['level']<level:
            return result

        # Recursion
        if nn['level']==level:
            dict_insert_or_append(result,cn['name'],cn['value'])
        elif nn['level']>level:
            rr = ttree_to_json(ttree[i+1:], level=nn['level'])
            dict_insert_or_append(result,cn['name'],rr)
        else:
            dict_insert_or_append(result,cn['name'],cn['value'])
            return result
    return result

where:

def dict_insert_or_append(adict,key,val):
    """Insert a value in dict at key if one does not exist
    Otherwise, convert value to list and append
    """
    if key in adict:
        if type(adict[key]) != list:
            adict[key] = [adict[key]]
        adict[key].append(val)
    else:
        adict[key] = val

The approach is redundant and therefore inefficient.  I also wonder whether the solution is robust (for example, I had to modify the code to accommodate repeated tags).  Think of the Input above as a formatting for SGML.  Any suggestions for improvement would be greatly appreciated!


texts: A double search function that looks in a list for one value and then the other alternatively

texts:
I'm writing in Python (3.4) a double search function that looks in a list for one value and then the other alternatively. That is, start searching the second value once you find first the first value (and start searching from where you found the first value) and vice-versa.

My first approach was to write a recursive function to do it, only to find out they don't end up as neat in Python as they do in Haskell. This is a basic sketch of the function:

def double_search(input_list, first_condition, second_condition, condition_to_search, output_list):
    if input_list == []:
        return output_list
    else:
        if condition_to_search == 1:
            if input_list[0] == first_condition:
                return output_list + double_search(input_list[1:], first_condition, second_condition, 2, output_list + ['First'])
            else:
                return output_list + double_search(input_list[1:], first_condition, second_condition, 1, output_list + ['None'])
        if condition_to_search == 2:
            if input_list[0] == second_condition:
                return output_list + double_search(input_list[1:], first_condition, second_condition, 1, output_list + ['Second'])
            else:
                return output_list + double_search(input_list[1:], first_condition, second_condition, 2, output_list + ['None'])

I have several problems with the way it turned out, looks forced and ugly in Python. And produces different outputs in Python interpreter and pydev debugger!

Pydev debugger gives the proper result while in the interpreter I have to take the tail of the result:

result[-len(input_list):]

To get a list of the appropriate length, which I find unacceptable because I have no clue where the garbage in front comes from.

Would appreciate any suggestion to improve this code, make it more pythonic and easier to maintain as well as any performance improvements you can suggest.

EDIT: As per request, the following is an example of the function in use with some sample data.

example_list = [5,4,1,2,0,3,1,3,4,2,5,0]
double_search(example_list, 1, 3, 1, [])

Should result in: ['None', 'None', 'First', 'None', 'None', 'Second', 'First', 'Second', 'None', 'None', 'None', 'None']

While:

double_search(example_list, 1, 5, 1, [])

Results in: ['None', 'None', 'First', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'Second', 'None']

Notice how in the second case only matches the second to last '5', because it needs to find first a '1'.