texts: Message classification with Levenshtein Distance

texts:
I have a Python script that classifies messages. Each message carries a score, which is tallied up later in the script. It looks for messages that look alike, and puts them into a category.

items = []
cats = collections.OrderedDict()

# Do some preparation with the messages
punctuation_re = re.compile(r"([^\w\s.])")
multiple_spaces_re = re.compile(r"\s+")

# Load the messages from the CSV
with open('sentences.csv', encoding='utf-8') as f:
    reader = csv.DictReader(f, fieldnames=["message", "score"])
    for row in reader:
        match_desc = re.sub('(\s+)(a|an|and|the|is|are|or|to|on|under|in|about|at|have|had|was|were)(\s+)', '\1', match_desc)
        match_desc = re.sub(punctuation_re, "", match_desc)
        match_desc = re.sub(multiple_spaces_re, " ", match_desc)
        row["match_desc"] = match_desc.strip().lower()
        items.append(row)

# Match the items
for item in sorted(items, key=lambda x: len(x["match_desc"])):
    hasMatch = False

    if len(item["match_desc"]) <= 5:
        # Don't bother
        continue
    elif len(item["match_desc"]) > 15:
        # If the string is longer than 15 characters, use Levenshtein distance
        for k, v in reversed(cats.items()):
            # If string length difference is greater than maximum Levinshtein distance allowed, skip
            if (abs(len(item["match_desc"]) - len(k)) > math.ceil(len(item["match_desc"]) * 0.2)):
                continue

            # Else compute the Levenshtein distance
            if item["match_desc"] == k or Levenshtein.distance(item["match_desc"], k) < math.ceil(len(item["match_desc"]) * 0.2):
                cats[k].append(item)
                hasMatch = True
                break
    else:
        # Use exact match
        if item["match_desc"] in cats.keys():
            # Exact match
            cats[item["match_desc"]].append(item)
            continue
    if not hasMatch:
        cats[item["match_desc"]] = [item]

The problem is this script is \$O(n^2)\$, and struggles with large datasets as the script will need to go through more items to find a match. For example, a 70000-message dataset with varying lengths of messages takes 20 minutes on my machine (Python 3.6.3).

Some speedups I've included are:

Discarding messages that are too short
Only run Levenshtein distance if the string's lengths are similar (I use python-Levenshtein which is written in C)
Making cats an OrderedDict() and reversing it so that it's more likely to exit early (as the list of messages is sorted, it's more likely to find a match looking at what's recently inserted)

Are there any avenues of speedups possible that I'm missing?


texts:
I wanted to make a very simply Battleship game in Java, any feedback is welcome.

Nevermind the getters / setters. Just assume they are there.

class Game {
    Board board = new Board();

    void playGame() {
        Scanner scanner = new Scanner(System.in);
        while (!board.allShipsSank()) {
            System.out.println("Enter missile locations, x and y.");
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            board.shoot(x, y);
        }
    }
}

class Board {
    Set<Ship> ships = new HashSet<>();

    boolean allShipsSank() {
        for (Ship ship : ships)
            if (!ship.isSank())
                return false;
        return true;
    }

    void shoot(int x, int y) {
        for (Ship ship : ships) {
            if (ship.shipGeographic.orientation == ShipGeographic.Orientation.HORIZONTAL) {
                if (y == ship.shipGeographic.y && ship.shipGeographic.x <= x && x <= ship.shipGeographic.x + ship.len) {
                    ship.missileAt(x - ship.shipGeographic.x);
                    return;
                }
            }
            if (ship.shipGeographic.orientation == ShipGeographic.Orientation.VERTICAL) {
                if (x == ship.shipGeographic.x && ship.shipGeographic.y <= y && y <= ship.shipGeographic.y + ship.len) {
                    ship.missileAt(ship.shipGeographic.y + y);
                    return;
                }
            }
        }
    }
}

class ShipGeographic {
    enum Orientation {
        HORIZONTAL, VERTICAL;
    }

    int x;
    int y;
    ShipGeographic.Orientation orientation;
}

class Ship {
    // length of the ship
    int len;

    // Nodes where this ship has been hit
    Set<Integer> hit = new HashSet<>();

    // Where this Ship is
    ShipGeographic shipGeographic;

    Ship(int len) {
        this.len = len;
    }

    boolean isSank() {
        return hit.size() == len;
    }

    // For example, if ship is hit at head, parameter is 0
    // Missile at same node of ship has no effect
    void missileAt(int offsetFromLen) {
        if (hit.add(offsetFromLen)) {
            System.out.println("boom!");
            System.out.println(hit);
        }
    }
}

here is how I initialize and run the game:

class App {
    public static void main(String[] args) {
        Game game = new Game();

        // Just some sample data!
        {
            Ship ship = new Ship(3);
            ShipGeographic shipGeographic = new ShipGeographic();
            shipGeographic.orientation = ShipGeographic.Orientation.HORIZONTAL;
            shipGeographic.x = 1;
            shipGeographic.y = 1;

            ship.shipGeographic = shipGeographic;

            game.board.ships.add(ship);
        }

        game.playGame();
    }
}

A sample run:

Enter missile locations, x and y.
1
1
boom!
[0]
Enter missile locations, x and y.
5
5
Enter missile locations, x and y.
2
1
boom!
[0, 1]
Enter missile locations, x and y.
3
1
boom!
[0, 1, 2]

Process finished with exit code 0


texts: Returns all primes p between m <= p <= n

texts:
This is my submission for the Prime Generator on SPOJ and it was accepted. Are there any improvements/changes I can make?

  Input:

  The input begins with the number \$t\$ of test cases in a single line
  (\$t \le 10\$). 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 \le p \le n\$,
  one number per line, test cases separated by an empty line.

  Example:

  Input:

2
1 10
3 5

  Output:

2
3
5
7

3
5

#include <iostream>
#include <cmath>
#include <vector>

using std::vector;
using std::cout;
using std::cin;

bool isPrime(int n) {
    if (n == 1) return false;
    if (n == 2) return true; // invariant
    int root = int(ceil(sqrt(n))); // check up to ceil of square root n
    for (int i = 2; i <= root; ++i){
        if (n % i == 0) return false; // not prime
    }
    return true;
}

int main() {
    int lines;
    int toPush;
    vector<int> inputs;
    // get inputs
    cin >> lines;
    int tempA = 0;
    while (tempA < 2*lines) {
        cin >> toPush;
        inputs.push_back(toPush);
        ++tempA;
    }

    auto i = inputs.begin();
    while (i < inputs.end()){
        int m = *i;
        int n = *(i + 1);
        while (m <= n){
            if (isPrime(m)){
                int value = m;
                cout << value << " ";
            }
            ++m;
        }
        cout << "\n";
        std::advance(i, 2);
    }
}


texts: Is this binary search close to idiomatic OCaml?

texts:
let binsearch ~arr ~cmp x = (
    let cmpx = cmp x in
    (* Assuming arr is ordered according to cmp, then (bs min max) is an   *)
    (* index of a value v in arr such that ((cmp x value) = 0) between     *)
    (* min (inclusive) and max (exclusive).                                *)
    let rec bs min max =
      if min >= max then (
        None
      ) else (
        (* mid is always strictly less than max because min < max. *)
        let mid = (min + max) / 2 in
        let delta = (cmpx (Array.get arr mid))
        in (
          if delta = 0 then (
            Some mid
          ) else if delta < 0 then (
            (* since mid < max, we make progress *)
            bs min mid
          ) else (
            bs (mid + 1) max
          )))
    in bs 0 (Array.length arr));;

and then it can be used thus

let a = [|1; 2; 4; 4; 4; 7; 9; 9; 11; 16|];;

let bs = binsearch ~arr:a ~cmp:compare;;

let results = (bs 0, bs 1, bs 2, bs 3, bs 4, bs 5, bs 6, bs 7, bs 8,
               bs 9, bs 10, bs 11, bs 12, bs 13, bs 14, bs 15, bs 16, bs 17);;

 (results = (None, Some 0, Some 1, None, Some 2, None, None, Some 5, None,
             Some 7, None, Some 8, None, None, None, None, Some 9, None));;


texts: Retrieving data from SQL DB based on user input

texts:
I wrote this to connect to a local DB using my local login credentials. It pulls back card information based on the user's input.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace SQL_Console{
public class Info
{

//SQL Sever connection

    public static string connstring = @"Data Source=localhost\MAYDAY;Initial Catalog=NV; Integrated Security=SSPI; Connection Timeout=5";

    public static string ConnectionString
    {
        get
        {
            return ConnectionString;
        }
        set
        {
            connstring = value;
        }
    }
}

public class Lookup
{

//SQL Query

        public static string squery = "Select Cardnumber, CardHolder, ExpireDate from CreditCardTransactionHistory where clientnumber = (select clientnumber from foliolink where folionumber = @fnumber)";

}

//Execution

    class Program
{
    static void Main(string[] args)
    {
        string sqlconn = Info.connstring;

        Console.WriteLine("Enter Folio Number:");
        int fnum = Convert.ToInt32(Console.ReadLine());

        Console.Clear();

        SqlConnection sqlcon1 = new SqlConnection(sqlconn);
        sqlcon1.Open();

        SqlCommand sql1 = new SqlCommand(Lookup.squery, (sqlcon1));

        sql1.Parameters.AddWithValue("@fnumber", fnum);
        SqlDataReader reader = sql1.ExecuteReader();

        while (reader.Read())
        {
            Console.Write("Card Number: {0}\nCard Holder: {1}\nExpiration: {2}\n\n", reader[0], reader[1], reader[2]);

        }
        Console.ReadLine();
        sqlcon1.Close();
    }

}
}


texts: Hours and Minutes math in a work week calculator

texts:
I have written a small bit of code to tell me how many hours I need to work to finish up my 40 hours a week each day.

I can add hours per day and it will calculate total hours left in the work week.

My main issue with it is the way my math is written. It just seems so complicated and unnecessary but I was unable to find a better solution and was hoping someone could point me in the right direct for a better formula.

If you check the hours_left_update(self) method you will see that I am using floats, the Decimal method with str and quantize as well as split. All to try and get an output to a label that shows my results in hours and minutes.

Keep in mind when you put in hours worked the time clock system I get my information from uses a decimal system to display work hours. So if I worked 7 and 1/2 hours one day it would show me 7.50 hours worked. This is the kind of format I am putting into the program and it automatically convert that number to display as 7 hours 30 min.

from decimal import Decimal, ROUND_HALF_UP
from time import strftime
import tkinter as tk
import datetime

class TimeClockApp(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.master = master
        self.hours_worked = 0.00
        self.dtlbl = tk.Label(self.master, text="Current Date-Time: {} ~ {}".format(datetime.date.today(),strftime("%H:%M:%S")))
        self.dtlbl.grid(row=0, column=0, columnspan=2)

        self.lbl1 = tk.Label(self.master, text="Hours worked").grid(row=1, column=0, columnspan=2)

        weekdays = ["Monday: ", "Tuesday: ", "Wednesday: ", "Thursday: ", "Friday: "]
        for i in range(5):
            tk.Label(self.master, text=weekdays[i], anchor = "e").grid(row=i+2, column=0, sticky="e")

        self.lbl7 = tk.Label(self.master, text="Total Hours worked:").grid(row=7, column=0, sticky="e")
        self.lbl8 = tk.Label(self.master, text="00h 0m")
        self.lbl8.grid(row=7, column=1, sticky="w")

        self.lbl9 = tk.Label(self.master, text="Hours left to 40:").grid(row=8, column=0, sticky="e")
        self.lbl10 = tk.Label(self.master, text="40h 0m")
        self.lbl10.grid(row=8, column=1, sticky="w")

        self.entry_list = []

        for i in range(5):
            self.entry_list.append(tk.Entry(self.master,width=7))
            self.entry_list[i].bind("<Key>", lambda x: self.master.after(500, self.hours_left_update))
            self.entry_list[i].grid(row = i+2, column = 1, sticky = "w")

        self.status_clock()

    def status_clock(self):
        self.dtlbl.config(text ="Current Date-Time: {} ~ {}".format(datetime.date.today(),strftime("%H:%M:%S")))
        self.dtlbl.after(1000, lambda: self.status_clock())

    def hours_left_update(self):
        for entry in self.entry_list:
            if entry.get() != "":
                try:
                    #print(Decimal(entry.get()).quantize(Decimal("0.01"), ROUND_HALF_UP))
                    self.hours_worked += float(entry.get())
                except:
                    pass

        x = str(Decimal(str(self.hours_worked)).quantize(Decimal("0.01"), ROUND_HALF_UP)).split('.')
        m60 = "00"

        if int(x[1]) != 0:
            m60 = Decimal(str(60 * float("0.{}".format(x[1])))).quantize(Decimal("1"))

        self.lbl8.config(text="{}h {}m".format(x[0], m60))

        var = 40 - int(x[0])
        if int(x[1]) != 0:
            var = 39 - int(x[0])

        x2 = "00"

        if Decimal(str(60 * float("0.{}".format(x[1])))).quantize(Decimal("1")) != 0:
            x2 = (60 - Decimal(str(60 * float("0.{}".format(x[1])))).quantize(Decimal("1")))

        self.lbl10.config(text="{}h {}m".format(var,x2))

        self.hours_worked = 0.00

if __name__ == "__main__":
    root = tk.Tk()
    app = TimeClockApp(root)
    root.mainloop()


texts: Optimizing solution for Project Euler Problem #23 (non-abundant sums)

texts:
Project Euler Problem 23 asks:

  A perfect number is a number for which the sum of its proper divisors
  is exactly equal to the number. For example, the sum of the proper
  divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28
  is a perfect number.

  A number n is called deficient if the sum of its proper divisors is
  less than n and it is called abundant if this sum exceeds n.

  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the
  smallest number that can be written as the sum of two abundant numbers
  is 24. By mathematical analysis, it can be shown that all integers
  greater than 28123 can be written as the sum of two abundant numbers.
  However, this upper limit cannot be reduced any further by analysis
  even though it is known that the greatest number that cannot be
  expressed as the sum of two abundant numbers is less than this limit.

  Find the sum of all the positive integers which cannot be written as
  the sum of two abundant numbers.

I have been trying to optimize my solution for almost a day now but my program is not ready to get small and optimized. Can anyone please tell me how I can do that?

def isabundant(n): return sum(list(x for x in range(1, int(n/2)+1) if n % x == 0)) > n
abundants = list(x for x in range(1, 28123) if isabundant(x) == True)
sums = 0
for i in range(12, 28123):
    for abundant in abundants:
        if abundant >= i and isabundant(i+abundant) == True: sums += i
print(sums)


texts: std::string/std::wstring template wrapper for Win32 API

texts:
I have not completed this but want to make my own template library for wrapping the Win32 API to make it compatible with std::string/std::wstring... Here's a sample of what I've worked with so far.

My questions are:

Is this a good idea?
Is it acceptable to undefine Windows API macros (e.g. #undef GetWindowText)?
Is there perhaps a better way to do this besides changing the name scheme (e.g. getWindowText or GetWindowString as opposded to GetWindowText)? I prefer not to change the names.

Note: Please don't provide answers like "why don't you just use WTL?" or "just use MFC". I prefer to deal directly with the Windows API; I just want to make it easier to work with std::basic_string.

Implementation

#ifdef _WINUSER_
#undef GetWindowTextLength
template<typename _T> int GetWindowTextLength(HWND hWnd);
template<> int GetWindowTextLength<wchar_t>(HWND hWnd) { return ::GetWindowTextLengthW(hWnd); }
template<> int GetWindowTextLength<char>(HWND hWnd) { return ::GetWindowTextLengthA(hWnd); }

#undef GetWindowText
template<typename _T> std::basic_string<_T> GetWindowText(HWND hWnd);
template<> std::basic_string<wchar_t> GetWindowText(HWND hWnd)
{
    std::size_t len = GetWindowTextLength<wchar_t>(hWnd)+1;
    std::vector<wchar_t> buffer(len);
    ::GetWindowTextW(hWnd, buffer.data(), len);
    return std::basic_string<wchar_t>(buffer.begin(), buffer.end());
}
template<> std::basic_string<char> GetWindowText(HWND hWnd)
{
    std::size_t len = GetWindowTextLength<char>(hWnd)+1;
    std::vector<char> buffer(len);
    ::GetWindowTextA(hWnd, buffer.data(), len);
    return std::basic_string<char>(buffer.begin(), buffer.end());
}
#endif//_WINUSER_

Example Usage

std::basic_string<TCHAR> text = GetWindowText(hWnd);


texts: Function for checking if a string is a path or an URL be improved

texts:
I made myself a function to check if a string is a path or an URL:
import os

def isPath(s):
    """
    @param s string containing a path or url
    @return True if it's a path, False if it's an url'
    """
    if os.path.exists(s): # if a file with name s exists, we don't check any further and just return True
        return True
    elif s.startswith("/"): # clearly a path, urls never start with a slash
        return True
    elif "://" in s.split(".")[0]: # if a protocol is present, it's an url
        return False
    elif "localhost" in s: # special case for localhost domain name where splits on . would fail
        return False
    elif len(s.split("/")[0].split(".")) > 1: # dots before the first slash, normally separating TLD and domain name
        return False
    elif len(s.split("/")[0].split(":")) > 1: # if colons are present, either it's a IPv6 adress or there is a port number
        return False
    else: # all possible cases of an url checked, so it must be a path
        return True

Did I miss any cases of an url / path, and can the function be improved in some way ?


texts: Handler for a control to pan a map in four directions

texts:
I have a pan control that look like this:

Pretty standard Google Mapsish controls, IMO.

When the user clicks in the top 3rd of the control, it should pan up (deltaY = +1); right third means it should pan east (deltaX = -1); Down is deltaY = -1, and West is deltaX = +1. The control is 50px, square. I have working code, but I believe it can be written much more elegantly than this using a single (if discontinuous) mathematical function.

$(control).click(function (evt) {
    var clickPointX = (evt.layerX || evt.offsetX),
        clickPointY = (evt.layerY || evt.offsetY),
        deltaX,
        deltaY;

    // control is 50x50 px.
    // Click in the top third, get a positive 'Y' value.
    // Click in the left third, get a positive 'X' value.
    // Click in the middle, get zero.
    if (clickPointX < 16) {
        deltaX = +1;
    } else if (clickPointX > 34) {
        deltaX = -1;
    } else {
        deltaX = 0;
    }

    if (clickPointY < 16) {
        deltaY = +1;
    } else if (clickPointY > 34) {
        deltaY = -1;
    } else {
        deltaY = 0;
    }
    map.panDirection(deltaX, deltaY);
});


texts:
The challenge can be found here.
In short we have a recursive function, and we need to find when \$z_i\$ is equal to one.
$$
\begin{align}
    z_1 &= 1\\
    z_i &= z_{i-1} * a\ \%\ n\\
    \text{find}\ z_i &= 1
\end{align}
$$
Input range:
$$ 2 \le a \lt n \le 10^9 $$
I have written the following. It is simple, but too slow.
import math

def solution(a, n):
    if math.gcd(a, n) > 1:
        return 0
    z = 1
    i = 1
    while True:
        z = z * a % n
        if z == 1:
            return i
        i += 1
l = map(int, input().split(' '))
print(solution(*l))


texts: Building DataFrames from gz and json files

texts:
This is part of my code.

List all files and read them into the list files.
Now I have a dictionary my_dict. The values are the parquet files. all files must have same schema.
I have more than 2000 files is my folder, so files is large.
For each file I firstly gunzip all of them.
Next I find all the JSON files.
Problem is here. My file tick_calculated_2_2020-05-27T01-02-58.json will be read and converted to dateframe and appended to 'tick-2.parquet'.

My code works but the execution time is very low. How do I get rid of one or more loops?
def gunzip(file_path, output_path):
    with gzip.open(file_path, "rb") as f_in:
        with open(output_path, "wb") as f_out:
            shutil.copyfileobj(f_in, f_out)

if __name__ == '__main__':
    files = os.listdir('/Users/milenko/mario/Json_gzips')
    files = [fi for fi in files if fi.endswith(".gz")]

    my_dict = {'ticr_calculated_2': 'ticr-2.parquet', 'ticr_calculated_3': 'ticr-3.parquet', \
               'ticr_calculated_4': 'ticr-4.parquet', 'tick_calculated_2': 'tick-2.parquet', \
               'tick_calculated_3': 'tick-3.parquet', 'tick_calculated_4': 'tick-4.parquet'}
    basic = '/Users/milenko/mario/Json_gzips/'

    for file in files:
        gunzip(file, file.replace(".gz", ""))

        json_fi = glob.glob("*.json")

        for key, value in my_dict.items():
            filepath = basic + value
            for f in json_fi:
                if key in f:
                    result_df = pd.DataFrame()
                    with open(f, encoding='utf-8', mode='r') as i:
                        data = pd.read_json(i, lines=True)
                        result_df = result_df.append(data)
                        table_from_pandas = pa.Table.from_pandas(result_df)
                        pq.write_table(table_from_pandas, filepath)


texts: Wrapper to translate text in wxPython widgets

texts:
I am writing a wrapper for all widgets that contain text that needs to be translated for wxPython and make them handle the initial translation and the change of language on their own using gettext.

I already have a working prototype but I'm sure this is not the correct way to do it. Here is an example for all subclasses of wx.Control.

My Idea is to override the relevant methods of wx.Control and then merge the actual widgets (subclasses of wx.Control) together with my Control.

import wx
from wx.lib.pubsub import pub

class Control(wx.Control):
    def __init__(self, label):
        self.ml_label = label
        pub.subscribe(self.Update, 'language.changed')

    def Update(self):
        super().Update()
        super().SetLabel(_(self.ml_label))

    def SetLabel(self, label):
        self.ml_label = label
        super().SetLabel(_(self.ml_label))

class Button(wx.Button, Control):
    def __init__(self, parent, id=wx.ID_ANY, label=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
                 validator=wx.DefaultValidator, name=wx.ButtonNameStr):
        Control.__init__(self, label)
        wx.Button.__init__(self, parent, id, _(label), pos, size, style, validator, name)

class StaticText(wx.StaticText, Control):
    def __init__(self, parent, id=wx.ID_ANY, label=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
                 name=wx.StaticTextNameStr):
        Control.__init__(self, label)
        wx.StaticText.__init__(self, parent, id, _(label), pos, size, style, name)

Before I had the code from the Control class in Button and StaticText but as there are lots of widgets based on Control I wanted to move the duplicate code to one place.

It works, but I'm sure it's not the right way to do it especially as I don't call super().__init__ in the Control class, which can't be right.

Should I even be using multiple inheritance for what I am trying to do here?


texts: Join a JSON object of arrays and reduce down to one key

texts:
Given that I have a dataset as follows:

{ 1: ['Extremely Tall'], 2: ['Tall'], 3: ['Medium', 'Low'], 4: ['Dwarf'] }

and I receive a value (e.g. Tall or Medium) I want to determine the associated key. By the way feel free to change the dataset, i.e. it doesn't have to be a json object... so long as:

Medium -> 3
Low -> 3
Tall -> 2

My solution is below, anyone have a better way of doing it?

const R = require('ramda')
const heightsMap = { 1: ['Extremely Tall'], 2: ['Tall'], 3: ['Medium', 'Low'], 4: ['Dwarf'] }
const height = 'Medium'

const associatedNumber = R.keys(heightsMap).filter(key => heightsMap[key].includes(height))[0]

console.log(associatedNumber)


texts:
I am using an CloseableHttpAsyncClient the following way:

public class AsyncHttpClient {

    private static final Logger logger = LogManager.getLogger(Main.class);

    private static CloseableHttpAsyncClient HTTP_ASYNC_CLIENT = null;
    private static HttpPost HTTP_POST = null;
    private static HttpContext HTTP_CONTEXT;

    private static PropertiesLoader PROP_LOADER = new PropertiesLoader();
    private static Properties PROPERTIES = PROP_LOADER.initProp("./config/config.properties");
    private static final int CON_REQUEST_TIMEOUT = Integer.valueOf(PROPERTIES.getProperty("connectionrequesttimeout"));
    private static final int CON_TIMEOUT = Integer.valueOf(PROPERTIES.getProperty("connecttimeout"));
    private static final int CON_SOCKET_TIMEOUT = Integer.valueOf(PROPERTIES.getProperty("sockettimeout"));
    private static final String CON_URL = PROPERTIES.getProperty("conurl");
    private static final int CONMANAGER_MAX_TOTAL = Integer.valueOf(PROPERTIES.getProperty("conmanagermaxtotal"));
    private static final int DEFAULT_MAX_PER_ROUTE = Integer.valueOf(PROPERTIES.getProperty("conmanagermaxdefaultperroute"));

    //Reusable connection
    private static RequestConfig createConnConfig() {

        return RequestConfig.custom()
                .setConnectionRequestTimeout(CON_REQUEST_TIMEOUT)
                .setConnectTimeout(CON_TIMEOUT)
                .setSocketTimeout(CON_SOCKET_TIMEOUT).build();
    }

    private static PoolingNHttpClientConnectionManager createPoolingConnManager() throws IOReactorException {
        IOReactorConfig config = IOReactorConfig.DEFAULT;
        ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config);

        PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
        cm.setMaxTotal(CONMANAGER_MAX_TOTAL);
        cm.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);

        return cm;
    }

    private static synchronized CloseableHttpAsyncClient getCloseableClient() throws IOReactorException {

        if (HTTP_ASYNC_CLIENT == null) {
            logger.info("New Async Client created ");
            HTTP_ASYNC_CLIENT = HttpAsyncClientBuilder.create()
                    .setDefaultRequestConfig(createConnConfig())
                    .setConnectionManager(createPoolingConnManager()).build();

            HTTP_ASYNC_CLIENT.start();
        }
        return HTTP_ASYNC_CLIENT;
    }

    private static synchronized HttpPost getPost() {
        if (HTTP_POST == null) {
            logger.info("New Post created ");
            HTTP_POST = new HttpPost(CON_URL);
            HTTP_POST.setHeader("Accept", "application/json");
            HTTP_POST.setHeader("Content-type", "application/json");
        }
        return HTTP_POST;
    }

    public static void postData(String data) throws Exception {
        //TODO - needs cleanup
        StringEntity entity = new StringEntity(data);
        HttpPost httpPost = getPost();
        httpPost.setEntity(entity);
        getCloseableClient().execute(httpPost, HTTP_CONTEXT, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse httpResponse) {
                logger.info("Completed");

            }

            @Override
            public void failed(Exception e) {
                logger.info("Completed with exception " + e);
            }

            @Override
            public void cancelled() {
                logger.info("Cancelled ");
            }
        });
    }

}

Throughout the program I want only one instance to be alive, I am also using multiple threads to post data using the above class.


texts: Evaluating a dotted quad IP address has clumsy use of inject/fold

texts:
I wrote this to consume valid IPv4 addresses in dotted-quad decimal form:

def dotted_ip_to_num ip
  strings = ip.split('.').reverse
  strings.each_with_index.inject(0) do |sum, pair|
    str, i = pair
    sum + str.to_i * (2 ** (i * 8))
  end
end

But my chain of each_with_index and inject (aka left-fold or reduce) looks clumsy to me.

Firstly, Ruby won't let me match (aka desctructure) the pair yielded by each_with_index like this |sum, str, i| or this |sum, [str, i]|. Did I miss something? So, I do this on a line of its own (line 4.)

Secondly, although the message chain is only 2 messages, is it so complex in this case that I should split it up to do the summation as an extra line, like this?

octets = strings.each_with_index.collect do |str, i|
  str.to_i * (2 ** (i * 8))
end
octets.inject(0, :+)

Please set aside the improvement of multiplying the accumulator by 256 at each inject/reduce step, as that eliminates each_with_index entirely, and means I won't get the answer to my two main questions.

I also welcome reviews from users of non-Ruby collections libraries. (FYI collect is map in some other languages.)


texts:
The level 3 menu is broken in 2 parts if there are more than 10 items. The issue is with hovering over the newly created list.

At this moment I have 3 functions that apply the shown-sub class. I want to reduce it to only one. It should work when hovering over cotton and both ul lists.

 !function(){
 $("#nav ul.level0 ul.level1").each(function(){
  var menuLength = $(this).find("li.level2").length;
  if (menuLength > 10){
   var detachedElements = $(this).find("li.level2").slice(10);
   detachedElements.detach();
   $(this).parent().append("

");
   detachedElements.appendTo($(this).siblings(".second-menu"));
  }
  $(this).siblings("a").hover(
   function(){
    $(this).siblings(".second-menu").addClass("shown-sub");
   },
   function(){
    $(this).siblings(".second-menu").removeClass("shown-sub");
   }
  );
  $(this).children(".level2").hover(
   function(){
    $(this).parent().siblings(".second-menu").addClass("shown-sub");
   },
   function(){
    $(this).parent().siblings(".second-menu").removeClass("shown-sub");
   }
  );
  $(this).siblings(".second-menu").children(".level2").hover(
   function(){
    $(this).parent().addClass("shown-sub");
   },
   function(){
    $(this).parent().removeClass("shown-sub");
   }
  );
 })
 }();
.second-menu{
  color:red;
}
.shown-sub{
 color:blue;
}

        link text

            Cotton

has to be black

has to be black

has to be black

has to be black

has to be black

has to be black

has to be black

has to be black

has to be black

has to be black

has to be blue on hover

has to be blue on hover

has to be blue on hover

has to be blue on hover

has to be blue on hover

has to be blue on hover

has to be blue on hover

has to be blue on hover

has to be blue on hover

has to be blue on hover


texts: Find the intersect area of two overlapping rectangles

texts:
This is my solution to find the coordinates of 2 overlapped rectangles implemented in JavaScript. Each rectangle is represented by 2 points, each with 2 (x,y) coordinates.

Can this code be improved?

const maxOfX = (rec) => (Math.max(rec.x1, rec.x2));
const maxOfY = (rec) => (Math.max(rec.y1, rec.y2));
const minOfX = (rec) => (Math.min(rec.x1, rec.x2));
const minOfY = (rec) => (Math.min(rec.y1, rec.y2));
const comBinedRectangle = (rec1, rec2) => {
  let overlappedRec = {};
  const NolappingFromX = maxOfX(rec1) <= minOfX(rec2) || minOfX(rec1) >= maxOfX(rec2);
  const NolappingFromY = maxOfY(rec1) <= minOfY(rec2) || minOfY(rec1) >= maxOfY(rec2);
  if (!(NolappingFromX || NolappingFromY)) {
    overlappedRec.x1 = Math.max(minOfX(rec1), minOfX(rec2));
    overlappedRec.y1 = Math.max(minOfY(rec1), minOfY(rec2));
    overlappedRec.x2 = Math.min(maxOfX(rec1), maxOfX(rec2));
    overlappedRec.y2 = Math.min(maxOfY(rec1), maxOfY(rec2));
  }

  return overlappedRec;
}
const rectangle1 = { x1: 2, y1: 2, x2: 4, y2: 4 };
const rectangle2 = { x1: 3, y1: 3, x2: 6, y2: 2 };
console.log(comBinedRectangle(rectangle1, rectangle2));
// { x1: 3, y1: 2, x2: 4, y2: 3 }


texts: Script to temporarily drop admin privileges

texts:
Description

The aim of my project is to allow administrators to drop privileges for reasons of self-control. Currently, it works only on MacOS Sierra but the concept should be extensible to any Unix compatible system.

The sudoers mechanism is the workhorse. By adding a file in sudoers.d/ the administrator user (let's call him my-admin) is given permissions to run the script admin-helper as root.

The admin-helper script when run, toggles my-admin's membership from the admin group. When the my-admin is not in the admin group, the user is only added after the script sleeps for 20 min.

Files

admin-helper

#!/bin/bash

set -e -u
username=$SUDO_USER
delay=$((60*20)) #20 minutes
uGuid=$(dscl . -read /Users/$username/ GeneratedUID | sed -nE 's/GeneratedUID: (.*$)/\1/p')

if groups "$username" | grep -q -w admin; then
    dscl . -delete /Groups/admin GroupMembers "$uGuid"
    echo "Removed '$username' from admin. You may need to logout for changes to take effect."
else
    echo "'$username' is not an admin"
    echo "Sleeping for $delay seconds staring from $(date '+%D %T')"
    sleep "$delay"

    if [[ -z "${1+x}" ]]; then
       echo "Adding '$username' to admin group"
       dscl . -append /Groups/admin GroupMembers "$uGuid"
    else
       echo "Executing command as root"
       $1
    fi
fi

admin.sudoers

  User_Alias DELAYED_ADMINS = my-admin
  Cmnd_Alias ADMIN_HELPERS = /usr/local/bin/admin-helper

  DELAYED_ADMINS ALL=(root) ADMIN_HELPERS

Usage

This is the installation process:

  sudo mkdir -p /private/etc/sudoers.d/
  EDITOR="cp admin.sudoers" sudo visudo -f /private/etc/sudoers.d/admin
  sudo cp admin-helper /usr/local/bin/admin-helper

The subsequent usage is:

sudo admin-helper

or

sudo admin-helper "whoami"

Review

Some of the points I want a review for include:

The way to add/remove user from the admin group. Perhaps there is a better cross-platform way of doing this.
Potential security issues. Possibility of locking oneself out from the admin privilages.
Better/safer way to do implement installation or uninstallation.

EDIT:

The way I use this script is to have my privileges dropped most of the time, and only regain them (by running the script 20min before) when I need to do admin stuff.

Purpose/Example usage

The whole reason behind having the delay before gaining admin privileges is to prevent  my-admin from gaining them at whim. As a concrete example, suppose my-admin wishes to use MacOS parental control settings on himself.  He can do so by dropping admin privileges using admin-helper,  then setting parental controls for my-admin using another administrator account (and then forgo access to the other admin account). Now suppose my-admin wants to disable the parental-controls, he must regain privileges by running admin-helper script again, and only then he can disable parental-controls. For this he has to wait for 20min which is a good thing. Say parental-controls prevented him from viewing Facebook. This means that he can no longer open that Facebook tab on whim while he is still doing important work. He can always decide that, "I will run Facebook after 20min", but that decision too can be changed anytime within 20 minutes by interrupting the admin-helper script while it is sleeping.

An analogy would be that you have a box of candies that only opens 20min after you tell it to. Will you eat the same amount of candies that you would eat if you could open the box instantly?


texts:
It's a simple timed event template class. It's used in a 3D multiplayer game!
template <class T>
class CTimeEventDecorator : public CBaseDecorator, public CPooledObject<CTimeEventDecorator<T>>
{
public:
    typedef CTimeEvent<T> TTimeEventType;
    typedef std::vector<TTimeEventType> TTimeEventContainerType;

    CTimeEventDecorator(const TTimeEventContainerType& TimeEventContainer, T* pValue = 0)
        : it_start(TimeEventContainer.begin())
        , it_cur(TimeEventContainer.begin())
        , it_next(TimeEventContainer.begin())
        , it_end(TimeEventContainer.end())
        , pData(pValue)
    {
        if (it_start == it_end)
            *pValue = T();
        else
            ++it_next;
    }

    void SetData(T* pValue)
    {
        pData = pValue;
    }

protected:
    CTimeEventDecorator(CTimeEventDecorator<T>& ted, CParticleInstance* pFirstInstance, CParticleInstance* pInstance)
        : it_start(ted.it_start)
        , it_end(ted.it_end)
        , it_cur(ted.it_cur)
        , it_next(ted.it_next)
        , pData((T*)((unsigned char*)ted.pData - (DWORD)pFirstInstance + (DWORD)pInstance))
    {
        if (it_start == it_end)
            *pData = T();
    }

    virtual CBaseDecorator* __Clone(CParticleInstance* pFirstInstance, CParticleInstance* pInstance)
    {
        return new CTimeEventDecorator(*this, pFirstInstance, pInstance);
    }

    virtual void __Execute(const CDecoratorData& d)
    {
        if (it_start == it_end)
            Remove();
        else if (it_cur->m_fTime > d.fTime)
            *pData = it_cur->m_Value;
        else
        {
            while (it_next != it_end && it_next->m_fTime <= d.fTime)
                ++it_cur, ++it_next;

            if (it_next == it_end)
            {
                *pData = it_cur->m_Value;
                Remove();
            }
            else
            {
                float length = it_next->m_fTime - it_cur->m_fTime;

                *pData = it_cur->m_Value * (1 - (d.fTime - it_cur->m_fTime) / length) ;
                *pData += it_next->m_Value * ((d.fTime - it_cur->m_fTime) / length);
            }
        }
    }

    typename TTimeEventContainerType::const_iterator it_start;
    typename TTimeEventContainerType::const_iterator it_end;
    typename TTimeEventContainerType::const_iterator it_cur;
    typename TTimeEventContainerType::const_iterator it_next;

    T* pData;
};

What optimizations, refactor I can do?


texts:
I was recently asked an interview question with regards to algorithm design. The challenge is as follows:

Given a 6 or less digits positive integer (0 - 999999 inclusive), write a function englishify(number: int) that returns the full English equivalent of that number. Here are some samples of the structure you are expected to generate:
1 - One
222 - Two Hundred And Twenty two
1234 - One Thousand, Two Hundred and Thirty Four
31337 - Thirty One Thousand, Three Hundred And Thirty Seven
100100 - One Hundred Thousand And One Hundred
200111 - Two Hundred Thousand, One Hundred And Eleven

As you may be able to see, there is a key requirement when it comes to formatting this:

There should be a comma, not 'And', after the thousands and before the hundreds, if both exist.

I have attempted this challenge with the code below:
def englishify(number):
    #Numbers 0-19 (unique numbers)
    OneToNine= 'One Two Three Four Five Six Seven Eight Nine'.split()
    TenToNineteen = 'Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
    ZeroToNineteen = [''] + OneToNine + TenToNineteen

    #Numbers >= 20 at intervals of 10
    Tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()

    #Additional function for ease of processing of numbers
    def englishifyHundreds(number):
    #Special case: Number = 0
        if number == 0:
            return 'Zero'

        #1. Number from 1-19
        if number < 20:
            return ZeroToNineteen[number]

        #2. Number from 20-99
        if number >= 20 and number < 100:
            result = Tens[int(number/10)-2] + ' ' + ZeroToNineteen[int(number%10)]
            return result.rstrip()

        #3. Number from 100-999
        if number >= 100:
            #Separating hundreds digit and tens digit
            tens = number - ((number//100)*100)

            #Accounting for edges = 0 (number = 100, 200, ...)
            if number%100 == 0:
                return ZeroToNineteen[int(number/100)] + ' Hundred'

            else:
                return ZeroToNineteen[int(number/100)] + ' Hundred And ' + englishifyHundreds(tens)

    #Actual processing of number
    if len(str(number)) <= 3:
        return englishifyHundreds(number)

    else:
        #Splitting number into 'thousands' digits and 'hundreds' digits
        thousands = int(str(number)[:-3])
        hundreds = int(str(number)[-3:])

        #Accounting for edges = 0 (thousands = 1000, 2000, ...)
        if thousands % 1000 == 0:
            return englishifyHundreds(thousands) + ' Thousand'

        else:
            #Accounting for if hundreds == 0:
            if hundreds == 0:
                return englishifyHundreds(thousands) + ' Thousand'

            #Accounting for cases where comma is not necessary
            elif hundreds % 100 == 0 or hundreds < 100:
                return englishifyHundreds(thousands) + ' Thousand And ' + englishifyHundreds(hundreds)

            #Remaining cases implementing comma
            else:
                return englishifyHundreds(thousands) + ' Thousand, ' + englishifyHundreds(hundreds)

I am currently trying to rack my brains thinking of ways to optimize this, but with my limited knowledge of recursions and algorithms this is the best I can churn out for now. Hopefully I can seek some opinions from some of the more experienced programmers around here.


texts:
I have implemented a stack calculator based on this programming task. I wondered if a more experienced racketeer could give me feedback and tell me if I am missing anything in Racket that would enable the solution to be more elegant.

#lang racket

(define (inc n)
  (+ n 1))

(define (print-value s)
  (begin
    (display s)
    (display " ")))

(define (exec l (stack empty) (opcount 1))
  "executes a stack based program."
  (cond
    [(empty? l) (void)]

    ;; push number onto stack
    [(number? (string->number (first l)))
     (exec (rest l)
           (cons (string->number (first l)) stack)
                 (inc opcount))]

    ;; pop number from stack
    [(equal? (first l) ".")
     (begin
       (print-value (first stack))
       (exec (rest l) (rest stack)
       (inc opcount)))]

    ;; mathmatical operators
    [(equal? (first l) "+")
     (exec (rest l) (cons
                     (+ (first stack) (second stack))
                     (rest (rest stack))) (inc opcount))]
    [(equal? (first l) "-")
     (exec (rest l) (cons
                     (- (first stack) (second stack))
                     (rest (rest stack))) (inc opcount))]
    [(equal? (first l) "*")
     (exec (rest l) (cons
                     (* (first stack) (second stack))
                     (rest (rest stack))) (inc opcount))]
    [(equal? (first l) "/")
     (exec (rest l) (cons
                     (/ (first stack) (second stack))
                     (rest (rest stack))) (inc opcount))]

    ;; duplication operator
    [(equal? (string-downcase (first l)) "dup")
     (exec (rest l)
           (cons (first stack) stack) (inc opcount))]
    [else
     (~a "Error: operation " opcount " invalid")]))

(define program (string-split "64 DUP * ."))

(exec program)


texts:
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem

Given two words (begin and end), and a dictionary's word list,
find all shortest transformation sequence(s) from begin to end,
such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that begin
is not a transformed word. Note:

Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume begin and end are non-empty and are not the same.

Inputs
"hit"
"cog"
["hot","dot","dog","lot","log","cog"]
"hit"
"cog"
["hot","dot","dog","lot","log"]

Outputs
[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
[]

Code
#include <vector>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>

struct Solution {
    const inline std::vector<std::vector<std::string>> findLadders(
                const std::string begin,
                const std::string end,
                const std::vector<std::string> &words
    ) {
        std::unordered_set<std::string> dict_words(words.begin(), words.end());

        if (dict_words.find(end) == dict_words.end()) {
            return {};
        }

        graph graph;
        std::vector<std::vector<std::string>> paths;
        std::vector<std::string> path = {begin};

        if (make_graph(graph, begin, end, dict_words)) {
            find_paths(graph, begin, end, path, paths);
        }

        return paths;
    }

private:

    typedef unordered_map<std::string, std::vector<std::string>> graph;

    const inline bool make_graph(
        graph &graph,
        const std::string begin,
        const std::string end,
        std::unordered_set<std::string> &dict_words
    ) {
        std::unordered_set<std::string> candidate_words;
        candidate_words.insert(begin);

        while (!candidate_words.empty()) {
            if (candidate_words.find(end) != candidate_words.end()) {
                return true;
            }

            for (std::string word : candidate_words) {
                dict_words.erase(word);
            }

            std::unordered_set<std::string> curr_word;

            for (std::string word : candidate_words) {
                std::string parent = word;

                for (int chari = 0; chari < word.size(); chari++) {
                    char character = word[chari];

                    for (int letter = 0; letter < 26; letter++) {
                        word[chari] = 'a' + letter;

                        if (dict_words.find(word) != dict_words.end()) {
                            curr_word.insert(word);
                            graph[parent].push_back(word);
                        }
                    }

                    word[chari] = character;
                }
            }

            std::swap(candidate_words, curr_word);
        }

        return false;
    }

    static const inline void find_paths(
        graph &graph,
        const std::string begin,
        const std::string end,
        std::vector<std::string> &path,
        std::vector<std::vector<std::string>> &paths
    ) {
        if (begin == end) {
            paths.push_back(path);

        } else {
            for (std::string child : graph[begin]) {
                path.push_back(child);
                find_paths(graph, child, end, path, paths);
                path.pop_back();
            }
        }
    }
};

References

Problem

Discuss

Solution


texts:
Mind that this is my first actual program in C++ and I tried to prepare for any possible input.  Also the reason I included static_cast<void>(generator(range)) is to throw away the first random value because I read on LearnCpp.com that throwing away the first is a common practice to produce more random results.  Anyways here is the code, all suggestions are welcome.
#include <iostream>
#include <limits>
#include <random>

bool validateInput(int input)
{
    using namespace std;

    if (1 <= input && input <= 100)
        return true;
    else if (!input)
        return false;
    else
        return false;
}

int generateRandomNumber()
{
    std::random_device dev;
    std::mt19937_64 range(dev());
    std::uniform_int_distribution<std::mt19937_64::result_type> generator(1, 100);
    static_cast<void>(generator(range));
    return static_cast<int>(generator(range));
}

bool placement(int input, int target)
{
    using namespace std;
    if (input > target)
    {
        cout << "Guess is too high.";
        return false;
    }

    else if (input < target)
    {
        cout << "Guess is too low.";
        return false;
    }
    else
    {
        cout << "Guess is correct!";
        return true;
    }
}

int main()
{
    using namespace std;
    cout << "You have 7 guesses to guess what number I am thinking of between 1 and 100.\n";
    int winning_num{ generateRandomNumber() };
    static int tries{ 1 };
    do
    {
        int num;
        cout << "\nGuess#" << tries << ": Enter a number -> ";
        cin >> num;
        if (!cin)
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            continue;
        }

        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        if (validateInput(num))
            ;
        else
        {
            continue;
        }
        if (!placement(num, winning_num))
        {
            cout << "\nIncorrect!\n";
            ++tries;
        }
        else
        {
            cout << "\nCorrect!\n";
            exit(0);
        }

    }
    while (tries <= 7);
    cout << "\nYou did not guess the number in the alloted amount of guesses :(\nTry Again!\n";

}


texts:
I'm learning about using inheritance and super in Ruby. This is a continuation of one of the exercises that is in a book I am reading.

I set up my Vehicle class to be the superclass. From there, MyCar and MyTruck inherit the Vehicle class's methods, by using the super method.

Both subclasses also have a MAX_SPEED constant, which is different for each. Each subclass also has its own .speed_up method, which outputs different strings depending on how fast the vehicle is going.

Is my code formatted correctly? It works, but I wonder how I can improve it, and if I am also using best practices in this case.

Should the year, color, model, and gasoline arguments be in the MyCar and MyTruck subclasses? Or should they remain in the Vehicle class?

The code below is also in my GitHub repository.

require 'date'

class Vehicle
  attr_accessor :speed, :on, :color
  attr_reader :year, :model, :gallons
  def initialize(year, color, model, gallons)
    @year = year
    @model = model
    @gallons = gallons
    @color = color
    @speed = 0
    @on = false
  end

  @@miles_per_gallon = 0

  def self.mileage(tank, miles)
    @@miles_per_gallon = miles / tank
  end

  def brake
    if self.speed == 0
      puts "You aren't moving! Yet you keep pushing the brake..."
    elsif self.speed >= 10
      self.speed -= 10
      puts "You slow down to #{self.speed} kilometers an hour."
    end
  end

  def shut_off
    if self.on == false
      puts "Your car is already off."
    else
      self.on = false
      puts "You turn off your car. The engine falls silent."
    end
  end

  def turn_on
    if self.on == false
      self.on = true
      puts "The car's engine rumbles and sparks to life."
    else
      puts "Your car is already running!"
    end
  end

  def drive(distance)
    puts "You drive #{distance} miles."
    Vehicle.mileage(self.gallons, distance.to_i)
    puts "When you stop in the gas station, you find that your car gets #{@@miles_per_gallon} miles per gallon."
  end

  def look_at
    if Time.new.hour >= 17 && Time.new.hour < 19
      puts "The red light of the setting sun sparkles off the paint of your #{model}."
      puts "You feel nostalgic."
    elsif Time.new.hour >= 19 && Time.new.hour < 6
      puts "Your #{model} carves a dark outline in the moon's pale light."
      puts "You feel dangerous. Perhaps you should go find a street race?"
    else
      puts "You gaze at the body of your #{self.year} #{self.model}. Its #{color} paint sparkles in the sunlight."
      puts "You feel happy."
    end
  end

  def repaint(color)
    self.color = color
    puts "You changed your car's color to #{self.color}!"
    puts "Mmm, sexy."
  end

end

class MyCar < Vehicle

  def initialize(year, color, model, gallons)
    super(year, color, model, gallons)
  end

  MAX_SPEED = 180

  def speed_up
    if self.speed != MAX_SPEED
      self.speed += 10
      puts "You speed up to #{self.speed} kph."
      if self.speed == 120
        puts "The engine purrs, the wind flows past the open window next to your seat."
        puts "You reach serenity..."
      end
    else
      puts "The engine roars, putting forth maximum effort."
      puts "The speedometer is pinned to the max!"
    end
  end

end

class MyTruck < Vehicle

  def initialize(year, color, model, gallons)
    super(year, color, model, gallons)
  end

  MAX_SPEED = 140

  def speed_up
    if self.speed != MAX_SPEED
      self.speed += 10
      puts "You speed up to #{self.speed} kph."
      if self.speed == 120
        puts "The engine rumbles, the wind flows past the open window next to your seat."
        puts "You feel calm. If you had a dog, he'd probably be sticking his head out of the window."
      end
    else
      puts "The engine roars, putting forth maximum effort."
      puts "Your fuel gauge needle slowly trickles downward..."
    end
  end

end


texts: Script for removing empty rows in a sheet

texts:
I often receive Excel worksheets (with empty rows) which I have to process as a pivot table. Because pivot tables don't allow empty rows, I've made this script. Any feedback is welcomed.

' Removes empty rows from an sheet.

Public Sub RemoveEmptyLines()
  Dim lastRow As Long
  Dim currentRow As Long
  Dim emptyLine As Boolean
  Dim answer As Integer
  Dim countDeleted As Integer

  Application.ScreenUpdating = False

  answer = MsgBox("Empty lines will be deleted." & vbLf & _
             "Do you wish to continue?", _
              vbYesNo, "Changing table-structure?")

  If answer = vbYes Then
    ' Minus 1 => The last one we check will be the last
    ' but one row.
    lastRow = Range("A1").SpecialCells(xlCellTypeLastCell).row - 1
    currentRow = 1
    countDeleted = 0
    ' Go until the last but two row! The last row can't
    ' be empty (Result of SpecialCells). So we don't have
    ' to check that.
    While currentRow < lastRow

      emptyLine = True

      Do
        ' When the complete row is empty then delete it.
        ' Table structure might be changed while iterating
        ' through the inner loop. So repeat the check from
        ' the main loop.
        If _
           WorksheetFunction.CountA(Rows(currentRow + 1).EntireRow) = 0 _
        And _
           currentRow < lastRow _
        Then

          Rows(currentRow + 1).EntireRow.Delete
          countDeleted = countDeleted + 1
          lastRow = lastRow - 1

        Else
          ' I case of "not empty" leave the inner loop and
          ' check the next line.
          emptyLine = False

        End If

      Loop Until emptyLine = False

      currentRow = currentRow + 1
    Wend

    MsgBox countDeleted & " rows have been deleted.", _
           vbInformation, "Result"

  End If

  Application.ScreenUpdating = True

End Sub


texts: Computing and Populating Excel Table With VBA

texts:
I am trying to populate a table like this in Excel. I came up with a bunch
of loops to do this. I feel like this is a brute-force approach and may not work well when populating bigger tables.

Any other ways to populate values in Excel?

Sub Fill_SLA_priority()

    Dim SLAbyPrior      As Worksheet
    Dim wsAssignedTix   As Worksheet

    Dim ctP1            As Integer
    Dim ctP1RespSLA     As Integer
    Dim ctP1PlanSLA     As Integer
    Dim ctP1ResSLA     As Integer
    Dim ctP1All3SLA    As Integer

    Dim d              As Range

    Set SLAbyPrior = Worksheets("SLA by Priority")
    Set wsAssignedTix = Worksheets("AssignedTickets")

    For Each d In wsAssignedTix.Range(wsAssignedTix.Range("H1").End(xlDown), wsAssignedTix.Range("H" & Rows.count).End(xlUp))

            '' Loop through entire list to count number of P1 - P4, Request.
            '' P1
            '' Count number of Responded, Planned, Resolved, Overall SLA

            If d.Value = "Priority 1 Incident - Critical" _
                And (d.Offset(0, -1) = "Closed" Or d.Offset(0, -1) = "Resolved") Then

                    ctP1 = ctP1 + 1

                    If d.Offset(0, 2) = 1 Then ctP1RespSLA = ctP1RespSLA + 1
                    If d.Offset(0, 4) = 1 Then ctP1PlanSLA = ctP1PlanSLA + 1
                    If d.Offset(0, 6) = 1 Then ctP1ResSLA = ctP1ResSLA + 1
                    If d.Offset(0, 2) = 1 And d.Offset(0, 4) = 1 And d.Offset(0, 6) = 1 Then
                            ctP1All3SLA = ctP1All3SLA + 1
                    End If

            End If
    Next d

    '' Populating the cells in SLA_by_Priority
    With SLAbyPrior

            '' P1 - Resp SLA %
            .Range("B5") = ctP1RespSLA / ctP1

            '' P1 - Plan SLA %
            .Range("C5") = ctP1PlanSLA / ctP1

            '' P1 - Resl SLA %
            .Range("D5") = ctP1ResSLA / ctP1

            '' P1 - All 3 SLA %
            .Range("E5") = ctP1All3SLA / ctP1

    End With

End Sub


texts: Complex multiplication and integration with CUDA

texts:
I want to perform multiplication on two vectors and integrate it in a vector called acc_y. The acc_y variable will update over every iteration and averaged out.
I have modified vector addition code for it.

kernel for the multiply and integration:

__global__ void cvctmac (int M,float *yre,float *yim,float *x1re,float *x1im,float *x2re,float *x2im,double *acc_yre,double *acc_yim) {
    int index  = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;

    // Multiplication
    for (int i = index; i < M; i += stride) {
        acc_yre[i] += x1re[i] * x2re[i] - x1im[i] * x2im[i];
        acc_yim[i] += x1re[i] * x2im[i] + x1im[i] * x2re[i];
    }
}
__global__ void cavg(int M,double iter,double *xre,double *xim){
    // Averaging
    int index  = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;
    // Grid-stride approch
    for (int i = index; i < M; i += stride) {
        xre[i] /= iter;
        xim[i] /= iter;
    }
}

As the code is performing complex arithmetic, I am doing 4 operations per thread(2 for multiplication and 2 for integration). what will be the way to optimize the kernel cvctmac?

Will shared memory help here?

I have used cuComplex.h also but getting the same performance.

host code:

for (j = 0; j < iter; j++) {

    // Generate data in host
    for (i = j * M, c = 0; i < M * (j + 1); i++, c++) {
        x1re[c] = (float)i;
        x1im[c] = 0.0;
        x2re[c] = 1.0;
        x2im[c] = 0.0;
    }

    // Copy host to device
    cudaMemcpy(dx1re, x1re, M * sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(dx1im, x1im, M * sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(dx2re, x2re, M * sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(dx2im, x2im, M * sizeof(float), cudaMemcpyHostToDevice);

    //mac
    cvctmac<<<numBlock, numThread>>>(
        M,
        dyre, dyim,
        dx1re, dx1im,
        dx2re, dx2im,
        dacc_yre, dacc_yim
    );
}
// Avg
cavg<<<numBlock, numThread>>>(
    M, (double) iter,
    dacc_yre, dacc_yim
);

Please suggest the way to optimize the code.  I'm targeting CUDA with compute capability 6.1.


texts: jQuery looping on fields after validation

texts:
I have the following code:

$(":input, textarea, select").on('blur', function(ev) {

var data = $('#campaign-form').serialize();

$.ajax({
    url: "/campaign/validate",
    type: "POST",
    data: data,
    cache: false,
    dataType: 'json',
    success: function (data) {
        if (data) {

            /*Assign error classes*/
            $.each(data, function (field, message) {
                jQuery("#" + field).addClass('input-error');
                jQuery("#" + field + "-error").text(message);
            })
        }
    }
});

This code adds a class 'input-error' to fields which have an error (validated on the PHP side).

The issue is that if I fix the error, and send validation again, the input-error class is not removed. Also I need to add class input-valid to the correct fields.

I have tried a solution, but it does not look optimal (it does make the work though).

$(":input, textarea, select").on('blur', function(ev) {

var data = $('#campaign-form').serialize();

$.ajax({
    url: "/campaign/validate",
    type: "POST",
    data: data,
    cache: false,
    dataType: 'json',
    success: function (data) {
        if(data) {

            /*Remove classes for all fields in the form*/
            clearFields = $("#campaign-form :input.gg-field, #campaign-form textarea.gg-textarea, #campaign-form select.gfp-field").each(function(index) {
                var input = $(this);
                var fieldId = input.attr('id');
                jQuery("#"+fieldId).removeClass('input-valid');
                jQuery("#"+fieldId).removeClass('input-error');
                jQuery("#"+fieldId+"-error").text("");

            });

            /*Assign error classes*/
            $.each(data, function(field, message) {
                jQuery("#"+field).addClass('input-error');
                jQuery("#"+field+"-error").text(message);
            })

            /*To the other fields assign valid classes*/
            validFields = $("#campaign-form :input.gg-field, #campaign-form textarea.gg-textarea, #campaign-form select.gfp-field").not( ".input-error" ).each(
                function(index) {
                    var input = $(this);
                    var fieldId = input.attr('id');
                    jQuery("#"+fieldId).addClass('input-valid');
                    jQuery("#"+fieldId+"-error").text("");
                });

        }
    }
});

I would like to verify which fields are coming on the data JSON object in order to assign the error or valid class in that process, avoiding the need to loop through the fields again.

Data object example:

{ "title":"* The Campaign Title field is required.",
  "description":"* The Description field is required.",
  "campaign_category_id":"* The Campaign Category field is required."
}


texts: Check string having unique character or not without additional data structure

texts:
Here is my code without using additional data structures. Assuming all the characters are alphabetical and character checks are case-insensitive.

public static boolean isRepeated(String s) {
    if (s == null) {
        return true;
    }
    int length = s.length();
    for (int i = 0; i < length; i++) {
        if (!checkChar(i, s.toUpperCase())) {// making all character to upper case.
            return false;
        }
    }

    return true;

}

private static boolean checkChar(int i, String s) {
    char charAtI = s.charAt(i);
    //check all the character before that index;
    for (int k = 0; k < i; k++) {
        if (s.charAt(k) == charAtI)
            return false;
    }
    //check all the character after that index;
    for (int l = i + 1; l < s.length(); l++) {
        if (s.charAt(l) == charAtI)
            return false;
    }
    return true;
}

But it takes \$O(n^2)\$. Is there better way to do it, or some improvement?

To save complexity, I am using the other way, i.e. using an array.

public static boolean isRepeatedUsingArray(String s) {
        int[] charArray = new int[26];
        for(char c:s.toUpperCase().toCharArray()) {
            if(charArray[(int)c - 65] == 1) {
                return false;
            }
            charArray[(int)c - 65] = 1;
        }
        return true;

    }

Let me know your comments on this one as well.


texts:
While trying to learn Python I stumbled upon a question which asks you to write a code that is able to take an input and verify it to see whether it meets the IPv6 Criteria.

I wrote the following code:

valid_characters = ['A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f', ':', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
address = input('Please enter an IP address: ')
is_valid = []

for i in range(len(address)):
    current = address[i]
    for j in range(len(valid_characters)):
        check = valid_characters[j]
        if check == current:
            a = 1
            is_valid.append(a)

address_list = address.split(":")
invalid_segment = False

for i in range(len(address_list)):
    current = address_list[i]
    if len(current) > 4:
        invalid_segment = True

if len(address) == len(is_valid) and len(address_list) == 8 and invalid_segment == False:
    print("It is a valid IPv6 address.")

elif invalid_segment:
    print("It is not a valid IPv6 address.")

else:
    print("It is not a valid IPv6 address.")

Although the code works and for the sample cases that were provided it is successfully able to confirm whether the entered IP address is IPv6 or not, I feel like my solution is not really elegant enough and that there should be a better way to do this.

I would really appreciate it if someone could point me to the right direction for how I should condense or improve my code.

Please note that I am new to Python, with little to no experience.


texts:
I've written this function that concats strings:

public void find(ArrayList<String> operations, ArrayList<String> set) {
  String toMerge = operations.get(1);
  String fromMerge = operations.get(2);
  outer: for (int i = 0; i < set.size(); i++) {
     String[] toSet = set.get(i).split(" ");
     for (int k = 0; k < toSet.length; k++) {
    if (toMerge.equals(toSet[k])) {
        for (int j = 0; j < set.size(); j++) {
        String[] fromSet = set.get(j).split(" ");
        for (int x = 0; x < fromSet.length; x++) {
            if (fromMerge.equals(fromSet[x])) {
            for (int c = 0; c < toSet.length; c++) {
                set.set(j, set.get(j)+ ' ' +  toMerge.concat(' ' +toSet[c]));
                set.set(i, " ");
                }
                break outer;
            }
          }
        }
      }
    }
  }
}

This function takes as parameter an arrayList of operations, and an arrayList of set:

For the arrayList of operations, I always get a specific position, so I don't iterate.  It is always \$O(1)\$.
for the arrayList of set, I have to iterate, or rather, as I think of that to proceed:

For example, if I have as operation move foo bar, I have to do these steps:

First of all, I have to find where foo is:

Inside set, I can have this situation:

position x : {bar tree hotel}
...
position y : {foo lemon coffee}

When I find the string foo, I have to find the position of bar (I made an iteration as to find foo) and then i have to  concat the foo string into bar string  in this way:

position x : {bar tree hotel foo lemon coffee}
...
position y : {}

My program works as well as my function, but it is a nasty and inefficient solution.  How can I improve the efficiency of this function?


texts: Passing variables by values without the dreaded if/switch/eval

texts:
I have to pass a bunch of inputs and outputs between two Angular controllers and I've come up with a way to do it using $broadcast.  I'm using an "if" statement to make sure the inputs match the outputs, but there must be an easier way.

app.controller('Ctrl2', ['$scope', '$rootScope', function($scope, $rootScope) {
  var myArray = [$scope.input1, $scope.input2];
  $scope.textChange = function(whichChange) {
    if (whichChange == 1) {
      $rootScope.$broadcast('textChanged', $scope.input1, 1);
    } else if (whichChange == 2) {
      $rootScope.$broadcast('textChanged', $scope.input2, 2);
    } //else if, else if, else if, etc...
  };
}]);

But seems there should be a way I can replace that if statement with a single line, something like:

$rootScope.$broadcast('textChanged', $scope.relevantInput, relevantOutput);

Working Plunkr here

Same question applies to the case statement in controller Ctrl1, but I figure answering the question for one controller would answer it for the other.

Also: while comments on whether this is the best way to do this in Angular are certainly welcome my question is more about avoiding if/switch/eval.


texts: Making my Rock, Paper, Scissors game shorter

texts:
I am looking for advice on making the following code shorter.  Any help is appreciated.

public String determineWinner(String winner) {
    winner = "";
    if (playChoice.equals(compChoice))
        winner = "The result is a tie.";
    else if (compChoice.equals("R"))
    if (playChoice.equals("S") || playChoice.equals("s"))
        winner = "Computer wins because Rock beats Scissors.";
    else
        winner = "Player wins because Paper beats Rock";
    else if (compChoice.equals("S"))
    if (playChoice.equals("P") || playChoice.equals("p"))
        winner = "Computer wins because Scissors beats Paper.";
    else
        winner = "Player wins because Rock beats Scissors";
    else
    if (playChoice.equals("R") || playChoice.equals("r"))
        winner = "Computer wins because Paper beats Rock.";
    else
        winner = "Player wins because Scissors beats Paper.";
    return winner;
}


texts: Wordcloud from all answers of a user here on CR

texts:
Since I haven't really used Python's new async features yet, I took some older code of mine, which took all of my answers here on Code Review and generated a word cloud from them, and updated it to fetch the pages in an asynchronous way.

This script uses the py-stackexchange package for the API (don't forget to get your API key in order to increase the number of requests you can make to 10k). There are other packages for the API out there, but this one is easy to use IMO, especially for getting all questions/answers of one particular user. However, unfortunately (or luckily for me) it does not support getting the body of an answer (only of a question). So that part is done with aiohttp and BeautifulSoup, which is where the asynchronous part comes in. The text is split into words using nltk and the word cloud is generated via wordcloud.

To install everything:

$ pip install aiohttp bs4 lxml matplotlib nltk py-stackexchange wordcloud
$ python
>>> import nltk
>>> nltk.download('punkt')

Any and all feedback, especially on the use of the async stuff, is welcome. Maybe I should've split up fetching the page and processing it more? Maybe I missed some important performance trick?

import aiohttp
import asyncio
from bs4 import BeautifulSoup, SoupStrainer
from itertools import chain
import matplotlib.pyplot as plt
from nltk.tokenize import word_tokenize

import stackexchange
from wordcloud import WordCloud

API_KEY = '**redacted**'    # https://meta.stackexchange.com/q/261829/342577
CR = stackexchange.Site("CodeReview", API_KEY)

STRAINER = SoupStrainer(
    'div', attrs={'class': ['answer', 'answer accepted-answer']})

async def fetch(session, url, answer_id):
    async with session.get(url) as response:
        page = await response.text()
    soup = BeautifulSoup(page, "lxml", parse_only=STRAINER)
    try:
        answer_text = soup.select_one(
            f'div#answer-{answer_id} div.post-text').text
    except AttributeError:
        print("Failure:", url)
        return []
    else:
        print("Success:", url)
        return word_tokenize(answer_text)

async def fetch_all(urls, answer_ids):
    async with aiohttp.ClientSession() as session:
        jobs = [fetch(session, url, answer_id)
                for url, answer_id in zip(urls, answer_ids)]
        results = await asyncio.gather(*jobs)
    return results

if __name__ == "__main__":
    user = CR.user(98493)   # that's me
    user.answers.fetch()  # needed to initialize it...

    urls = (answer.url.replace(CR.domain, "codereview.stackexchange.com")
            for answer in user.answers)
    answer_ids = (answer.id for answer in user.answers)

    loop = asyncio.get_event_loop()
    words = list(chain.from_iterable(
        loop.run_until_complete(fetch_all(urls, answer_ids))))

    plt.figure()
    wordcloud = WordCloud(width=480, height=480, colormap="Blues")
    wordcloud = wordcloud.generate(" ".join(words))
    plt.imshow(wordcloud, interpolation="bilinear")
    plt.axis("off")
    plt.margins(x=0, y=0)
    plt.show()

The image produced by this code looks something like this.
Seems like I define, and talk about, a lot of functions...


texts: FizzBuzz without hard-coded logic checks

texts:
I'm a self-taught (on the job) programmer, always looking for ways to expand my skills. Seeing all the FizzBuzz examples with hard-coded logic checks made my head hurt, so I thought I'd try my hand at it. Leaning heavily on KISS, I'm ignoring exception handling and such, and all that's required to add new fizzbuzzers is a call to Catalog.Add(Divisor,Output).

I'd appreciate your feedback, whether on style or substance. This is part of my journey to adopting SOLID principles for better OO development, but I felt that not much could be applied here without over-complicating it.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var catalog = new Catalog();
        catalog.Add(Divisor: 3, Output: "Fizz");
        catalog.Add(Divisor: 5, Output: "Buzz");
        catalog.Add(Divisor: 10, Output: "Pozz");

        var counter = new Counter(Min: 1, Max: 100, Catalog: catalog);
        counter.Output();
        Console.ReadLine();
    }
}

internal class Counter
{
    private int min;
    private int max;
    private Catalog catalog;

    internal Counter(int Min, int Max, Catalog Catalog)
    {
        this.min = Min;
        this.max = Max;
        this.catalog = Catalog;
    }
    internal void Output()
    {
        for(int i = min; i <= max; i++)
        {
            Console.WriteLine(catalog.ToString(i));
        }
    }
}

internal class Catalog
{
    private List<Spec> specs;
    internal class Spec
    {
        internal int divisor;
        internal string output;
    }
    internal Catalog()
    {
        this.specs = new List<Spec>();
    }
    internal void Add(int Divisor, string Output)
    {
        this.specs.Add(new Spec() { divisor = Divisor, output = Output });
    }
    internal string ToString(int Number)
    {
        string outputstring = "";
        foreach (var x in specs)
        {
            outputstring += Number % x.divisor == 0 ? x.output : "";
        }
        return String.IsNullOrWhiteSpace(outputstring) ? Number.ToString() : outputstring;
    }
}

.NetFiddle


texts: Reimplementation of Laravel's config system

texts:
I am trying to create a config class identical to Laravel's but wanted to do it myself, to test my knowledge on the PHP language, can anyone help me improve it?

Each config file is located in the /app path and can be named whatever you want .php.

You can then get your config values by doing
Config::get('file.array_key')

So lets say I had a file called app.php and an array with a config key I wanted to get called 'author' or something I could simply do Config::get('app.author') I could even dive deeper and go for a key of a key by doing Config::get('app.author.email')

If I wanted to go even deeper, what would be a better way other than just doing an if statement for each index? checking the length etc?

Here is my code:

<?php

namespace PhpTestApp\App\Library\Config;

class Config
{
    static private $configFiles = [];

    public static function loadConfig() {
        $files = scandir(AP . '/app/config/');

        foreach(glob(AP . '/app/config/*.php') as $file) {
            self::$configFiles[explode('.', basename($file))[0]] = include(AP . '/app/config/' . basename($file));
        }
    }

    public function get($getString) {
        $parts = explode('.', $getString);
        $countDot = count($parts);

        if ($countDot == 2) {
            return array_key_exists($parts[0], self::$configFiles) ?
            (array_key_exists($parts[1], self::$configFiles[$parts[0]]) ?
            self::$configFiles[$parts[0]][$parts[1]] : '...')
            : '';
        }
        else if ($countDot == 1) {
            return ''; // just a file?
        }
        else {
            return '';
        }
    }
}


texts: What's better: return null or handle the Exception?

texts:
I'm in doubts what approach to take here, please have a look on the code below:

private void processBarCodeResponse(String decodedQrCode) {
        JSONObject jsonObject = JsonUtil.composeJsonObject(decodedQrCode);
        SalePoint salePoint = parseSalePoint(jsonObject);
        if (salePoint == null) return; // handle null value here
        saveSalePoint(salePoint);
    }

private SalePoint parseSalePoint(JSONObject jsonObject) {
        SalePoint salePoint = new SalePoint();
        try {
            salePoint.type = jsonObject.getString("type");
            salePoint.url = jsonObject.getString("url");
            salePoint.salePointId = jsonObject.getString("salePointId");
        } catch (JSONException e) {
            Logger.logError(TAG, "jsonObject " + jsonObject.toString() + " wasn't parsed " +
                    "correctly");
            return null; // point of concern
        }

        return salePoint;
    }

For the sake of readability I moved the try/catch block to the parseSalePoint() method, but then if parsing fails I'm enforced to return null from the method and check for null value in processBarCodeResponse() method. Wouldn't it be right to just handle the JSONException in processBarCodeResponse() method and stop its execution once it is thrown?


texts:
I made this class to eventually create a tic tac toe game. I used numpy which is a first for me. Here it is:

import numpy as np

class Grid():

    def __init__(self, data, row_length, coloumn_length):
        """Represents a Grid of data as a matrix.

        Args:
            data(list): data to be placed in grid matrix
            row_length(int): number of elements per row
            coloumn_length(int): number of elements per column
        """
        data_len = row_length*coloumn_length
        if len(data) < data_len:
            difference = data_len - len(data)
            data += [0]*(difference)
        self.grid_matrix = np.array(data, dtype=object).reshape(row_length, coloumn_length)

    def __str__(self):
        return str(self.grid_matrix)

    def replace(self, position, value):
        """Replace a value in a grid"""
        x,y = position
        rows, coloumns = len(self.grid_matrix), len(self.grid_matrix[0])
        if x < rows and y < coloumns:
            self.grid_matrix[x,y] = value

Note the goal is to make a generic grid class to make it easier to make different games with different tools so the actual rendering will be done in the game class.


texts:
I'm trying to build my first object oriented system. I'm not sure that my register function below is the best way of approaching this within OOP.

class User {
  public $username;
  private $email;
  private $password;

  public function register() {
   //Check if the username input is set.
   if(isset( $_POST['username'] )) {
     //Assign the variables.
     $this->username = $_POST['username'];
     $this->email = $_POST['email'];
     $unhashed_pass = $_POST['password'];

     //Hash the password
     $this->password = password_hash($unhashed_pass, PASSWORD_BCRYPT);

     $sql = "INSERT INTO 'users' ('id', 'username', 'email', 'password') VALUES (NULL, '$this->username', '$this->email', '$this->password')";
     $results = mysql_query($sql);

     if($results) {
      //Query was successful
      echo "Success";
     } else {
      echo mysql_error();
     }
   }
  }
}

Please give me any feedback. I'm okay with PHP; I'm just trying to learn how to effectively use OOP.


texts:
I am developing a GUI using Swing, but before my project gets too complex.  I would like to have a good design structure. I have a few ideas and will use a simple example to illustrate.  Some feedback on whether or not this is a good approach would be great.

This is what my GUI looks like:

There are 2 Jpanels LeftPanel and RightPanel. When Show Name is clicked the name in that panel pops up.

My approach for this is:

If a component is used more than once, I write a class(GetNameButton,NameLabel).
I write a class for each panel.  As the project gets bigger, the JFrame class won't get too cluttered and changes to a panel won't affect the JFrame class.

Here is the code:

public class MyFrame extends JFrame{

    public MyFrame(){
        this.setLayout(null);
        this.setBounds(100,100,400,400);
        this.add(new LeftPanel());
        this.add(new RightPanel());
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new MyFrame();
    }

}

LeftPanel

public class LeftPanel extends JPanel implements ActionListener{
    CloseButton cb = new CloseButton();
    JLabel name = new JLabel("foo");
    GetNameButton gnb = new GetNameButton();

    public LeftPanel(){
        this.setLayout(null);
        this.setBounds(20, 20, 160, 320);
        this.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null));
        this.add(new NameLabel());

        name.setBounds(50,10,40,10);
        this.add(name);
        this.add(cb);

        this.add(gnb);
        gnb.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==gnb){
            JOptionPane.showMessageDialog(null, name.getText());
        }

    }
}

RightPanel

public class RightPanel extends JPanel implements ActionListener{
    JLabel name = new JLabel("bar");
    GetNameButton gnb = new GetNameButton();

    public RightPanel(){
        this.setLayout(null);
        this.setBounds(200, 20, 160, 320);
        this.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null));
        this.add(new NameLabel());

        JLabel name = new JLabel("bar");
        name.setBounds(50,10,40,10);
        this.add(name);

        this.add(gnb);
        gnb.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==gnb){
            JOptionPane.showMessageDialog(null, name.getText());
        }
    }
}

GetNameButton

public class GetNameButton extends JButton{

    public GetNameButton(){
        this.setText("Show Name");
        this.setBounds(20,100,120,20);
    }

}

NameLabel

public class NameLabel extends JLabel{
    public NameLabel(){
        this.setBounds(10,10,40,10);
        this.setText("NAME: ");
    }

}

CloseButton

public class CloseButton extends JButton implements ActionListener{

    public CloseButton(){
        this.setText("Close");
        this.setBounds(20,50,100,20);
        this.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==this){
            System.exit(8);
        }
    }

}


texts: Optimizing Dijkstra implementation using PriorityQueue in Java

texts:
I am trying to make Dijkstra implementation more efficient. Below is the code for class Node which implements Comparable so it can be used in PriorityQueue.

public class Node implements Comparable<Node> {

private final char label;
private int distanceFromSource;
private final Map<Node, Integer> neighbourList;

public Node(char label, int distanceFromSource) {
    this.label = label;
    this.distanceFromSource = distanceFromSource;
    this.neighbourList = new LinkedHashMap<>();
}

public void addNeighbourer(Node node, int distance) {
    neighbourList.put(node, distance);
}

public char getLabel() {
    return label;
}

public Map<Node, Integer> getNeighbourerList() {
    return neighbourList;
}

public int getDistanceFromSource() {
    return distanceFromSource;
}

public void setDistanceFromSource(int distanceFromSource) {
    this.distanceFromSource = distanceFromSource;
}

@Override
public int compareTo(Node o) {
    return Integer.compare(this.getDistanceFromSource(), o.getDistanceFromSource());
}

}

Adding Node to PriorityQueue and calling the Dijkstra method to find shortest distances:

PriorityQueue<Node> nodePriority = new PriorityQueue<>();
    nodePriority.add(nodeA);
    nodePriority.add(nodeB);
    nodePriority.add(nodeC);
    nodePriority.add(nodeD);
    nodePriority.add(nodeE);
    nodePriority.add(nodeF);
    Dijkistra dijkistra = new Dijkistra();
    dijkistra.findShortestDistances(nodePriority, 6);

Below is the algorithm for Dijkstra:

public void findShortestDistances(PriorityQueue<Node> nodePriority, int noOfVertices) {

    Set<Node> MST = new LinkedHashSet<>();
    while (MST.size() < noOfVertices) { // time complexity: O(n)

        Node minNode = nodePriority.poll();
        MST.add(minNode);

        /* list of nodes to be updated in nodePriority after iteration finishes. */
        List<Node> nodesToAdd = new ArrayList<>();
        Iterator<Node> nodePriorityIterator = nodePriority.iterator();
        while (nodePriorityIterator.hasNext()) {  // time complexity: O(n)

            Node node = nodePriorityIterator.next();
            if (minNode.getNeighbourerList().containsKey(node)) { // time complexity: O(log(n))

                int adjacentNodeDistanceFromSource = minNode.getDistanceFromSource() + minNode.getNeighbourerList().get(node);
                if (node.getDistanceFromSource() > adjacentNodeDistanceFromSource) {

                    Node updatedCopy = node; // original node copied.
                    updatedCopy.setDistanceFromSource(adjacentNodeDistanceFromSource); // node copy updated with new value.
                    nodesToAdd.add(updatedCopy); // updated node added to list.
                    nodePriorityIterator.remove();  // time complexity: O(logn(n))
                }
            }
        }
        nodePriority.addAll(nodesToAdd); // all updated nodes added to priority Queue.
    }
    /* display final shortest distances for all vertices from source */
    for (Node node : MST) {
        System.out.println(node.getLabel() + " : " + node.getDistanceFromSource());
    }
}

I think the time complexity is \$O(n^2)\$. How can we improve on it?


texts: Prepared PHP statement to fetch posts for some category

texts:
I am slowly learning PHP and have been using prepared statements.

I have a simple category.php page, which takes a category tag to display posts from that category, such as localhost/php/category.php?tag=sysadmin. I want to select the Category Title from the "j_oracle_cat" table based on the value of the incoming tag in the querystring.

My code seems to be extremely cumbersome and long-winded (I'm using MySQLi instead of PDO):

<?php
/* connection string up here */

/* get category tag */
$foo = $_GET['tag'];

/* if it contains an apostrophe go to homepage */
$foo2 = strpos($foo, '\'');
if ($foo2 > 0) { Header("Location: default.php"); }

/* sql */
$cat_title_sql = "SELECT fld_title FROM j_oracle_cat WHERE fld_tag = ? LIMIT 1";

/* category variable */
$foo_cat = $foo;

/* initialise and prepare */
$stmt = $conn->stmt_init();
$result_cat_title = $stmt->prepare($cat_title_sql);
if(!$result_cat_title) { trigger_error("Error preparing statement: $stmt->error
SQL query: $cat_title_sql", E_USER_ERROR); }

/* bind */
$result = $stmt->bind_param('s',$foo_cat);
if(!$result) { trigger_error("Error binding parameter: $stmt->error
", E_USER_ERROR); }

/* execute */
$stmt->execute();

/* store */
$stmt->store_result();
$count_cat = $stmt->num_rows;

/* if no results go to homepage */
if ($count_cat == 0) {
    Header("Location: ../default.php");
    } elseif ($result) {
        $stmt->bind_result($fld_title);
        while ($stmt->fetch()) {
            $cat_ttl = $fld_title;
        }
}

/* ... header include down here */
?>
<title><?php echo $cat_ttl?></title>

I just wondered if I am making a meal of this, and if the code is over the top, or if I am on the right track (both with the prepared statement and handling the incoming querystring variable).


texts:
I'm making a bot for PlayStation 5.
And restock  is coming soon so I want to make my bot faster.
The approximate duration is 4.90 seconds.
Is there any way to make this faster?
I found that I should write this in C or C ++ for better results.
#startup
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
driver = webdriver.Chrome('chromedriver')
driver.maximize_window()
driver.get("https://www.games.rs/ps4-konzole/16794-konzola-playstation-4-1tb-pro-black-dualshock-fifa-21")

Cena and Kupi are unnecessary.
Program clicks to accept cookies.
Then scrolling cuz it needs to.
And then refreshing page until text in button is "Add to Cart".
#order
start_time = time.time()
kupi = driver.find_element_by_xpath('//*[@class="block product-attributes-wrapper clearfix"]/ul[1]/li[1]/div[1]/div[1]')
cena = driver.find_element_by_xpath('//*[@class="block product-attributes-wrapper clearfix"]/ul[1]/li[1]/div[1]/div[1]')
driver.find_element_by_xpath('//*[@id="modal-cookie-info"]/div/div/div/div/button').click()
driver.execute_script("window.scrollTo(712, 200);", kupi)
while True:
    try:
        driver.find_element_by_xpath('//button[text()="Dodaj u korpu"]')
    except NoSuchElementException:
        driver.refresh()
    else:
        driver.find_element_by_xpath('//button[text()="Dodaj u korpu"]').click()
        break

driver.find_element_by_xpath('//*[@id="miniCartContent"]/div[1]/a').click()
driver.execute_script("window.scrollTo(0 , 900);", )

Lastly login for informations and completing order.
#login
driver.find_element_by_xpath('//*[@id="order_address_content"]/div/div/div[2]/div[2]/div[1]/div[1]/div[2]/div/div/a').click()
time.sleep(0.2)
email = driver.find_element_by_css_selector('#login_email')
email.send_keys("mail")

password = driver.find_element_by_id('login_password')
password.send_keys("pass")
driver.find_element_by_xpath('//*[@id="login_modal"]/div/div/form/div[3]/button').click()
time.sleep(0.2)
driver.execute_script("window.scrollTo(0 , 1600);", )
driver.find_element_by_xpath('//*[@class="delivery-options list-unstyled"]/li[3]/div[1]/div[1]').click()
time.sleep(0.5)
driver.execute_script("window.scrollTo(0 , 2500);", )
driver.find_element_by_xpath('//*[@id="submit_order_one_page"]').click()

This prints duration of the program.
print("--- %s seconds ---" % (time.time() - start_time))


texts: Creating nested list comprehension of files starting with specific string

texts:
I have a directory with 'sets' of files that start with a state name followed by 4 or 5 digits (typically indicating year). Each 'file set' contains 3 files a .txt, a .png, and a .jpg.

Example of files in directory:

California1998_reform_paper.txt
California1998_reform_paper.pdf
California1998_reform_paper.jpg
California2002_waterdensity_paper.txt
California2002_waterdensity_paper.pdf
California2002_waterdensity_paper.jpg

Based on a users input I am trying to write some code that can put each of these file sets into a list of lists. Ultimately I would like to iterate over the list of lists. That said, I am not married to any one data type if a dictionary or something else may be more efficient.

I would like the user to be able to enter either:

The state name i.e. 'California' - to get all files from California
OR
The state name + year i.e. 'California1998' to get all files from California 1998

import os
import regex

directory = #path to directory
input = 'California1998'

# Does input match proper format? If not error.
mm = regex.match('^([a-z]+)([0-9]{4,5})|^([a-z]+)', input)
dir = str(os.listdir(directory))
if mm.group(1):
    state = mm.group(1)
    number = mm.group(2)
    state_num = state + number
    fileset = regex.findall(state_num, dir)
elif mm.group(3):
    state = mm.group(3)
    fileset = regex.findall(state + r'[0-9]{4,5}', dir)
else:
    print('Put some error message here')

# Does input exist? If not error.
if len(fileset) > 0:
    fileset = tuple(set(sorted(fileset)))
else:
    print('Put some error message here')

# Get list of lists
state_num_files = [[file.path
    for file in os.scandir(directory)
    if file.name.startswith(state_num)]
    for state_num in fileset]
return state_num_files

Above is the code I have thus far. It first uses regex.match to check the input, then regex.findall to find all matching state + years. I then create a sorted() set() from this list, which is converted into a tuple() called fileset. The last bit of code is a nested list comprehension that produces the list of lists by iterating through all files in the directory and iterating through all the state + years in fileset.

It certainly works, but seems repetitive and slower than it needs to be. My goal is to increase efficiency and remove any unnecessary iteration.

Thoughts on improvements:

Possibly replace each regex.findall with a nested list comprehension? and thus remove the state_num_files nested comprehension at the end of script?

Any thoughts are greatly appreciated!


texts: Parse a csv file and create a dictionary of partial results

texts:
I have a bunch of .csv files which I have to read and look for data. The .csv file is of the format:

A row of data I will ignore
State,County,City
WA,king,seattle
WA,pierce,tacoma

In every csv file, the order of columns is not consistent. For example in csv1 the order can be State,County,City, in csv2 it can be City,County,State. What I am interested is the State and County. Given a county I want to find out what State it is in. I am ignoring the fact that same counties can exist in multiple States. The way I am approaching this:

with open(‘file.csv’) as f:
    data = f.read()

# convert the data to iterable, skip the first line
reader = csv.DictReader(data.splitlines(1)[1:])
lines = list(reader)
counties = {k: v for (k,v in ((line[‘county’], line[‘State’]) for line in lines)}

Is there a better approach to this?


texts: Ideal FP/Scala way to vaildate rectangular list

texts:
I am learning Scala and FP (Functional Programming), coming from Java, OO and a strong imperative pardigm. I am now trying to implement a small puzzle solving project so I can get some deeper hands on experience with both Scala and FP.

So, I have the following Scala class:

class Bitmap2d(rowsByColumns: List[List[Int]]) {
  if (!validateRectangular) {
    throw new IllegalArgumentException("all rows must have same length")
  }

  def validateRectangular: Boolean = {
    rowsByColumns.size == rowsByColumns.filter(_.size / rowsByColumns.first.size != 1)
  }
}

I am attempting to validate the single class constructor parameter. The requirements of a properly constructed instance of this class are:

The list is not null or empty.
The list contains at least one list which is itself not null or empty.
If the outer list contains more than a single inner list, validate all the inner lists are of identical length.

I was quite proud of figuring out how to implement validateRectangular in the FP style of immutability (my first try was the traditional Java imperative approach). However, upon further analysis, I am now not happy with it as it visits every row (as opposed to stopping the evaluation at the first row that fails to have the correct size).

So, here are my questions:

In Java, the null and non-empty checks are obvious. Do I need to perform these checks in Scala (where null seems to be quite abhored)? If so, what would be considered the idiomatically correct way to do so. If not, why must I check for it in Java, but not in Scala?
While my validateRectangular method works fine, I would prefer a fail fast test which stopped iterating as soon as a row had a size different than the first row (the first row's size is considered the baseline to which all the remaining rows must conform). So, what would be the ideal FP way to approach re-writing validateRectangular such that it properly validates all rows are the same size, but fails fast (stops iterating) as soon as the current row is of a different size?
What is the correct way to reject constructing an instance of a Scala class if the parameters are not correctly defined? In Java, I use the standard style of throwing an exception in the constructor after a parameter fails to validate. That's what I have implemented above. Is that considered idiomatic Scala?

UPDATE:

Here's the same class modified per Daniel C Sobral's suggestions:

class Bitmap2d(rowsByColumns: List[List[Int]]) {
  require(validateRectangular, "all rows must have same length")

  def validateRectangular: Boolean = {
    rowsByColumns.forall(_.size == rowsByColumns.head.size)
  }
}