texts: Akka actor to calculate a soccer league rank

texts:
I am new to Scala / Akka and this is my first attempt at writing an actor.

The task that I am trying to accomplish is: given a sequence of soccer matches, generate a ranking based on the usual rules of soccer (winner gets 3 points, loser gets 0 points, and 1 point each in case of a draw).

Here is my current ranker actor:

package soccerLeague.akka

import akka.actor.Actor
import soccerLeague.common.{LeagueRules, MatchResult, TeamWithPoints}

// Stateful Ranker actor that maintains a rank.
// The rank gets updated every time a MatchResult message is received.
class RankerActor(rules: LeagueRules) extends Actor {

  private var rank: Seq[TeamWithPoints] = List()
  private var rankMap = Map[String, Int]()

  def receive = {
    case MatchResult(team1, score1, team2, score2) => {
      updateRank(MatchResult(team1, score1, team2, score2))
      sender ! rank
    }
    case Message("getRank") => {
      sender ! rank
    }
  }

  private def updateRank(matchRes: MatchResult): Unit = {

    def calcDeltaPoints(score1: Int, score2: Int): Int = {
      if(score1 == score2) rules.drawScore
      else if(score1 > score2) rules.winScore
      else rules.lossScore
    }

    val newPoints1 = rankMap.getOrElse(matchRes.team1, 0) + calcDeltaPoints(matchRes.score1, matchRes.score2)
    val newPoints2 = rankMap.getOrElse(matchRes.team2, 0) + calcDeltaPoints(matchRes.score2, matchRes.score1)

    rankMap += (matchRes.team1 -> newPoints1, matchRes.team2 -> newPoints2)

    // Sort by score, in reverse order (i.e. the team with most points is first).
    // Teams that have the same score are sorted in alphabetical order.
    // TODO: this *can* be improved by only moving around the two teams that are changing.
    rank = rankMap.toSeq
      .map { case (t, s) => new TeamWithPoints(t, s) }
      .sortBy { case TeamWithPoints(team, points) => (-points, team) }
  }

}

I have a few supporting case classes:

case class MatchResult(team1: String, score1: Int, team2: String, score2: Int)
case class LeagueRules(winScore: Int, drawScore: Int, lossScore: Int)
case class TeamWithPoints(team: String, points: Int)

What are ways that I can make this code better and more idiomatic?
How can I avoid deconstructing the MatchResult (in the receive method) and then reconstructing it again when I want to pass it down to the updateRank method?


texts:
I have written this code for cookie parsing. Can anyone tell me what optimizations we can do in this or what can we do to make it more concise?

function parseCookies(cookies) {
  var cookie,
    cookieParts,
    parsedCookies = [];

  if (!cookies || !cookies.length) {
    return null;
  }

  // Remove domain from each cookie to decrease the size of cookie (Not needed)
  for (var i = 0; i < cookies.length; i++) {
    cookie = cookies[i];
    cookieParts = cookie.split(';');

    for (var index2 = cookieParts.length - 1; index2 >= 0; index2--) {
      var pair = cookieParts[index2],
        key = pair.split('=')[0];

      if (key && key.trim().toLowerCase() == 'domain') {
        cookieParts.splice(index2, 1);
      }
    }

    cookie = cookieParts.join(';');
    parsedCookies.push(cookie);
  }

  return parsedCookies;
}


texts: Plotting different parameterized polynoms

texts:
For a university assignment I had to plot different polynomial functions depending on one single parameter. That parameter gave the number of supporting points to interpolate a given function in the domain \$\lbrack -1.0, 1.0 \rbrack \$.

The supporting points were to be calculated in two different fashions. Either they were to be equidistant or be Chebyshev nodes. The given definitions were:

$$ x_i = \frac{2i}{n} - 1 , \quad x_i = \cos \frac{(2i + 1)\pi}{2(n + 1)} $$

The plots are to be handed in in a pdf. The polynomial functions I had to calculate were given as:

\$\Phi_n(x) = \underset{i \neq j}{\underset{i = 0}{\overset{n}{\Pi}}} (x - x_i) \$ and the slightly more complicated \$\lambda(x) = \underset{i = 0}{\overset{n}{\Sigma}} \lvert l_{i,n}(x) \rvert \$. Here \$l_{i,n}(x)\$ denotes a Lagrange polynomial.  I'll just stop torturing you with math definitions, (because I'm reasonably sure I'm able to copy a formula from a script into code).

Note that \$\Phi_n\$ is called "Supporting point polynomial" and \$\lambda\$ is called "Lebesgue function" in the assignment.

So without further ado, here's my code.
Note that maintainabiltiy for future use is not a concern, so if you want you can mention docstrings and variable names, but those points don't really help me :)

import numpy as np
import matplotlib.pyplot as plt

def equidistant_points(count):
    points = []
    for i in np.arange(0, count):
        points.append((2 * i / count) - 1)
    return points

def tschebyscheff_points(count):
    points = []
    for i in np.arange(0, count):
        points.append(np.cos(((2 * i + 1) * np.pi) / (2 * (count + 1))))
    return points

def as_supporting_point_poly(points, x):
    poly = 1
    for point in points:
        poly = poly * (x - point)
    return poly

def lagrange_poly(points, j, x):
    poly = 1
    for i in range(0, len(points)):
        if (i != j):
            poly = poly * ((x - points[i]) / (points[j] - points[i]))
    return poly

def lebesgue_function(points, x):
    leb = 0
    for i in range(0, len(points)):
        leb = leb + np.fabs(lagrange_poly(points, i, x))
    return leb

def plot_and_save(n, x, poly_calc, name):
    equi = plt.plot(x, poly_calc(equidistant_points(n), x), 'r-', label='Äquidistante Stützstellen')
    tsch = plt.plot(x, poly_calc(tschebyscheff_points(n), x), 'g-', label='Tschebyscheff-Stützstellen')

    plt.xlabel("x")
    plt.ylabel("y")
    plt.title(name + " mit n = " + str(n))
    plt.grid(True)
    plt.legend(loc='upper right', shadow=False)
    plt.savefig("Aufg1"+ poly_calc.__name__ + str(n) + ".png")
    plt.show()

if __name__== '__main__':
    domain = np.arange(-1.0, 1.0001, 0.0001)
    plot_and_save(8, domain, as_supporting_point_poly, "Stützstellenpolynome")
    plot_and_save(20, domain, as_supporting_point_poly, "Stützstellenpolynome")

    plot_and_save(8, domain, lebesgue_function, "Lebesgue-Funktion")
    plot_and_save(20, domain, lebesgue_function, "Lebesgue-Funktion")

I'm especially interested in ways to make the calculation of the supporting points in equidistant_points and tschebyscheff_points cleaner.


texts: Short bash script to join arguments with dashoption, escaping quotes and $ dollar sign

texts:
So I got this short awk invocation wrapped in a bash script. unfortunately the bash script is kinda unreadable. Do you have any pointers?
#!/bin/bash
action="printf \"$1 \" \$1 \" \""
awk {"$action"} $2

Invoking it like this joinargs -s tmp if the tmp file looks like:
a
bb
ccc

would create this output -s a -s bb -s ccc and it's useful when assembling commands


texts:
I have been solving the problem from UVA 10474. In this problem, there will be marbles with numbers written on them. For example suppose five marbles with numbers 50 , 43, 43, 43, 2, 90, 44. There will be several query with number and position has to be told in a sorted sequence. For example after sorting these looks like : 2,43,43,43,44,50,90. Now, query for 43 will give output : 43 fond at 2 and query for -3 will output "-3 not found".

Can you please review it and provide me with feedback?

#include <iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>

void printMarbelPositionIfFound()
{
    int numMarbles, numQueries, aMarble, case1;
    std::vector<int>marbles;

    case1 = 0;

    while(true)
    {
        scanf("%d %d", &numMarbles, &numQueries);
        if(0 == numMarbles && 0 == numQueries)return;

        case1++;

        for(int i=0; i<numMarbles; i++)
        {
            scanf("%d", &aMarble);
            marbles.push_back(aMarble);
        }

        std::sort(marbles.begin(), marbles.end());
        std::cout<<"CASE#"<<" "<<case1<<":"<<"\n";
        for(int i=0; i<numQueries; i++)
        {

            scanf("%d", &aMarble);

            std::vector<int>::const_iterator itr = std::lower_bound(marbles.begin(), marbles.end(),aMarble);
            if(*itr == aMarble)
            {
                std::cout<<aMarble<<" found at "<<itr - marbles.begin() + 1<<'\n';
            }
            else
            {
                std::cout<<aMarble<<" not found"<<'\n';
            }
        }

        marbles.clear();
    }
}

int main()
{
    printMarbelPositionIfFound();
    return 0;
}


texts: Factorials, loops, break and professional code

texts:
The program below correctly calculates factorials, until the limit for an unsigned long long integer is exceeded.

My question has to do with loops and exiting loops. The program uses one infinite while loop and the break statement to exit 2 while loops.

Do working, professional programmers handle loops this way? If not, how would they write and exit these loops?

/* factorial.c

   program to calculate factorials until the limit for an unsigned long long
   integer is exceeded

   20! =    2,432,902,008,176,640,000
   limit = 18,446,744,073,709,551,615
   21! =   51,090,942,171,709,440,000
*/

#include <stdio.h>
#include <limits.h>

unsigned long long int factorial (int i)
{
    // function returns 0 when limit exceeded

    int j;
    unsigned long long int result;

    if ( i == 0 )
        result = 1;
    else {
        result = i;

        j = i - 1;

        while ( j >= 1 ) {
            if ( result <= ULLONG_MAX / j )
                result *= j;
            else {
                result = 0;
                break;
            }

            --j;
        }
    }

    return result;
}

int main (void)
{
    int i;
    unsigned long long int number;

    printf ("\nTABLE OF FACTORIALS\n\n");
    printf (" n            n!\n");
    printf ("-- ------------------------\n");

    i = 0;

    while ( 1 ) {
        number = factorial (i);
        if ( number == 0 )
            break;
        printf ("%2i %24llu\n", i, number);
        ++i;
    }

    return 0;
}


texts: Improve this javascript code: It displays hidden text and highlights the selected page number

texts:
This code (http://jsbin.com/isexez/5/edit) functions as expected:
(1) it displays the page selected; and
(2) it highlights the number of the selected page.

I would appreciate help in improving it.

I am in the process of writing an ebook (http://www.keepcount.net/ebook/01-09/02_tricks.html) and need to improve this code before I get back to my writing.

*  Here's my jQuery code as suggested by @Gisborne *
See also  jsbin.com/iduxol/2/edit

<!DOCTYPE html>

 -->

<meta charset=utf-8 />
<title>JS Bin</title>

 p1
 p2

   text on page 1

   quiz on page 2


texts: Shell script that copies configuration and dotfiles to repository

texts:
A while ago I had the idea to store all the important configuration and dotfiles from my system in a Git repository. That saved me a few months ago: My harddrive died, but I could get back to work with Ubuntu and that repository quickly.

Only problem: I maintained that repo by manually copying the files from the various directories to the repo directory. That’s what I wrote the shell script for.

What does the script do?

Checks whether the command is executed from within the root of a git repository
Detects which OS it’s operating on (Windows, Linux or OS X) and saves that information in a variable OS
Assigns variables for certain tool groups (like Bash, Git, etc.) and creates the target directories in the repo if they don’t exist
Copies file by file to these destinations

Notes:

Currently, I separate the files on a per-OS basis. This is probably unnecessary and even a hinderance. I’d like to here your opinion here
The script currently does not use any Bash >4 features, because besides Ubuntu I mainly work on Windows. I use Git Bash there which only has version 3 bundled.
I also wrote a short article about this script: Backup configuration and dotfiles with Git and a shell script
If you’re interested in current/updated versions, check out the script in the repo: get-dotfiles.sh

#!/bin/bash

################################################################################
#
# Shell script to copy important configuration files from the current
# environment to this repository.
#
################################################################################

# Exit as soon as a command fails
set -e

# Accessing an empty variable will yield an error
set -u

# Assume the working directory is the path to the dotfiles repository
REPO_PATH="$PWD/"

# Abort mission when we’re not in a git repository
if [[ ! -d .git ]] || ! git rev-parse --git-dir > /dev/null 2>&1; then
    echo "Not a git repository."
    exit 1
fi

# Detect OS (OS X, Linux or Windows)
if [ "$(uname)" = "Darwin" ]; then
    echo "Detected system: OS X"

    OS="osx/"

    ST_DIR="$HOME/Library/Application Support/Sublime Text 3/Packages/User/"
elif [ "$(expr substr $(uname -s) 1 5)" = "Linux" ]; then
    echo "Detected system: Linux"

    OS="linux/"

    ST_DIR="$HOME/.config/sublime-text-3/Packages/User/"
elif [ "$(expr substr $(uname -s) 1 10)" = "MINGW32_NT" ]; then
    echo "Detected system: Windows"

    OS="win/"

    ST_DIR="$HOME/AppData/Roaming/Sublime Text 3/Packages/User/"
    NPM_DIR="$HOME/AppData/Roaming/npm/node_modules/npm/"
fi

# Adjust destination paths so the files are separated by OS
BASH_DEST="${REPO_PATH}${OS}bash/"
GIT_DEST="${REPO_PATH}${OS}git/"
NPM_DEST="${REPO_PATH}${OS}npm/"
RUBY_DEST="${REPO_PATH}${OS}ruby/"
ST_DEST="${REPO_PATH}${OS}sublime-text/"

declare -a destinations=($BASH_DEST $GIT_DEST $NPM_DEST $RUBY_DEST $ST_DEST)

for dest in "${destinations[@]}"; do
    mkdir -p "$dest"
done

# Bash
cp "$HOME/.bashrc" "$BASH_DEST"
cp "$HOME/.bash_aliases" "$BASH_DEST"

# Git
cp "$HOME/.gitignore_global" "$GIT_DEST"
cp "$HOME/.gitconfig" "$GIT_DEST"

# Node.js/npm
cp "${NPM_DIR}.npmrc" "$NPM_DEST"

# Ruby/RubyGems
cp "$HOME/.gemrc" "$RUBY_DEST"

# Sublime Text
cp "${ST_DIR}Preferences.sublime-settings" "$ST_DEST"
cp "${ST_DIR}Markdown.sublime-settings" "$ST_DEST"
cp "${ST_DIR}YAML.sublime-settings" "$ST_DEST"
cp "${ST_DIR}Package Control.sublime-settings" "$ST_DEST"
cp "${ST_DIR}For Loop (range).sublime-snippet" "$ST_DEST"
cp "${ST_DIR}Fraction (TeX).sublime-snippet" "$ST_DEST"

# OS specific copy operations
if [ "$OS" = "osx/" ]; then
    echo "Nothing here."
elif [ "$OS" = "linux/" ]; then
    cp "${ST_DIR}Default (Linux).sublime-keymap" "$ST_DEST"
elif [ "$OS" = "windows/" ]; then
    cp "${ST_DIR}Default (Windows).sublime-keymap" "$ST_DEST"
fi

echo "Completed."

(Shell scripts are new terrain for me, I probably made some faulty assumptions. Still, don’t have mercy.)


texts: Collecting all relevant data from xlsm files

texts:
Is there a way to speed this guy up? The code is designed to go into a directory, open up all of the .xlsm files in the folder, and copy specific data into a target file. This code works as is, but it is extremely slow. Is there a way to speed it up?

Const FOLDER_PATH = "C:\Users\maxd\OneDrive - Nortek, Inc\Coil Test Data\coils_35_and_36\36\WET\Testing\"  'REMEMBER END BACKSLASH

Sub ImportWorksheets()
   '=============================================
   'Process all Excel files in specified folder
   '=============================================
   Dim sFile As String           'file to process
   Dim wsTarget As Worksheet
   Dim wbSource As Workbook
   Dim wsSource As Worksheet
   Dim rowTarget As Long         'output row

   rowTarget = 11

   'check the folder exists
   If Not FileFolderExists(FOLDER_PATH) Then
      MsgBox "Specified folder does not exist, exiting!"
      Exit Sub
   End If

   'reset application settings in event of error
   On Error GoTo errHandler
   Application.ScreenUpdating = False

   'set up the target worksheet
   Set wsTarget = Sheets("Sheet1")

   'loop through the Excel files in the folder
   sFile = Dir(FOLDER_PATH & "*.xlsm*")
   Do Until sFile = ""

      'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
      Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
      Set wsSource = wbSource.Worksheets("Report")

      'import the data
      With wsTarget
         .Range("A" & rowTarget).Value = wsSource.Range("E9").Value 'Year
         .Range("B" & rowTarget).Value = wsSource.Range("D30").Value 'CFM
         '.Range("D" & rowTarget).Value = wsSource.Range("D30/(30*30/144)").Value 'Face Velocity
         .Range("E" & rowTarget).Value = wsSource.Range("D36").Value 'AVG Capacity
         .Range("F" & rowTarget).Value = wsSource.Range("D29").Value 'APD
         .Range("G" & rowTarget).Value = wsSource.Range("D34").Value 'WPD
         .Range("H" & rowTarget).Value = wsSource.Range("D22").Value 'Inlet db
         .Range("I" & rowTarget).Value = wsSource.Range("D23").Value 'Inlet  wb
         '.Range("J" & rowTarget).Value = wsSource.Range("").Value 'Inlet dp
         .Range("K" & rowTarget).Value = wsSource.Range("L16").Value 'Inlet WT
         .Range("L" & rowTarget).Value = wsSource.Range("L17").Value 'Outlet WT
         .Range("M" & rowTarget).Value = wsSource.Range("L22").Value 'Heat Balance

         'optional source filename in the last column
         .Range("N" & rowTarget).Value = sFile
      End With

      'close the source workbook, increment the output row and get the next file
      wbSource.Close SaveChanges:=False
      rowTarget = rowTarget + 1
      sFile = Dir()
   Loop

'Loop for face velocity
  Dim r As Integer
  Dim i As Integer

i = Cells(Rows.Count, 1).End(xlUp).Row
    For r = 11 To i
        Cells(r, 4) = "=RC[-2]/(30*30/144)"
    Next r

errHandler:
   On Error Resume Next
   Application.ScreenUpdating = True

   'tidy up
   Set wsSource = Nothing
   Set wbSource = Nothing
   Set wsTarget = Nothing

End Sub

Private Function FileFolderExists(strPath As String) As Boolean
    If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function


texts:
I've written a CLI tool in Python, for bruteforcing hashes (only md5 with this version). Apart from the fact that Python is not exactly suitable for bruteforcing (performance), what else can I do to improve my code (performance -otherwise-, styling, naming, argument handling etc.)?

from sys import argv, exit
from time import time
from hashlib import md5
from itertools import product
from datetime import datetime
from string import ascii_lowercase, ascii_uppercase, digits

hash_ = argv[1]
charset_ = argv[2]
minlength = argv[3]
maxlength = argv[4]

charset = {"1":  ascii_lowercase,
           "2":  ascii_uppercase,
           "3":  digits,
           "4":  ascii_lowercase
               + ascii_uppercase,
           "5":  ascii_lowercase
               + digits,
           "6":  ascii_uppercase
              + digits,
           "7":  ascii_lowercase
              + ascii_uppercase
              + digits
         }

 charset = charset[charset_]

 colors = {"R":"\033[91m",
           "G":"\033[92m",
           "~":"\033[00m"
         }

def bruteforce(hash_, characters, min_length, max_length):

    start = datetime.now()
    start_time = time()

    for length in range(int(min_length), int(max_length) + 1):
        products = product(characters, repeat=length)
        for attempt in products:
            hashed = "".join(attempt).encode("utf-8")
            hashed = md5(hashed).hexdigest()

            if hashed != hash_:
                print(f"{colors['R']}{''.join(attempt)}")

            else:
                diff = int(time()-start_time)
                print(f"{colors['G']}{''.join(attempt)}")
                print(colors["~"])
                print(" Statistics")
                print("~~~~~~~~~~~~~~~~~")
                print(f"Started:          {start}")
                print(f"Calculation time: {diff} seconds")
                print(f"Original hash:    {hash_}")
                print(f"Found string:     {''.join(attempt)}")
                print("~~~~~~~~~~~~~~~~~")

               return True

def main():
    print(colors["~"])
    bruteforce(hash_, charset, minlength, maxlength)
    print(colors["~"])

if __name__ == "__main__":
    main()
    exit()


texts: Returning a NumPy array (or list) of strings of words repeated N times

texts:
I have a list of \$n\$ words, and a corresponding \$m \space x \space n\$ frequency matrix (as a NumPy array). I would like to return a list/array of strings of length \$m\$ where the \$m\$th string is comprised of each word repeated according to the frequencies in the \$m\$th row of the frequency matrix. I have managed to achieve the desired result (help from here), but the code is not particularly easy to understand at a glance. Is there a cleaner and more efficient way to perform the following operation?

import numpy as np
x = ['yugoslavia', 'zealand', 'zimbabwe', 'zip', 'zone']
y = np.array([[2,1,0,0,5], [0,0,1,3,0]])
z = np.apply_along_axis(lambda b: ' '.join([ item for sublist in [[x[i]]*b[i] for i in range(len(x))] for item in sublist]),1,y)

>>> z
array(['yugoslavia yugoslavia zealand zone zone zone zone zone',
   'zimbabwe zip zip zip'],
  dtype='<U54')

I am looking for solutions compatible with Python 3.5.


texts: MySQL JDBC integration into App from tutorial

texts:
I was following this tutorial for JavaFX and Gradle:

JavaFX with Gradle, Eclipse and, Scene Builder on OpenJDK11

After completion of the tutorial you will have a simple GUI which you input a lower and upper bound and generate random numbers between them. The generated numbers and their bounds are then saved and listed in another view.

After completion of this tutorial I wanted to integrate MySQL as the back end.

The tutorial creator acknowledged at some point that a database like SQLite would be the preferred back end but that it was outside the scope of the tutorial. Luckily it seems he designed the app in such a way that he uses DAO class and I just replaced his code in there with my own JDBC implementation.

package RandomNumber.repository;

import java.util.*;
import java.sql.*;

import RandomNumber.models.RandomNumber;

public class LocalRandomNumberDAO implements RandomNumberDAO {

    public LocalRandomNumberDAO() {

    }

    private List<RandomNumber> numbers = new ArrayList<>();

    private Connection openConn() throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/numbers?" +
                                                   "user=demo_java&password=1234");
    }

    @Override
    public boolean save(RandomNumber number) {
        boolean res = false;
        try (
            var conn = openConn();
            var stmt = conn.prepareStatement("insert into numbers_tabl values(?,?,?,?,?)");
        ) {
            stmt.setInt(1, 0);
            stmt.setInt(2, number.getNumber());
            stmt.setInt(3, number.getLowerBounds());
            stmt.setInt(4, number.getUpperBounds());
            stmt.setDate(5, java.sql.Date.valueOf(number.getCreatedAt()));
            res = stmt.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return res;
    }

    @Override
    public void loadNumbers() {
        try (
            var conn = openConn();
            var stmt = conn.createStatement();
        ) {
            String strQuery = "select * from numbers_tabl;";
            var rset = stmt.executeQuery(strQuery);
            numbers.clear();
            while(rset.next()) {
                numbers.add(new RandomNumber(
                        rset.getDate("created").toLocalDate(),
                        rset.getInt("number"),
                        rset.getInt("min"),
                        rset.getInt("max")
                        )
                    );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<RandomNumber> getNumbers() {
        return Collections.unmodifiableList(numbers);
    }
}

I am also calling loadNumbers each time the generate button is pressed, so I essentially insert 1 row, and then query all rows in the database.

Questions:
1. Must I always provide a value for the Primary Key to the PreparedStatement in the save method? my table description follows:

mysql> describe numbers_tabl;
+---------+------+------+-----+---------+----------------+
| Field   | Type | Null | Key | Default | Extra          |
+---------+------+------+-----+---------+----------------+
| id      | int  | NO   | PRI | NULL    | auto_increment |
| number  | int  | NO   |     | NULL    |                |
| min     | int  | NO   |     | NULL    |                |
| max     | int  | NO   |     | NULL    |                |
| created | date | YES  |     | NULL    |                |
+---------+------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

2. What best practices am I blatantly ignoring?
3. Is there a better way? Or rather, is there a library or framework that is more worth my time?
4. This is my first time using Java-11. I have always used pretty much only Java 7 or 8 features. Is my usage of the var keyword appropriate?


texts: Compare Sheet1 and Sheet2 for every match and then write them on Sheet3

texts:
I have the following code

Sub checkdata()
Application.Calculation = xlCalculationManual
Dim sheet1 As Worksheet
Set sheet1 = Sheets(1)
Dim sheet2 As Worksheet
Set sheet2 = Sheets(2)
Dim sheet3 As Worksheet
Set sheet3 = Sheets(3)
lr1 = sheet1.Cells(Rows.Count, 1).End(xlUp).Row
lr2 = sheet2.Cells(Rows.Count, 1).End(xlUp).Row
lr3 = sheet3.Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lr1
DoEvents
    check = sheet1.Cells(i, 1).Value
    lr3 = lr3 + 1
    For k = 1 To 5
        sheet3.Cells(lr3, k).Value = sheet1.Cells(lr3, k).Value
    Next k
    For j = 1 To lr2
        If sheet2.Cells(j, 4).Value = check And sheet2.Cells(j, 5).Value = vbNullString Then
            sheet2.Cells(j, 9).Value = "x"
            lr3 = lr3 + 1
            For k = 1 To 3
               sheet3.Cells(lr3, k + 5).Value = sheet2.Cells(lr3, k).Value
            Next k
            Exit For
        End If
    Next j
    lr3 = lr3 + 1
Next i
Application.Calculation = xlCalculationAutomatic
End Sub

It goes like: For each line on sheet1, copy the information I need to sheet3, then check all lines on sheet2 and see if it is from the same thing (Column 1 on sheet1 and Column 4 in sheet2). If it matches and it wasnt used yet, mark as used and put the info on sheet3 too, offset to the right.

Most of the variables are placeholders. Lr means lastrow, and the for loops uses i, j and k

I just have a problem that it is too slow, because both Sheet1 and Sheet2 can have around 100k lines, making it check 100k*100k times, to a total of 10kkk. I know the DoEvents makes it even slower, but I need a way to unlock excel, so it doesn't get that "Not responding" state for too long.

The output may look kinda weird, but it's how I need it for other places that I can't touch yet.


texts: Printing all possible sums of two n-sided dice rolls

texts:
For my CS class, we were tasked with writing a program that calculates all the possible results from rolling two n-sided dice.  For example, the input of 4 would print [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 8].  Or, if the input was 3, it would print [2, 3, 3, 4, 4, 4, 5, 5, 6].

I was given enough test cases that I noticed the pattern that the number range was [2,n] and the test cases had a pattern where the pattern was always could be represented by printing the number in [2,2n+1] a number in the set [1,n] U (n,1] a corresponding number of times.  For example, for 4, the set would be [1,2,3,4,3,2,1] and the output would be [(one 2), (two 3s), (three 4), (four 5s), (three 6s), (two 7s), and (one 8).  This explanation may be horrible, but see the code and you will understand.

The code:

def allRolls(sides):
    nums = list(range(1,sides+1)) + reverseIt(list(range(1,sides)))
    index = sides-1
    #the return array
    retVal = []
    #The index to look for in the list of nuts
    cIndex = 0
    for i in range(2,sides*2+1):
        for b in range(nums[cIndex]):
            retVal.append(i)
        cIndex+=1
    retVal.sort()
    return retVal

#Reverses the list
def reverseIt(liste):
    newb =[]
    index = len(liste)-1
    while index>=0:
        newb.append(liste[index])
        index= index-1
    return newb

The issue:  everyone in my class got it in many fewer lines of code.  What did I do wrong?

Code test cases:

Input: 2
Output:[2, 3, 3, 4]

Input: 3
Output:[2, 3, 3, 4, 4, 4, 5, 5, 6]

Input: 4
Output: [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 8]


texts: Remove item after a specified item from a linked list

texts:
I have written a function that deletes the item that is next to the one being passed as a parameter. So far this function deletes but I feel like there is a better way to implement this.

public class MyLinked{
private class Node{
    Node next;
    double item;
    public Node(double item, Node next) {
        this.item = item;
        this.next = next;
    }
    public Node() {

    }
}
Node first;

Here is the function:

public void removeAfter(double x) {
    if(first == null) { return;}
    else {
        Node c = first;
        while(c!=null){
            if(c.item == x && c.next!=null) {
                c.next = c.next.next;
            }
            c = c.next;
        }
    }
}


texts: Guessing game - am I using the concept of objects in Java properly?

texts:
I'm new to Java and find it hard to grasp the concept of objects. I wrote a simple guessing game to practice the concept of OO programming but I am not sure if I am doing it correctly.

The objective of the game is to guess a number from 0-9 with 3 players and the first player who guesses it correctly will win the game.

Player

public class Player {

    private String playerName;
    private int number;

    public int getNumber() {
        return number;
    }

    public String getPlayerName() {
        return playerName;
    }

    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }

    public void guessNumber(){
        number = Integer.parseInt(JOptionPane.showInputDialog(playerName
            + "'s Turn\nGuess the Number"));
        JOptionPane.showMessageDialog(null, playerName+ "'s GUESS is " + number);
    }
}

GuessGame

public class GuessGame {

    private int numberToGuess;
    private Player p1;
    private Player p2;
    private Player p3;

    public void startGame(){
        numberToGuess = (int) (Math.random()*10);
        p1 = new Player();
        p2 = new Player();
        p3 = new Player();

        p1.setPlayerName(JOptionPane.showInputDialog("Enter Player 1 Name: "));
        p2.setPlayerName(JOptionPane.showInputDialog("Enter Player 2 Name: "));
        p3.setPlayerName(JOptionPane.showInputDialog("Enter Player 3 Name: "));

        int flagWinner = 0;
        while(0==flagWinner){
            p1.guessNumber();
            if (p1.getNumber()==numberToGuess){
                flagWinner = 1;
                break;
            }
            JOptionPane.showMessageDialog(null, p1.getPlayerName()
                + "'s Guess is Wrong!");
            p2.guessNumber();
            if (p2.getNumber()==numberToGuess){
                flagWinner = 2;
                break;
            }
            JOptionPane.showMessageDialog(null, p2.getPlayerName()
                + "'s Guess is Wrong!");
            p3.guessNumber();
            if (p3.getNumber()==numberToGuess){
                flagWinner = 3;
                break;
            }
            JOptionPane.showMessageDialog(null, p3.getPlayerName()
                + "'s Guess is Wrong!");
        }
        if (1 == flagWinner){
            JOptionPane.showMessageDialog(null,p1.getPlayerName()+ " Wins!");
        } else if (2 == flagWinner){
            JOptionPane.showMessageDialog(null,p2.getPlayerName()+ " Wins!");
        } else JOptionPane.showMessageDialog(null,p3.getPlayerName()+ " Wins!");
    }
}

And I have a gameLauncher where I have the main() method which creates the game.

Am I doing it correctly especially in the Player class where I created a method guessNumber() instead of setter setNumber(int number)?

Am I violating any object-oriented concepts in my code?

How can I improve my code?


texts:
This is some Erlang code I wrote to output a string of all the IP addresses of the machine. The string is simply printed to the user for him to read.

-module(ip).
-export([get_ip_address_string/0]).

get_ip_address_string() ->
    {ok, IPAddress} = inet:getif(),
    filter_ip_address(IPAddress).

filter_ip_address(IPAddress) ->
    filter_ip_address(IPAddress, []).

filter_ip_address([], Acc) ->
    Acc;
filter_ip_address([{{127,0,0,1}, _Broadcast, _Mask} | Tail], Acc) ->
    %Do not include the loopback address.
    filter_ip_address(Tail, Acc);
filter_ip_address([Head | Tail], Acc) ->
    {{Oct1, Oct2, Oct3, Oct4}, _Broadcast, _Mask} = Head,
    IPString = io_lib:format("~b.~b.~b.~b ", [Oct1, Oct2, Oct3, Oct4]),
    filter_ip_address(Tail, IPString ++ Acc).

Comments on how to write this in a more Erlang way, make it more readable, or anything you would do different are welcome.


texts:
I have the following class:

Class Core {

public $security;
public $db;
public $extra;

public function __construct() {
    spl_autoload_register(array($this, 'loader'));
}

public function loader($name) {
    include $name.'.php';
}

public function __get($key) {
    return $this->extra[$key];
}

public function init( $extra ) {
    #error_reporting(0);
    $this->security = new Security();
    #$this->db = new Database();
    $extra = explode(",", $extra);
    if(is_array($extra)) {
        foreach($extra as $key) {
            $key = trim($key);
            $this->extra[$key] = new $key;
        }
    }
}
}

Index.php
    include 'core/Core.php';

$start = microtime(true);

$core = new Core();
$core->init('User, Control');

$core->Control->test2();

echo "<br />";

$core->User->test();

The purpose of this was to make it so I could load/instantiate classes only when I need them, but use the Core class on all pages.  I will of course check if the file exists or not, but I wanted some feedback on whether or not this was viable.  Also, is there an easier way to do what I'm trying achieve?


texts:
Here is a small C++11 utility collection to store any object that satisfies a given interface. Only the basic concepts are provided, I did not try to create a full collection:

#include <memory>
#include <utility>
#include <vector>
#include <boost/iterator/indirect_iterator.hpp>

template <typename Interface, template <typename> class Adapter>
class poly_collection
{
public:
    using iterator = boost::indirect_iterator<typename std::vector<std::unique_ptr<Interface>>::iterator>;

    template<typename T, typename... Args>
    auto push(Args&&... args)
        -> void
    {
        auto ptr = new Adapter<T>{ std::forward<Args>(args)... };
        entities.emplace_back(ptr);
    }

    template<typename T>
    auto push(T&& other)
        -> void
    {
        auto ptr = new Adapter<T>{ std::forward<T>(other) };
        entities.emplace_back(ptr);
    }

    auto begin()
        -> iterator
    {
        return { std::begin(entities) };
    }

    auto end()
        -> iterator
    {
        return { std::end(entities) };
    }

private:
    std::vector<std::unique_ptr<Interface>> entities;
};

Here is an example of use. Imagine you have an abstract class named Shape. For the sake of simplicity, it will only have one abstract method, draw:

struct Shape
{
    virtual void draw() const = 0;

    virtual ~Shape() {};
};

Now, you have some nice classes, Rectangle and Circle, that you didn't write but that satisfy the Shape interface:

struct Circle
{
    Circle(int x, int y, int radius) {}

    void draw() const
    {
        std::cout << "Circle\n";
    }
};

struct Rectangle
{
    Rectangle(int x, int y, int height, int width) {}

    void draw() const
    {
        std::cout << "Rectangle\n";
    }
};

You would like to store Rectangle and Circle instances in a colleciton as if they inherited from a common base class. With our solution, you only have to write a new class: ShapeAdapter, and then feed it to the poly_collection:

template<typename T>
struct ShapeAdapter:
    Shape
{
    template<typename... Args>
    ShapeAdapter(Args&&... args):
        data(std::forward<Args>(args)...)
    {}

    virtual void draw() const override
    {
        data.draw();
    }

    T data;
};

int main()
{
    poly_collection<Shape, ShapeAdapter> shapes;

    shapes.push<Circle>(1, 2, 3);
    shapes.push<Rectangle>(4, 5, 6, 7);

    Circle c = { 8, 9, 10 };
    shapes.push(c);

    for (auto&& shape: shapes)
    {
        shape.draw();
    }
}

So, what do you think of the idea? Would that be an interesting utility? Is there any way I could improve such a collection appart from adding some functions to mimick the standard library's collections ones?


texts:
LeetCode: Group Anagrams C#
Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

All inputs will be in lowercase.
The order of your output does not matter.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace StringQuestions
{
    /// <summary>
    /// https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/778/
    /// </summary>
    [TestClass]
    public class GroupAnagramsTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            string[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
            var result = GroupAnagramsClass.GroupAnagrams(strs);
            List<IList<string>> expected = new List<IList<string>>();
            expected.Add( new List<string> {"eat", "tea", "ate"});
            expected.Add( new List<string> {"tan", "nat"});
            expected.Add( new List<string> {"bat"});
            for (int i = 0; i < result.Count; i++)
            {
                CollectionAssert.AreEqual(expected[i].ToList(), result[i].ToList());
            }
        }
    }

    public class GroupAnagramsClass
    {
        public static IList<IList<string>> GroupAnagrams(string[] strs)
        {
            Dictionary<char[], List<string>> dict = new Dictionary<char[], List<string>>(new CharComparer());
            foreach (var str in strs)
            {
                var key = str.ToCharArray();
                Array.Sort(key);
                if (!dict.TryGetValue(key, out var temp))
                {
                    temp = dict[key] = new List<string>();
                }
                temp.Add(str);
            }

            List<IList<string>> res = new List<IList<string>>(dict.Values.ToList());
            return res;
        }
    }

    public class CharComparer : IEqualityComparer<char[]>
    {
        public bool Equals(char[] x, char[] y)
        {
            if (x == null || y == null)
            {
                return false;
            }

            if (x.Length != y.Length)
            {
                return false;
            }

            for (int i = 0; i < x.Length; i++)
            {
                if (x[i] != y[i])
                {
                    return false;
                }
            }

            return true;
        }

        public int GetHashCode(char[] obj)
        {
            return 0;
        }
    }
}

Please review for performance. I don't like me copying the dictionary into IList<IList<string>. Is there a better way to do so, considering this the desired API defined by the question?


texts:
I've been doing a simple Tic-Tac-Toe with PHP, generating only HTML code.

A few notes:

I didn't bother yet to give an AI to the opponents (the Os), and it is intentional.
There is no CSS style to it, I intend to append it with a css file.
tictactoe.php is naturally the name of the script itself, so each links are refering to the page itself.

Now I don't know if I did everything correctly, here are my concern:

If I want to expand the functionalities of the game in the future (adding javascript, opponent AIs, new game features), I fear that the structure of the code is not adapted for it. Should I change my code so it is Object Oriented? EDIT I have in mind to add new feature to the game, like powers who would change the state of the board, like rewind to a previous state and; some css and javascript in a non-intrusive way and add some way to check if options are disabled (like javascript/flash), or check for the version of the browser for html5/css3 features.
As for now, it is easy to "cheat" and directly introduce the wished board state. I would like to prevent that, and if possible without using javascript, as I want the game to be playable also without it.

<?php
//Determine if a player as aligned three of its symbols and return the id of the player (1
//for X Player, -1 for O Player(Computer)). Otherwise return 0;
function isWinState($board){
    $winning_sequences = '012345678036147258048642';
    for($i=0;$i<=21;$i+=3){
        $player = $board[$winning_sequences[$i]];
        if($player == $board[$winning_sequences[$i+1]]){
            if($player == $board[$winning_sequences[$i+2]]){
                if($player!=0){
                    return $player;
                }
            }
        }
    }
    return 0;
}

//Player O plays its turn at random
function OsTurn($board){
    if(in_array(0,$board)){
        $i = mt_rand(0,8);
        while($board[$i]!=0){
            $i = mt_rand(0,8);
        }
        $board[$i]=-1;
    }
    return $board;
}

$winstate = 0;
$values = array();

if(empty($_GET['values'])){
    //initializing the board
    $values = array_fill(0,9,0);
    //determine who begins at random
    if(mt_rand(0,1)){
        $values = OsTurn($values);
    }
}else{
    //get the board
    $values = explode(',',$_GET['values']);
    //Check if a player X won, if not, player 0 plays its turn.
    $winstate = isWinState($values);
    if($winstate==0){
        $values = OsTurn($values);
    }
    //Check if a player 0 won
    $winstate = isWinState($values);
}
//Display the board as a table
for($i=0;$i<9;$i++){
    //begin of a row
    if(fmod($i,3)==0){echo '
';}
    echo '';
    //representation of the player token, depending on the ID
    if($values[$i]==1){
        echo 'X';
    }else if($values[$i]==-1){
        echo 'O';
    }else{
        //If noone put a token on this, and if noone won, make a link to allow player X to
        //put its token here. Otherwise, empty space.
        if($winstate==0){
            $values_link = $values;
            $values_link[$i]=1;
            echo '&nbsp;';
        }else{
            echo '&nbsp;';
        }
    }
    echo '	';
    //end of a row
    if(fmod($i,3)==2){echo '
';}
}
?>

<?php
//If someone won, display the message
if($winstate!=0){
    echo '
Player '.(($winstate==1)?'X':'O').' won!
';
}
?>


texts: Short function to remove unnecessary whitespace

texts:
I have a function consisting of one line of code:

def trimString(string):
    """ Remove unnecessary whitespace. """
    return re.sub('\s+', ' ', string).strip()

But I've been debating with myself whether the following would be better, seeing as explicit > implicit.

def trimString(string):
    """ Remove unnecessary whitespace. """
    string = re.sub('\s+', ' ', string).strip()
    return string

So which is preferable, the former or the latter? And why is that the case?

The question may be off-topic but I find myself asking it often enough and thought this was the place to ask.


texts:
I am working on a pathfinding program / algorithm, and I have the following class:

[System.Serializable]
public class UnitTileCosts
{
    int[] tileCosts;

    public UnitTileCosts()
    {
        //empty constructor uses default value of 1 for all fields
        GenerateDefaults();
    }

    public UnitTileCosts(Dictionary<TileType,int> costs)
    {
        GenerateDefaults();
        foreach(var pair in costs)
        {
            tileCosts[(int) pair.Key] = pair.Value;
        }
    }

    void GenerateDefaults()
    {
        tileCosts = new int[System.Enum.GetNames(typeof(TileType)).Length];
        for(int i = 0; i < tileCosts.Length; i++)
        {
            tileCosts[i] = 1;
        }
    }

    public int GetTileCost(TileType tile)
    {
        return tileCosts[(int) tile];
    }
}

Is this better or worse than simply using a Dictionary<TileType, int> in the first place?

Using the Dictionary (that is passed in to the constructor), I would need to check if the key exists because I only care about those values that differ from the result. (Which, admittedly, is easily doable with TryGetValue and an OUT parameter)

I would think that an array of ints would serialize better than a dictionary, to boot.

Is casting from the enum to the int acceptable in this instance? I understand that enums are designed to avoid magic numbers, but in this case I only care about the numbers (and not the magic), so I think it might be reasonable.


texts:
Here's what my task is:

  Dependant on the "Logged In" user, they'll have different access rights and will see different menus.

I have tried using the .get() function.

choices = {1: "| Student Details", 2: "| Student Grades", 3: "| Finance", 4:"| Staff Details", 5:"| Staff Payments"}

print(choices.get(1))
print(choices.get(4))

GIVEN OUTPUT >>

| Student Details
| Staff Details

But it will look very inefficient with all the Access Rights. Some access rights have access to different menus e.g (Access Level 1 = Menu 1 and Menu 4). So I cannot just use a for loop to print all menus like so.

for option,num in choices.items():
    print(option,num)

I've also attempted using the itemgetter() function which is available in the operator module, but I was unable of figuring out how to:
1. Print the outcome in lines, 2. Numerate the outcome in order (1,2,3)

choices = {1: "|Student Details", 2: "| Student Grades", 3: "| Finance", 4:"| Staff Details", 5:"| Staff Payments"}

print(itemgetter(3,5)(choices))

GIVEN OUTPUT >>
('| Finance', '| Staff Payments')

REQUIRED OUTPUT >>
1 | Finance
2 | Staff Payments

Here's an example of the inefficient code I have at the moment:

if user_name == "Mike":
    print("-Managing Menu-")
    print("1 | Staff Payments. ")
    print("2 | Finance. ")
    option = int(input("Option Choice (1-2): "))
    while option not in range(1,2):
        option = int(input("Option Choice (1-2): "))
    if option == 1:
        print("Welcome to Staff Payments")
    elif option == 2:
        print("Welcome to Finance.")
    else:
        print("Error.")

I'd really appreciate any feedback and help with this task.


texts: Segmented Sieve of Eratosthenes in Scala

texts:
I'm trying to solve PRIME1 in SPOJ with the following Scala snippet:

  Peter wants to generate some prime numbers for his cryptosystem. Help
  him! Your task is to generate all prime numbers between two given
  numbers!

  Input

  The input begins with the number \$t\$ of test cases in a single line
  (\$t \le 0\$). In each of the next t lines there are two numbers \$m\$ and \$n\$ (\$1 \le m \le n \le 1000000000, n-m \le 100000\$) separated by a space.

  Output

  For every test case print all prime numbers \$p\$ such that \$m <= p <= n\$,
  one number per line, test cases separated by an empty line.

object _002_PRIME1 extends App {

  import scala.io.StdIn._

  /// ***1***
  // def isPrime(num: Int) = (2 until num).view.takeWhile(i => i * i <= num).forall(i => i * (num / i) < num)

  def sieve(m: Int, n: Int, step: Int, primeArray: Array[Boolean]): Unit = {
    val start = {
      if (m <= step) {
        2 * step
      } else {
        val pre = (m / step) * step
        if (pre == m) {
          pre
        } else {
          pre + step
        }
      }
    }
    Range(start, n + 1, step).foreach(i => primeArray(i - m) = false)
  }

  def simpleSieve(num: Int): IndexedSeq[Int] = {
    val basicPrimes = Array.fill(num - 1)(true)
    for {
      i <- 2 to num
      if basicPrimes(i - 2)
      j <- i * 2 to num by i
    } basicPrimes(j - 2) = false
    for {
      j <- basicPrimes.indices
      if basicPrimes(j)
    } yield (j + 2)
  }

  def sieveAll(m: Int, n: Int): Unit = {
    val primeArray = Array.fill(n - m + 1)(true)

    val basicPrimes = simpleSieve(math.sqrt(n).toInt)
    /// for(p<- basicPrimes)sieve(m, n, p, primeArray)
    basicPrimes.foreach(p => sieve(m, n, p, primeArray))
    if (m == 1) {
      primeArray(0) = false
    }
    for (j <- primeArray.indices; if primeArray(j)) println(j + m)
    /// ***2***
    //    Array.tabulate(primeArray.length) { i => {
    //      if (primeArray(i)) {
    //        println(i + m)
    //      }
    //    }
    //    }
  }

  (1 to readInt()).foreach(_ => {
    val ss = readLine().split("\\s+").map(_.toInt)
    val (m, n) = (ss.head, ss.last)
    sieveAll(m, n)
  })
}

For PRIME1 itself, this is able to output the correct answer within 0.6s. However for another problem, PRINT, which is almost the same except that the input range is bigger: \$2 \le L < U \le 2147483647, U-L \le 1000000\$, and the time limit is more restricted (1.223s).

When I submit this code, it always tells that time limit exceeded. How can I tune this snippet to make it run faster?

Attempts I've tried (the time costs are based on the OJ from PRIME1):

Using isPrime for basic primes checking, this would increase the running time to 0.7s.
Using Array.tabulate instead of for comprehension for output, decreasing time a little, about 0.01s.

Additionally, from Daniel C. Sobral's answer in the other question, mutable.BitSet may be more memory efficient, however this answer mentions that as to Java, an array might be more CPU efficient. I therefore didn't use BitSet for Scala (the memory used by is about 314MB while the memory limited by SPOJ is 1536MB).


texts: Parse a CSV file and return an object or array

texts:
I recently published a JavaScript module for NPM which is also available on Github by the name of rawiki-parse-csv. The code takes raw CSV data and returns an array. The method has one option to include the first line as a header in which case an object is returned within the array. If the option is not set each line will be returned as an array.

The project includes a Chai test which inputs some sample CSV data and checks the returned output with both options specified. The tests pass without issue and use in an actual application appears to be faultless.

Could someone comment on any issues with this code, potentials for failure, incorrect structure or areas for improvement?

/*
The MIT License (MIT)
Copyright (c) 2016 Rawikitua Isherwood
Parse module creates an object or set of arrays from a csv file by splitting the text at each new
line and splitting each line at comma marks.*/

var parse = function (input, option){
    try
    {
        // output object
        var data = {},
        // output no columns array
        container = [],
        // output array
        records = [],
        // splits csv data at each new line
        lines =input.split(/\r\n|\r|\n/),
        // creates columns by splitting first line of csv
        columns = lines[0].split(',');
        // creates objects from csv data if column option included
        if (option === true){

            // loop through each line of csv file
            for (var l = 1; l <= lines.length-1; l++)
            {
                // splits each line of csv by comma
                var words = lines[l].split(',');

                // builds object based on column headers
                for (var cell in columns)
                {
                    data[columns[cell]] = words[cell];
                }
                // pushes object to output array
                records.push(data);
                // resets object in order to add another
                data = {};
            }
        }
        else {
            // creates nested arrays from csv data if column option omitted,false or not true
            for (var l = 0; l <= lines.length-1; l++)
            {
                // splits each line of csv by comma
                var words = lines[l].split(',');
                // creates objects from csv data
                for (var cell in words)
                {
                    container.push(words[cell]);
                }
                // push array to output array
                records.push(container);
                // reset array in order to add another
                container = [];
            }
        }
        // returns output array
        return records
    }
    catch(err){
        return err
    }
}

module.exports = parse


texts:
To train my Python skills I have made a vocabulary trainer which runs on a terminal:

import random
import os
import sys

FILE_PATH = "./words.txt"

class Entry:
    def __init__(self, french, english):
        self.french = french
        self.english = english

entries = []

if os.path.isfile(FILE_PATH):
    words = open(FILE_PATH, "r")

    for line in words:
        words = line.split(",")
        entries.append(Entry(words[0].strip(), words[1].strip()))

def insert():
    while True:
        french = raw_input("French word: ")

        if french == "#":
            return

        english = raw_input("English word: ")

        if english == "#":
            return

        entries.append(Entry(french, english))
        backup_wordpairs()

def query():
    total = 0
    right = 0
    wrong = 0

    while True:
        i = random.randint(0, len(entries) - 1)
        french = raw_input("French translation of " + entries[i].english + ": ")

        # TODO: Add a statistics which is displayed before leaving (x of y correct. Equal z percent).
        if french == "#":
            percentage = (right  * 100) / total
            print("You answered " + str(right) + " question out of " + str(total) + " correct.")
            print("Percentage: " + str(percentage) + " %")
            return

        total = total + 1

        if french.strip() == entries[i].french.strip():
            print("Correct.")
            right = right + 1
        else:
            print("Wrong!")
            wrong = wrong + 1

def printall():
    if len(entries) == 0:
        print("No words stored.")
        return

    for i in range(len(entries)):
        print(entries[i].french + " : " + entries[i].english)

def backup_wordpairs():
    woerter = open(FILE_PATH, 'w')

    for wort_paar in entries:
        woerter.write(wort_paar.french + "," + wort_paar.english + "\n")

    woerter.close()

def reset_list():
    global entries

    entries = []

    if os.path.isfile(FILE_PATH):
        os.remove(FILE_PATH)

while True:
    command = raw_input("Please enter a command: ")

    if command == "add":
        insert()
    elif command == "test":
        query()
    elif command == "list":
        printall()
    elif command == "end":
        break
    elif command == "reset":
        reset_list()
    else:
        print("No known command.")

print(" ------- Vocabulary becomes terminated. ----------  ")
sys.exit()

My GitHub repository (including a README-file with user-instructions and a screenshot).

The application runs fine but I would appreciate feedback from more experienced Python-developers. What would you have done differently and why?


texts:
I am studying design patterns in go. I need a review of this implementation. I started this exercise from wikipedia description of the pattern and implementing step by step all the sentences.

I decided to use two objects: the pool and the object managed by the pool.

type PoolObject struct {
    id int
}

type Pool struct {
    idle   *list.List
    active *list.List
}

When pool is initialized two empty lists were created.

func InitPool() Pool {
    pool := &Pool{
        list.New(),
        list.New(),
    }
    return *pool
}

Any time an object is requested, it's returned from the idle list or created from scratch.

func (p *Pool) Loan() PoolObject {
    if p.idle.Len() > 0 {
        for e, i := p.idle.Front(), 0; e != nil; e, i = e.Next(), i+1 {
            if i == 0 {
                object := e.Value.(PoolObject)
                return object
            }
        }
    }

    object := PoolObject{p.NumberOfObjectsInPool() + 1}
    p.active.PushBack(object)
    return object
}

Any time an object is returned, it's removed from the active list and pushed in the idle list.

func (p *Pool) Receive(object PoolObject) {
    p.idle.PushBack(object)
    for e, i := p.active.Front(), 0; e != nil; e, i = e.Next(), i+1 {
        if object == e.Value.(PoolObject) {
            p.active.Remove(e)
            return
        }
    }
}


texts: Microservice that fetches data from REST repository endpoints on Github

texts:
I have code in Python 3 where I fetch data from the GitHub API, and I want some advice on the architecture of this code.
import urllib.request, urllib.parse, urllib.error
import json
import sys
from collections import Counter
from datetime import datetime, timedelta, date
from tabulate import tabulate
from LanguagesRepoCounter import LanguagesCounter
from RepoListLanguages import RepoListLanguages

#getting the date of one mounth ago from today
One_Mouth_ago_date = datetime.date(datetime.now()) - timedelta(days=30)

url = 'https://api.github.com/search/repositories?q=created:%3E'+One_Mouth_ago_date.isoformat()+'&sort=stars&order=desc&page=1&per_page=100'

data_connection_request  = urllib.request.urlopen(url)

unicoded_data = data_connection_request.read().decode()

try:
    json_data = json.loads(unicoded_data)
except:
    json_data = None
# testing retrieaved data
if not json_data or json_data["total_count"]<1:
    print(json_data)
    sys.exit('######## Failure To Retrieve ########')

#Counting the number of repo using every language
Lang_Dic_Count = LanguagesCounter(json_data)

# Getting the list of repo using every language
DicDataList = RepoListLanguages(json_data, Lang_Dic_Count)

# Displaye the repo's urls for every language
for key in DicDataList:
    print(key, ' language used in')
    for i in range(len(DicDataList[key])):
        print("                           ", DicDataList[key][i])

# Displaye the number of repos using every language in a table
table = []
for key in Lang_Dic_Count:
    under_table=[]
    under_table.append(key)
    under_table.append(Lang_Dic_Count[key])
    table.append(under_table)
print(tabulate(table, headers=('Language', 'number of Repo using it'), tablefmt="grid"))

and the first function is :
def LanguagesCounter(Data):
    ''' Count how many times every programming language is used in the 100 most starred repos created in the last 30 days given in a parameter as json object, return a dict with languages as a keys and number of repo using this language as a value
    '''
    Languages_liste = []
    for i in range(len(Data["items"])):
        Languages_liste.append(Data["items"][i]["language"])
    Lang_Dic_Count ={i:Languages_liste.count(i) for i in Languages_liste}
    return Lang_Dic_Count

the third function is:
def RepoListLanguages(Data, list):
    '''
    return the list of repositories from Data parameter for every programming language in the list parameter as a dictionary with the programming language as key and a list of repositories as value
    '''
    languagesRepo = {}
    for key in list:
        languagesRepo[key]= []
        for repo in range(len(Data["items"])):
            if (key == Data["items"][repo]["language"]):
                languagesRepo[key].append(Data["items"][repo]["html_url"])

    return languagesRepo

The code fetches the most starred repos from GitHub API that were created in the last 30 days, counts how many repos use every programming language, and lists the repo links for every language.


texts:
Problem is Talent Buddy.

Your task is to

  write a function that prints to the standard output (stdout) for each query the user name that matches the query
  if there are multiple user names matching the query please select the one that is the smallest lexicographically
  all string matches must be case insensitive
  if no match is found for a given query please print "-1"

  Note that your function will receive the following arguments:

  usernames
   - which is an array of strings representing the user names

  queries
   - which is an array of strings representing the queries described above

  Data constraints
   - the length of the array above will not exceed 100,000 entries
   - each name or query string will not exceed 30 characters

  Efficiency constraints

  your function is expected to print the requested result and return in less than 2 seconds

  Example

Input
names: ["james", "jBlank"]
queries: ["j", "jm", "jbl", "JB"]

Output
james
-1
jBlank
jBlank

The above is an example testcase.

My algorithm:

def typeahead(usernames, queries):
        from bisect import bisect_left
        wordlist=sorted(usernames,key=str.lower)
        l_wordlist=map(str.lower,wordlist)
        for i in queries:
            word_fragment=i.lower()
            k=wordlist[bisect_left(l_wordlist, word_fragment): bisect_left(l_wordlist, word_fragment[:-1] + chr(ord(word_fragment[-1])+1))][:1]
            print k[0] if k else  -1

Steps:

Sorted the usernames lexicographically
sorted usernames of small letters(this used in bisect)
using word_fragment i am bisecting the total array

When I profiled my method, I got this testcase:

         250005 function calls in 0.715 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 bisect.py:1(<module>)
        1    0.480    0.480    0.715    0.715 py1.py:24(typeahead)
   100000    0.146    0.000    0.146    0.000 {_bisect.bisect_left}
    50000    0.009    0.000    0.009    0.000 {chr}
        1    0.010    0.010    0.010    0.010 {map}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    50000    0.013    0.000    0.013    0.000 {method 'lower' of 'str' objects}
    50000    0.006    0.000    0.006    0.000 {ord}
        1    0.050    0.050    0.050    0.050 {sorted}

The problem is that when I run it in the Talent Buddy, it is showing that it takes more than 2 seconds. How can I further optimise my code?

Edit as reference with another question with this testcase. The efficient code provided took the below time:

        147936037 function calls in 52.394 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.002    0.002    0.002    0.002 collections.py:1(<module>)
        1    0.000    0.000    0.000    0.000 collections.py:26(OrderedDict)
        1    0.000    0.000    0.000    0.000 collections.py:381(Counter)
        1    0.000    0.000    0.000    0.000 heapq.py:31(<module>)
        1    0.000    0.000    0.000    0.000 keyword.py:11(<module>)
        1   27.895   27.895   52.394   52.394 py.py:24(typeahead)
   100000    0.014    0.000    0.014    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.002    0.002    0.002    0.002 {method 'join' of 'str' objects}
   100000    0.025    0.000    0.025    0.000 {method 'lower' of 'str' objects}
147736029   24.457    0.000   24.457    0.000 {method 'startswith' of 'str' objects}


texts: Receive an array input and output a string

texts:
I have some code which is working, but I would be interested if anyone could review it and tell me if there is a more efficient way of achieving my goal.

I receive input from a data source as an array such as ["Y","Y",,"Y","Y",,"Y"].

The values relate to investment fund names and I am outputting a string such as "Balanced, Cash, High Growth, Moderate and Growth options".

If there is only one value populated with "Y" the string could be "Conservative option".

If there are two values, the string could be "Conservative and Cash options".

For more than two values, the string could be "Conservative, Cash and Moderate options".

I know that the order of the values will always be the same, eg the first value will always be the Balanced option. Here is the code:

// balanced, cash, high growth, moderate and growth
var params = ["Y","Y",,"Y","Y",,"Y"];

getString(params)

function getString(values) {

// map for the values
var fundMap = {
    0: "Balanced",
    1: "Cash",
    2: "Conservative",
    3: "High Growth",
    4: "Moderate",
    5: "Shares",
    6: "Growth"
    }

var fundArray = [];

// get fund names from map and push to array
for (var i = 0; i < values.length; i++) {
    if (values[i] == "Y") {
        fundArray.push(fundMap[i]);
    }
}
console.log(fundArray);

var fundString = "";

if (fundArray.length == 1) {

    fundString = fundArray + " option";

}
 else if (fundArray.length == 2) {

    fundString = fundArray[0] + " and " + fundArray[1] + " options";
}

 else  {

    for (var i = 0; i < fundArray.length -2; i++) {
        fundString = fundString + fundArray[i] +  ", ";
    }

    fundString = fundString + fundArray[fundArray.length -2] + " and ";
    fundString = fundString + fundArray[fundArray.length -1] + " options";
}
console.log(fundString);
}

I would love to know if there is a more efficient or just a neater way of writing this code please.

Thank you!


texts: First Python script: number-guessing game with a global variable

texts:
This is my first Python script, and I was hoping to get some feedback.  I do have one specific question: is the use of global variables considered a bad practice?  When I used them below, my programmer's instincts immediately went off as though I was creating a code-smell, mostly because it seems much less elegant than just having a private String myVariable at the top of a Java class.  The use of global myVariable to force the scope seemed a bit hacky.  But I don't know a single thing about Python except what I wrote below, so I could be way off.

I also realize that the below code is more complex than it needs to be.  I know that it could be written in much fewer lines of code by removing function definitions and such (in fact, my first version was only like 15 lines).  But I wrote this more complicated version in order to get a handle on some of the basic concepts like sharing variables, returning from functions, etc.

Any tips or glaring style/best-practices issues are appreciated!  (I'm a style-Nazi with Java, so please, don't hold back so that I can learn!)

#!/usr/bin/python

from random import randint

# GLOBALS
guesses = 0
the_number = 0

def checkGuess(guess):
    global the_number

    if guess <= 0:
        return False
    elif guess == the_number:
        return True
    elif guess < the_number:
        print "The number is HIGHER."
    elif guess > the_number:
        print "The number is LOWER."

    return False

def isValid(guess):
    return len(guess) > 0 and guess.isdigit()

def getInput():
    global guesses
    input = ""

    while not isValid(input):
        input = raw_input("(#" + str(guesses) + ") Guess a number: ")
        if not isValid(input):
            print "Please guess an integer!"

    return int(input)

def runGame(min, max):
    global guesses
    global the_number

    the_number = randint(min, max)
    guess = 0

    print "I'm thinking of a number between " + str(min) + " and " + str(max) + " ..."

    while not checkGuess(guess):
        guesses = guesses + 1
        guess = getInput()

    print "YOU WON!"

def printTitle():
    print "----------------------"
    print "----- MASTERMIND -----"
    print "----------------------"
    print ""

def main():
    printTitle()
    runGame(1, 100)

main()


texts:
Inspired by this question: Split a string into chunks of the same length

The code is designed to work on text elements rather than chars to avoid unicode problems.

public static class StringExtensions
{
    public static IEnumerable<string> Partition(this string value, int chunkSize)
    {
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value));
        }
        if (chunkSize < 1)
        {
            throw new ArgumentOutOfRangeException(nameof(chunkSize));
        }
        var sb = new StringBuilder(chunkSize);
        var enumerator = StringInfo.GetTextElementEnumerator(value);
        while (enumerator.MoveNext())
        {
            sb.Append(enumerator.GetTextElement());
            for (var i = 0; i < chunkSize - 1; i++)
            {
                if (!enumerator.MoveNext())
                {
                    break;
                }
                sb.Append(enumerator.GetTextElement());
            }
            yield return sb.ToString();
            sb.Length = 0;
        }
    }
}

And a couple of unit tests

[TestMethod]
public void Partition_SplittingAnAsciiString_ShouldSplitTheStringIntoTheRequiredChunkSize()
{
    string input = "123456";
    string[] expected = { "123", "456" };
    string[] actual = input.Partition(3).ToArray();

    CollectionAssert.AreEqual(expected, actual);
}

[TestMethod]
public void Partition_SplittingAPartiallyDecomposedString_ShouldSplitTheStringIntoTheRequiredChunkSize()
{
    string input = "éée\u0301";
    string[] expected = { "é", "é", "e\u0301" };
    string[] actual = input.Partition(1).ToArray();

    CollectionAssert.AreEqual(expected, actual);
}

I usually use Machine Specifications for unit tests so any tips on writing MSTest unit tests would be great especially naming conventions!

The method feels slightly too long to me but I couldn't see a nice way of splitting it up.


texts:
I'm a new developer looking for some code review for my ES6 React Weather Application, want to learn from my mistakes and make sure I'm not picking up any bad habits. Anyone interested in pulling my repo and taking a look over my code? How's the layout? Any refactoring you can recommend? Areas that could be improved? Stupid mistakes or redundant work?

import React from 'react';
import { string, number, instanceOf, object, shape } from 'prop-types';

import Forecast from './Forecast';

ForecastDetails.propTypes = {
  location: shape({
    state: shape({
      day: object.isRequired,
      date: instanceOf(Date).isRequired,
      icon: string.isRequired,
      name: string.isRequired,
      maxTemp: number.isRequired,
      minTemp: number.isRequired,
      country: string.isRequired,
    }).isRequired,
  }).isRequired,
};

export default function ForecastDetails(props) {
  const {
    day, date, icon, name, maxTemp, minTemp, country,
  } = props.location.state;
  const details = (

          {name}, {country}

{day.weather[ 0 ].description}

max: {maxTemp} ºC

min: {minTemp} ºC

humidity: {day.humidity}

  );
  return (

        <Forecast date={date} icon={icon}>
          {details}
        </Forecast>

  );
}

React Open Weather Application - Github

Netlify - Live Demo


texts: Project Euler problems 18/67: maximum path sum

texts:
I recently solved problems 18/67 in Project Euler. My code is long and I think it could be more effective. I solved the problem with dynamic programming and am new to it, so I want to improve my dynamic programming.  I think my running time is acceptable: 0.214 seconds.

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class EighteenNSixtyseven {
@SuppressWarnings("rawtypes")
public ArrayList<ArrayList> readFile() {
    ArrayList<ArrayList> nodeList = new ArrayList<ArrayList>();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader("Triangle.txt"));
        String tmp = reader.readLine();
        while (tmp != null) {
            String[] nums = tmp.split("\\s+");
            ArrayList<Integer> nmb = new ArrayList<Integer>();
            for (int i = 0; i < nums.length; i++) {
                nmb.add(Integer.parseInt(nums[i]));
            }
            nodeList.add(nmb);
                                     // im adding an ArrayList to the ArrayList
            tmp = reader.readLine();    // where the first ArrayList index is the
        }                                // the specific row and the other ArrayList
                                        // containing the numbers
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return nodeList;
}
public static void main(String[] args) {
    EighteenNSixtyseven ad = new EighteenNSixtyseven();
    long start = System.currentTimeMillis();  // starting time
    @SuppressWarnings("rawtypes")               // eclipse suggested this??? Why?
    ArrayList<ArrayList> list = ad.readFile(); // reading the file with numbers in triangle
    int size = list.size() - 1;
    int calc = 0;
    int otherCalc = 0;
    int q = 0;
    ArrayList<Integer> temp1 = new ArrayList<Integer>();
    ArrayList<Integer> temp2 = new ArrayList<Integer>();
    while (size >= 1) {
        temp1 = list.get(size);
        temp2 = list.get(size - 1);
        q = 0;
        if (temp2.size() != 1) {
            while (q < temp2.size() - 1) {
                for (int k = 0; k < temp2.size(); k++) {    // checking which
                    calc = temp1.get(q) + temp2.get(k);        // sum gives the bigger on
                    otherCalc = temp1.get(q + 1) + temp2.get(k); // adding numbers
                    if (calc > otherCalc) {                        // in the lower line
                        temp2.set(k, calc);                    // with the ones in the line
                    } else {                                // over to the right and left
                        temp2.set(k, otherCalc);
                    }
                    q++;
                }
                size--;
            }
        } else {
            calc = temp1.get(0) + temp2.get(0);            // had to add this or the
            otherCalc = temp1.get(1) + temp2.get(0);    // array is outOufBounds
            if (calc > otherCalc) {
                temp2.set(0, calc);
                size--;
            } else {
                temp2.set(0, otherCalc);
                size--;
            }
        }
    }

    System.out.println("\nThe sum total is = " + temp2.get(0));
    long elapsedTimeMillis = System.currentTimeMillis() - start;
    float elapsedTimeSec = elapsedTimeMillis / 1000F;
    System.out.println("Tid " + elapsedTimeSec);
}
}

As you can see, the code is a bit messy! Any suggestions will be highly appreciated!


texts:
Recently, I've solved the "01 Matrix" LeetCode problem and the solution was accepted by the LeetCode OJ:

  Given a matrix consists of 0 and 1, find the distance of the nearest 0
  for each cell.

  The distance between two adjacent cells is 1.

  Example:

Input:
0 0 0
0 1 0
1 1 1

Output:
0 0 0
0 1 0
1 2 1

  Note:

  The number of elements of the given matrix will not exceed 10,000.
  There are at least one 0 in the given matrix.
  The cells are
  adjacent in only four directions: up, down, left and right.

The idea behind the solution above is to use Dynamic Programming - starting with 0 cells work outwards putting not processed cells on the queue:

from collections import deque

class Solution(object):
    def updateMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        if not matrix:
            return matrix

        row_length = len(matrix)
        col_length = len(matrix[0])

        queue = deque()

        # put all 0 cells on queue, set all other cells to a big number
        for row_index in range(row_length):
            for col_index in range(col_length):
                if matrix[row_index][col_index] == 0:
                    queue.append((row_index, col_index))
                else:
                    matrix[row_index][col_index] = 10000

        # work from the 0 cells outwards while the queue is not empty
        while queue:
            row_index, col_index = queue.popleft()
            for i, j in [(row_index - 1, col_index),
                         (row_index + 1, col_index),
                         (row_index, col_index - 1),
                         (row_index, col_index + 1)]:
                if 0 <= i < row_length and \
                   0 <= j < col_length and \
                   matrix[i][j] > matrix[row_index][col_index] + 1:
                        matrix[i][j] = matrix[row_index][col_index] + 1
                        queue.append((i, j))

        return matrix

Even though the code works, I am not happy with the readability, in particular:

setting the non-zero cells to "magical" 10000 does not look good
getting the cell neighbors and checking if they are not out-of-bounds seems overly complicated

What would you improve code style and organization or time and space complexity wise?


texts: Storing words from an input stream into a vector

texts:
I'm extremely new to C++ and am doing the exercises on the book Accelerated C++. Here is one of the exercises:

  4-5. Write a function that reads words from an input stream and stores
  them in a vector. Use that function both to write programs that count
  the number of words in the input, and to count how many times each
  word occurred.

How can I make this program better by only using vectors?

#include <iostream>
#include <algorithm>
#include <vector>
#include<string>
#include <stdexcept>
using std::cout; using std::cin; using std::vector; using std::sort; using std::string; using std::endl; using std::domain_error; using std::cerr;

//it said "count the number of words in the input, and to count how many times each word occurred". I cannot think of any return value if a function do two things, so I used void.
void run(const vector<string>& v) {
    if (v.size() == 0) throw domain_error("Nothing to count");
    cout << "words count: " << v.size() << endl;
    string unique = v[0];
    int count = 1;
    for (vector<string>::size_type i = 1; i < v.size(); ++i) {
        if (v[i-1] == v[i]) {
            count++;
        } else {
            cout << unique << ": " << count << endl;
            unique = v[i];
            count = 1;
        }
    }
    cout << unique << ": " << count << endl;
}

int main() {
    cout << "Enter all words followed by end of file." << endl;
    vector<string> words;
    string word;
    while (cin >> word) {
        words.push_back(word);
    }
    sort(words.begin(), words.end());
    try {
        run(words);
    } catch (domain_error e) {
        std::cerr << e.what() << endl;
    }
    return 0;
}


texts:
I'm using Microsoft SQL Server 2014 Express.

I found myself wanting to add the Columns CompanyNameChangeDate (1 through 10) and CompanyNameChangePreviousName (1 through 10) to a table in my database.

I wrote the following query to do it:

declare @i int
set @i = 0

Declare @nameChangeDatePrefix as varchar(255) = 'CompanyNameChangeDate'

Declare @nameChangePreviousNamePrefix as varchar(255) = 'CompanyNameChangePreviousName'

declare @sql as varchar(255)

while (@i < 10)
begin
    set @i = @i + 1

    set @sql = 'ALTER TABLE company_registry_data ADD ' + @nameChangeDatePrefix + Cast(@i as varchar(255)) + ' DATE'
    execute(@sql)

    set @sql = 'ALTER TABLE company_registry_data ADD ' + @nameChangePreviousNamePrefix + Cast(@i as varchar(255)) + ' VARCHAR(255)'
    execute(@sql)
end

How could I make it better?
What naming conventions have I contravened?
What habits should I start building right now?
What are the code smells?


texts:
I'm merging dictionaries together in series. Each one may/may not have lists as values. I'd like to merge indefinitely and, have the final merged dictionary contain only flat lists as values.

Any advice for how to write this as a single/simpler function?

def merge_dlist(dict_1, dict_2):
    """Merge_dlist accepts dictionaries to be merged."""
    merged_dict = defaultdict(list)
    merged_dict = merge_type(dict_1, merged_dict)
    merged_dict = merge_type(dict_2, merged_dict)
    return merged_dict

def merge_type(dictionary, merged_dict):
"""Merge dictionary keys. Append value items as strings to value list."""
for key, value in dictionary.items():
    if isinstance(value, list):
        for item in value:
            merged_dict[key].append(item)
    if isinstance(value, str):
        merged_dict[key].append(value)
return merged_dict


texts:
The challenge:

  Suppose you are inhabitant of a planet where 1, 7, and 9 are lucky digits. A lucky number for you is a number that contains only your lucky digits in it. For ex: 1, 79, 911, 9917 etc., are lucky, where as 5, 172, 93, 170 are not. Given a integer N, count the number of lucky numbers in the range 1 to N.
  [Constraints : 1 ≤ N ≤ 10^12. Time limit : 3s]

How can I make this code faster? As of now it exceeds way beyond 3 secs.

#include<stdio.h>
#include<time.h>
int lucky(long long int num)
{
    while(num>0)
    {
        if(!(num%10==1 || num%10==7 || num%10==9))
            return 0;
        num = num/10;
    }
    return 1;
}
int main()
{
    clock_t tic = clock();
    long long int num,i,count = 0;
    scanf("%lld",&num);

    for(i=1;i<=num;i++)
    {
        count += lucky(i);
    }

    printf("%lld\n",count );
    clock_t toc = clock();

    printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
    return 0;
}


texts: Optimizing the Sieve of Eratosthenes for prime generation

texts:
I've been on a Project Euler spree and I've been solving problems and as you might know, many of them require you to use prime numbers. I've been using the following code to generate and store primes in a vector, but was wondering if there is any non-obvious speed-ups that will make a large difference on the runtime of the generation.

// Generate the primes upto N using the Sieve of Eratosthenes.
template<typename T>
std::vector<T> generatePrimes(T n) {
    std::vector<T> result = std::vector<T>();
    if(n < 2) {
        return result;
    }
    std::vector<int> input(n + 1, 1);
    // Calculates the upper limit of the numbers to check.
    T sqrtN = (T)sqrt(n);
    // Iterate till the square root.
    for(T i = 2; i <= sqrtN; i++) {
        if(!input[i]) {
            continue;
        }
        // Multiples are marked false.
        for(T j = i * i; j <= n; j += i) {
            input[j] = 0;
        }
    }
    // Add to result vector.
    result.push_back(2);
    for(T i = 3; i <= n; i += 2) {
        if(input[i]) {
            result.push_back(i);
        }
    }
    return result;
}

And it is called like so:

vector<unsigned int> primes = generatePrimes<unsigned int>(10'000);

Is there any other way to speed this up? Before I had changed a line where I create the input vector to int from bool and it resulted in a nice 2.3x speed increase. See here for benchmark.


texts:
I have a script which can only be run by one specific user on a system. I need to let all users on the system have access to run that script and see the output. But there must never be more than one instance of the script running simultaneously.

I came up with this program to be run as the specific user who can run the script. This program will be left running listening on a TCP port. Any user who want to run the script then connects to the TCP port and the script will run.

#include <arpa/inet.h>
#include <errno.h>
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int setup_socket()
{
  const int one = 1;
  struct sockaddr_in6 bind_addr = {
    .sin6_addr = IN6ADDR_LOOPBACK_INIT,
    .sin6_family = AF_INET6,
    .sin6_port = htons(65454),
    .sin6_flowinfo = 0,
    .sin6_scope_id = 0,
  };
  int fd = socket(PF_INET6, SOCK_STREAM, 0);

  setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));

  if (bind(fd, (struct sockaddr*)&bind_addr, sizeof(bind_addr)))
    error(EXIT_FAILURE, errno, "bind() failed");

  if (listen(fd, 5))
    error(EXIT_FAILURE, errno, "listen() failed");

  return fd;
}

int main(int argc, char ** argv)
{
  int fd;

  if (argc < 2) {
    fprintf(stderr, "Usage: %s <command>\n", argv[0]);
    return EXIT_FAILURE;
  }

  fd = setup_socket();

  while (1) {
    int child_fd = accept(fd, NULL, NULL);
    pid_t child = fork();

    switch (child) {
    case -1:
      error(0, errno, "fork() failed");
      close(child_fd);
      break;
    case 0:
      if ((dup2(child_fd, 1) != 1) ||
          (dup2(child_fd, 2) != 2))
        error(EXIT_FAILURE, errno, "dup2() failed");
      execvp(argv[1], argv + 1);
      error(EXIT_FAILURE, errno, "excvp(%s) failed", argv[1]);
    default:
      close(child_fd);
      waitpid(child, NULL, 0);
    }
  }
}

Do you see any flaws in this program? I am mostly concerned with security problems, but also interested in hearing of any other problems you may see in the program.


texts:
I asked this question on Stack Overflow and in the comments someone had this to say.

  In a proper design, you should almost never have to do a dynamic_cast, even if it's hidden inside some nice getter function.

Now this got me thinking a lot. I have been thinking of various ways in which I could eliminate the dynamic_cast in question, or any cast for that matter from my code. Now I come here rather frustrated as the only thing I can think of to get rid of that cast; in that location is by doing the cast elsewhere.

So I ask, how can I improve upon this design?

#include <iostream>
#include <string>

// Properties for all components
class ComponentProperties {
public:
  ComponentProperties( std::string componentProperty ):
    componentProperty_( componentProperty ) { }

  virtual ~ComponentProperties(  ) {  }
  std::string getComponentProperty(  ) const { return componentProperty_; }

protected:
  std::string componentProperty_;
};

// Properties specific to Textboxes
class TextboxProperties: public ComponentProperties {
public:
  TextboxProperties( std::string componentProperty, std::string textboxProperty ):
    ComponentProperties( componentProperty ),
    textboxProperty_( textboxProperty ) {  }

  std::string getTextboxProperty(  ) { return textboxProperty_; }

private:
  std::string textboxProperty_;
};

class Component {
public:
  Component( ComponentProperties& properties ):
    properties_( properties ) {  }

  virtual ~Component(  ) {  }

protected:
  ComponentProperties& properties_;
};

class Textbox : public Component {
public:
  Textbox( TextboxProperties& properties ):
    Component( properties ) {  }

  // overload << purely for displaying properties.
  friend std::ostream & operator << ( std::ostream& out, const Textbox& textbox );
};

std::ostream & operator << ( std::ostream& out, const Textbox& textbox ) {
  return out << textbox.properties_.getComponentProperty(  ) << ", "
             << dynamic_cast< TextboxProperties& >( textbox.properties_ ).getTextboxProperty(  );
}

int main(  ) {
  TextboxProperties properties( "PropertyOne", "PropertyTwo" );
  Textbox textbox( properties );

  std::cout << textbox << std::endl;
  return 0;
}


texts: Double click to edit and add new value to li

texts:
$(document).on('dblclick', '#li', function () {
    oriVal = $(this).text();
    $(this).text("");
    input = $("<input type='text'>");
    input.appendTo('#li').focus();

});

$(document).on('focusout', 'input', function () {
    if (input.val() != "") {
        newInput = input.val();
        $(this).hide();
        $('#li').text(newInput);
    } else {
        $('#li').text(oriVal);
    }

});

So far, I still can't do OOP in jQuery.  Can you improve the above code?


texts:
Challenge

Write a program which reads a file containing Morse Code and outputs the conversion.

Specifications

The first argument is a path to a file.
The file contains multiple lines.
Each line is a string of morse code.

Each letter is separated by a space.
Each word is separated by two spaces.

Constraints

The input file is correctly formatted.
The Morse Code strings are alphanumeric.

Sample Input

.- ...- ..--- .-- .... .. . -.-. -..-  ....- .....
-... .... ...--

Sample Output

  AV2WHIECX 45
  BH3

Source

My Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Solution {
    private static final Map<String, Character> morseAlphabet = new HashMap<>();

    static {
        morseAlphabet.put(".-", 'A');
        morseAlphabet.put("-...", 'B');
        morseAlphabet.put("-.-.", 'C');
        morseAlphabet.put("-..", 'D');
        morseAlphabet.put(".", 'E');
        morseAlphabet.put("..-.", 'F');
        morseAlphabet.put("--.", 'G');
        morseAlphabet.put("....", 'H');
        morseAlphabet.put("..", 'I');
        morseAlphabet.put(".---", 'J');
        morseAlphabet.put("-.-", 'K');
        morseAlphabet.put(".-..", 'L');
        morseAlphabet.put("--", 'M');
        morseAlphabet.put("-.", 'N');
        morseAlphabet.put("---", 'O');
        morseAlphabet.put(".--.", 'P');
        morseAlphabet.put("--.-", 'Q');
        morseAlphabet.put(".-.", 'R');
        morseAlphabet.put("...", 'S');
        morseAlphabet.put("-", 'T');
        morseAlphabet.put("..-", 'U');
        morseAlphabet.put("...-", 'V');
        morseAlphabet.put(".--", 'W');
        morseAlphabet.put("-..-", 'X');
        morseAlphabet.put("-.--", 'Y');
        morseAlphabet.put("--..", 'Z');
        morseAlphabet.put("-----", '0');
        morseAlphabet.put(".----", '1');
        morseAlphabet.put("..---", '2');
        morseAlphabet.put("...--", '3');
        morseAlphabet.put("....-", '4');
        morseAlphabet.put(".....", '5');
        morseAlphabet.put("-....", '6');
        morseAlphabet.put("--...", '7');
        morseAlphabet.put("---..", '8');
        morseAlphabet.put("----.", '9');
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println(args.length > 1 ? "Excessive arguments, only the first will be considered" : "No arguments provided.");
            System.exit(1);
        }

        try (Scanner fileScanner = new Scanner(new File(args[0]))) {
            while (fileScanner.hasNextLine()) {
                System.out.println(decode(fileScanner.nextLine()));
            }
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        }
    }

    private static String decode(String morse) {
        StringBuilder decoded = new StringBuilder();

        String[] words = morse.split("\\s{2}");
        for (String word : words) {
            decoded.append(' ');
            String[] letters = word.split("\\s");
            for (String letter : letters) {
                decoded.append(morseAlphabet.get(letter));
            }
        }

        return decoded.substring(1);
    }
}

Tests:

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class TestMorseConversion {
    @Test
    public void testCodeReviewMorse() {
        assertEquals(Morse.decode("-.-. --- -.. .  .-. . ...- .. . .--"), "CODE REVIEW");
    }

    @Test
    public void test2ndMonitor() {
        assertEquals(Morse.decode("..--- -. -..  -- --- -. .. - --- .-."), "2ND MONITOR");
    }

    @Test
    public void testFromCodeEval() {
        assertEquals(Morse.decode("..-. .-. --- --  -.-. --- -.. . . ...- .- .-.."), "FROM CODEEVAL");
    }
}

Note: The Morse class simply contains the map and decode method utilized above to facilitate testing.


texts: Limit drive starts with function block diagram

texts:
I have a drive (modulating fan) which needs to be interlocked and prevented from starting. The requirement is that:

  The drive is limited to 3 starts per hour with a minimum of 10 minutes between starts.

I am programming using function blocks diagrams. Some information to aid in your understanding of the function block diagram I created:

Program flow follows the execution numbers on the function blocks
Cyan lines show values of the integer short data type
Black lines show binary values (0/1)
References (small rounded rectangles with an alphanumeric identifier and no execution number) are used to move data without the need for connecting lines

Many of the blocks used are self-explanatory, however, the following information may be of use:

diss function block - routes either in1 or in2 to out depending on bse. When bse equals 0, in1 is used
ccob/ccos depends on the mode. 1 = rising edge, 2 = falling edge
dvss function block - outputs the min/max of the two inputs

Here is the function block diagram. I am interested in an alternate or more efficient methods to achieve the requirement.

I have exported my loop diagram as an SVG.

I have broken the function block diagram into three views:


texts:
I've written an answer to HackerRank's Angry Professor problem. Please let me know if there's a quicker/better way of solving this as I think I wrote quite a bit of code for this problem (answer has to be in 1 class btw). Also, any improvements on my code in Java 8 are welcome too.

Problem statement (as written on HackerRank):

  The professor is conducting a course on Discrete Mathematics to a
  class of N students. He is angry at the lack of their discipline, and
  he decides to cancel the class if there are less than K students
  present after the class starts.

  Given the arrival time of each student, your task is to find out if
  the class gets cancelled or not.

Answer:

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

public class AngryProfessor {
    public static void main(String[] args) {
        List<List<List<Integer>>> testCases = readInput();

        for(List<List<Integer>> testCase : testCases){
            int numStudents = testCase.get(0).get(0);
            int minStudents = testCase.get(0).get(1);
            // Gotta STDOUT in hacker rank for it to be graded.
            System.out.println(isLectureCancelled(calcNumAttending(testCase.get(1), numStudents), minStudents));
        }
    }

    private static void addData(List<Integer> arrayList, String[] numbersToAdd){
        for(String num : numbersToAdd){
            arrayList.add(Integer.valueOf(num));
        }
    }

    /**
     * Calculates the number of students that make the lecture on time.
     *
     * @param studentTimes    the relative time at which the student arrives (student is on time if time is <= 0)
     * @param numStudents     number of students that make the lecture on time
     * @return numStudents
     */
    private static int calcNumAttending(List<Integer> studentTimes, int numStudents){
        int numAttending = 0;
        for(int i = 0; i < numStudents; i++){
            if(studentTimes.get(i) <= 0){
                numAttending++;
            }
        }
        return numAttending;
    }

    /**
     * Determines whether the lecture is cancelled or not.
     *
     * @param numAttending    Number of students who attend the lecture
     * @param minStudents     Minimum number of students for the lecture to go ahead
     * @return whether the lecture is cancelled or not
     */
    private static String isLectureCancelled(int numAttending, int minStudents){
        return numAttending < minStudents ? "YES" : "NO";
    }

    /**
     * Reads and stores all the data given. Each index is a test case. At that index is a list containing two lists. One
     * for each line of input that's read. The first list contains numStudents and minStudents, and the second list
     * contains the student times.
     *
     * @return a List containing all the data.
     */
    private static List<List<List<Integer>>> readInput(){
        Scanner k = new Scanner(System.in);
        int numTestCases = Integer.valueOf(k.nextLine());
        List<List<List<Integer>>> testCases = new ArrayList<>(numTestCases);

        // fills up testCases with ArrayLists before filling up with numbers
        for(int i = 0; i < numTestCases; i++){
            List<List<Integer>> list = new ArrayList<>(2);
            for(int j = 0; j < 2; j++){
                list.add(new ArrayList<>());
            }
            testCases.add(list);
        }

        // Inputs data into the ArrayLists
        for(int i = 0; i < numTestCases; i++) {
            String line1 = k.nextLine();
            String line2 = k.nextLine();
            addData(testCases.get(i).get(0), line1.split(" "));
            addData(testCases.get(i).get(1), line2.split(" "));
        }
        k.close();
        return testCases;
    }
}


texts: Get radial distance between vector1 and vector2

texts:
A small script to calculate total units of distance between two vector entities. Especially useful in games and grid snaps, inventory snaps etc..

typedef struct COORD
{
    int X, Y;
} coord;

int get_dist (coord entity1, coord entity2)
{
    int minuendX    = max(entity1.X, entity2.X);
    int minuendY    = max(entity2.Y, entity2.Y);
    int subtrahendX = min(entity1.X, entity2.X);
    int subtrahendY = min(entity2.Y, entity2.Y);

    return (minuendX - subtrahendX) + (minuendY - subtrahendY);
}


texts:
This is a class representing a city in a mod I am creating for Minecraft. All the constructor parameters are mandatory and they are used to help the class that calculates and builds the Paths, Buildings etc.

The City class has all the fields that are listed in the constructor including a 2D array that is a representation of the city in X and Z axes. There are also 2 methods to serialize and deserialize the data in order to save them using the Minecraft Forge API.

public City(int id, BlockPos startingPos, int citySize, int edgeLenght, int pathExtends, Block groundBlock, Block pathBlock, boolean hasMainStreets, boolean hasPaths) {
    this.id = id;

    this.startingPos = startingPos;

    this.chunkLength = citySize;

    this.cityLength = citySize * 16;
    this.edgeLength = edgeLenght;
    this.mapLength = cityLength + edgeLenght + blockStart;

    this.pathExtends = pathExtends;

    this.hasMainStreets = hasMainStreets;
    this.hasPaths = hasPaths;

    this.groundBlock = groundBlock;
    this.pathBlock = pathBlock;

    this.blockStart = edgeLenght;

}

Initializing a city object looks like:

BlockPos startingPos = new BlockPos(1000,63,1000);
int citySize = 5; // Will be pseudorandom
int edgeLength = 4;// Will be pseudorandom
int pathExtends = 2;// Will be pseudorandom
City newCity = new City(++id, startingPos, citySize, edgeLength, pathExtends, Blocks.OBSIDIAN, Blocks.DIAMOND_BLOCK, true, true);

From an organizational point of view I can see the benefits of this approach but is this a good practice? Does it involve any pitfalls I have not thought about or is there a better way to do this?

This is not easy to read and understand and I was wondering if there was any better way to do it. My idea was to create CitySettings object hence making more readable the City object by moving all these fields to another class.

I am thinking of creating a class CitySettings to hold all of City's fields and an instance of CitySettings that will be stored as a field in the City class.