texts:
I have written a method that uses binary search to insert a value into an array.

It is working, but i would like to get a second opinion to see if i didn't write too much code for it. aka doing same thing twice for example.

The code looks for the right index for insertion and is called by an insert method that uses that index value to insert.

Here is the code:

public class OrdArray {

    final private long[] a;                      // ref to array
    int nElems;                                  // number of dataitems
    int curIn;
    //----------------------------------------------------------------------

    public OrdArray(int max) {                   // constructor
        a = new long[max];                       // create array
        nElems = 0;
    }

    public int binaryInsert(long insertKey) {
        int lowerBound = 0;
        int upperBound = nElems - 1;

        while (true) {
            curIn = (upperBound + lowerBound) / 2;
            if (nElems == 0) {
                return curIn = 0;
            }
            if (lowerBound == curIn) {
                if (a[curIn] > insertKey) {
                    return curIn;
                }
            }
            if (a[curIn] < insertKey) {
                lowerBound = curIn + 1;          // its in the upper
                if (lowerBound > upperBound) {
                    return curIn += 1;
                }
            } else if (lowerBound > upperBound) {
                return curIn;
            } else {
                upperBound = curIn - 1;          // its in the lower
            }
        }
    }

    public void display() {                      // display array contents
        for (int j = 0; j < nElems; j++) {       // for each element,
            System.out.print(a[j] + " ");        // display it
        }
        System.out.println("");
    }

    public void insert(long value) {             // put element into array
        binaryInsert(value);
        int j = curIn;
        int k;
        for (k = nElems; k > j; k--) {           // move bigger ones one up.
            a[k] = a[k - 1];
        }
        a[j] = value;                            // insert value
        nElems++;                                // increment size.
     }
}

public static void main(String[] args) {
    // TODO code application logic here
    int maxSize = 100;                                  // array size
    OrdArray arr;                                       // reference to array

    arr = new OrdArray(maxSize);                        // create array
    arr.insert(77);                                     // insert 10 items
    arr.insert(99);
    arr.insert(44);
    arr.insert(55);
    arr.insert(22);
    arr.insert(88);
    arr.insert(11);
    arr.insert(00);
    arr.insert(66);
    arr.insert(33);

    arr.display();
}

Feedback appreciated.


texts: Student project that calculates the return on an investment

texts:
This is a simple student project that calculates the return on an investment with a given investment amount, number of years invested, and annual interest rate.  I know this is pretty basic, but I'm just looking for feedback for formatting and other general improvements I can make to the code.

// Author: Joshua Ferrell
// Date: 3/25/2017

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

// A program that caculates the return on an investment.

public class Exercise15_5 extends Application {

    // globals
    private TextField tfInvestmentAmount = new TextField();
    private TextField tfNumYears = new TextField();
    private TextField tfAnnualInterestRate = new TextField();
    private TextField tfFutureValue = new TextField();
    private Button btCalc = new Button("Calculate");

    @Override
    public void start(Stage primaryStage) {

        // Create UI
        GridPane gridPane = new GridPane();
        gridPane.setHgap(5);
        gridPane.setVgap(5);
        gridPane.add(new Label("Investment Amount:"), 0, 0);
        gridPane.add(tfInvestmentAmount, 1, 0);
        gridPane.add(new Label("Number of Years:"), 0, 1);
        gridPane.add(tfNumYears, 1, 1);
        gridPane.add(new Label("Annual Interest Rate:"), 0, 2);
        gridPane.add(tfAnnualInterestRate, 1, 2);
        gridPane.add(new Label("Future Value:"), 0, 3);
        gridPane.add(tfFutureValue, 1, 3);
        gridPane.add(btCalc, 1, 4);

        // Set Properties for UI
        gridPane.setAlignment(Pos.CENTER);
        tfInvestmentAmount.setAlignment(Pos.BOTTOM_RIGHT);
        tfNumYears.setAlignment(Pos.BOTTOM_RIGHT);
        tfAnnualInterestRate.setAlignment(Pos.BOTTOM_RIGHT);
        tfFutureValue.setAlignment(Pos.BOTTOM_RIGHT);
        tfFutureValue.setEditable(false);
        gridPane.setHalignment(btCalc, HPos.RIGHT);

        // Process event (caculate future value)
        btCalc.setOnAction(e -> calculateFutureValue());

        // Create a scene and place it in the stage
        primaryStage.setScene(new Scene(gridPane, 300, 200));
        primaryStage.setTitle("Exercise15_05"); // Set Title
        primaryStage.show(); // Display the Stage
    }

    private void calculateFutureValue() {

        // Get Values from text fields
        double amount = Double.parseDouble(tfInvestmentAmount.getText());
        double interest = Double.parseDouble(tfAnnualInterestRate.getText());
        int years = Integer.parseInt(tfNumYears.getText());

        // Get Monthly interest rate
        double monthlyInterestRate = interest / 12 / 100;

        // Get Future Value
        double futureValue = amount * Math.pow(1 + monthlyInterestRate, years * 12);

        // set futureValue to tfFutureValue
        tfFutureValue.setText(String.format("$%.2f", futureValue));
    }
}


texts: PHP design pattern factory input for products and quotes

texts:
I'm working on figuring out the best way to design this so that it's well organized and it seems like the factory design pattern makes sense.

Updated:
What I'm building:
 - Pricing calculator
 - There are 4 products each having their own specific pricing rules that vary from user input
 - The person can choose between 1 product or all products

Should I have a Calculator class to determine product pricing or leave the calculations in each product type?

/*
 * Use Factory Pattern to build objects
 */

class ProductFactory {
    public static function createProduct($type) {
        switch ($type) {
            case 'solution1':
                return new Solution1Product();
                break;

            case 'solution2':
                return new Solution2Product();
                break;

            case 'solution3':
                return new Solution3Product();
                break;

            case 'solution4':
                return new Solution4Product();
                break;
        }

    }
}

/*
 * Abstract Product
 */

abstract class AbstractProduct {
    protected $price;
    protected $max_limit;
    protected $max_amount;

    abstract public function calculatePrice($dob, $gender, $amount);
}

/*
 * Solution 1 Product
 */
class Solution1Product extends AbstractProduct {
    protected $max_limit = 50000;

    function __contruct() {
        print "Test";
        return "Solution1";
    }

    function calculatePrice($dob, $gender, $amount) {
        $rate = 1.03;
        $price = 55;

        if ($amount >= $this->max_limit) {
            return "Max Limit Reached";
        }
        //@TODO go lookup price from tables

        $this->price = $rate * $price;
        return $this->price;
    }
}
$solution1 = ProductFactory::createProduct('solution1');
print $solution1->calculatePrice("02/25/1982", "male", 100000);


texts: Return early with Error from Sequence mapping

texts:
I have put together this f# code in an attempt to solve the following problem

Given a mapping operation that may not be able to return a value
Cease mapping over the remaining items of a sequence if the mapping operation fails
Append the error to items already mapped and return early

This cannot be achieved with the inbuilt Seq.map and I could not locate any other existing implementations
type OptionFunction<'a, 'b> = 'a -> 'b option
type ResultFunction<'a, 'b, 'c> = 'a -> Result<'b, 'c>

type MaybeProjection<'a,'b,'c> =
    | OptionProjection of OptionFunction<'a,'b>
    | ResultProjection of ResultFunction<'a,'b,'c>

type OptionResultBuilder<'e>() =
    member _.Return(x) = Result.Ok x
    member _.Bind(m,f) =
             let r = match m with
                        | Some a -> Ok a
                        | None -> Error Unchecked.defaultof<'e>
             Result.bind f r
    member _.Bind(m,f) = Result.bind f m

let orb = OptionResultBuilder()

let mapTillFail mapper s =
    let rec inner sq =
        seq {
            let mapped = orb {
                let! head = Seq.tryHead sq
                match mapper with
                | OptionProjection a ->
                    let! m = a head
                    return m
                | ResultProjection a ->
                    let! m = a head
                    return m
                }

            match mapped with
                | Error _ as err-> yield err
                | Ok _ ->
                    yield mapped
                    yield! sq |> Seq.skip 1 |> inner
        }
    inner s

//code to test it, not part of the implementation
let r = Seq.empty
let s = seq{1..10}

let op = OptionProjection (fun x -> if x < 5 then Some x else None)
let rp = ResultProjection (fun x -> if x < 5 then Ok x else Error "if >= 5")

r|> mapTillFail op
s|> mapTillFail op
r|> mapTillFail rp
s|> mapTillFail rp

The inbuilt Option and Result types are a natural fit, and I wanted to be able to use a mapping function that returned either of these types.
Despite several attempts to refactor the duplicate statements inside the match mapper with, I just could not not work out how to satisfy the compiler. Every attempt results in the compiler complaining that it can't find a suitable overload for Bind. Suggestions ?
Beyond that I'm largely happy with it for my purposes. But I welcome any other improvements, or comments on issues like performance (at this stage I've not stress tested it).


texts:
I just made this sort method. It runs fine and the code looks okay in my eyes.

Is is possible to optimize it so it runs faster?  If it's \$O(n^3)\$ now, it would be interesting changing it to \$O(n^2)\$ or something like that.

Side question: This is \$O(n^3)\$, right (I only like \$O(n^2)\$ and below)?

List<Log> errors = _logHandler.GetErrors(daysBack);
        List<Log> errorsSorted = new List<Log>();
        for (int i = 0; i < errors.Count; i++)
        {
            bool inserted = false;
            for (int j = 0; j < errorsSorted.Count; j++)
            {
                if (errors[i].Date < errorsSorted[j].Date)
                {
                    List<Log> tempList = new List<Log>();
                    tempList.AddRange(errorsSorted.GetRange(j,
                        errorsSorted.Count - j));

                    errorsSorted[j] = errors[i]; // replace at bigger date index
                    inserted = true;

                    errorsSorted.RemoveRange(j+1, errorsSorted.Count - (j+1));

                    // move all bigger dates one place to the right..
                    foreach (Log log in tempList)
                    {
                        errorsSorted.Add(log);
                    }
                    break;
                }
            }
            if (!inserted)
            {
                errorsSorted.Add(errors[i]); // No date is bigger, add at the end
            }
        }


texts: Parallel matrix multiplication in Java with streams

texts:
This StackOverflow post highlights how to do matrix multiplication using Java's stream.

With Java streams, there is a new way to enable concurrent threading with the Java's parallel stream.

ParallelMatrixMultiplication.java

  public Matrix multiply(Matrix v) {
    return new Matrix(Arrays.stream(this.m).parallel()
                            .map(row -> IntStream.range(0, v.m[0].length)
                            .mapToDouble(i -> IntStream.range(0, v.m.length)
                            .mapToDouble(j -> row[j] * v.m[j][i]).sum())
                            .toArray())
                            .toArray(double[][]::new));
  }

As you can see, I simply added the .parallel() method.

This function works fine as a noticeable speed up is seen for larger matrices.

I'm curious then, is there a way to optimize or speed this function up further?


texts: Optimization of Hibernate DAO in desktop application

texts:
I'm working on medium sized desktop application (with around 100 tables in database). For persistence layer I decided to use Hibernate for the first time to avoid massive redundancy of code for persistence layer.

This is final implementation of DAO interfaces:

public class BaseDAOImpl<E extends Serializable> implements BaseDAO<E> {

    @Override
    public void insert(E t) {
        Session session = HibernateUtil.openSession();
        try {
            session.beginTransaction();
            session.save(t);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();

            session.getTransaction().rollback();
        } finally {

            session.close();
        }
    }

    @Override
    public void delete(Class<E> e, int id) {
        Session session = HibernateUtil.openSession();
        try {
            session.beginTransaction();
            Object object = get(id, e);
            if (object != null) {
                session.delete(object);
            }
            session.getTransaction().commit();
        } catch (Exception ex) {
            ex.printStackTrace();

            session.getTransaction().rollback();
        } finally {
            session.close();
        }

    }

    @Override
    @SuppressWarnings("unchecked")
    public List<E> getAll(Class<E> c) {
        Session session = HibernateUtil.openSession();
        List<E> t = null;
        try {
            session.beginTransaction();
            t = session.createCriteria(c).list();
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
        return t;
    }

    @Override
    public void update(E t) {
        Session session = HibernateUtil.openSession();
        try {
            session.beginTransaction();
            session.merge(t);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally {

            session.close();
        }

    }

    @SuppressWarnings("unchecked")
    @Override
    public E get(int id, Class<E> c) {

        Session session = HibernateUtil.openSession();
        E t = null;
        try {
            session.beginTransaction();
            t = (E) session.get(c, id);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
        return t;
    }

}

Now, I'm a bit suspicious about session management. Is this a proper way to manage them (open session, commit changes, close session) or should I use some other approach, and what are the other suggestions to improve my code?


texts:
I am a very beginning in PHP and Design Patterns. I have been studying the amazing Head First Design patterns. So, I have been trying to translate the original into PHP. The class is working well, however, I would like to ask:

Is this considered good PHP?
Someone mentioned that this is not a Strategy Pattern. Head First's definition: "Strategy lets the algorithm vary independently from clients that use it".  Is this not correct?

<?php

interface FlyBehavior{
    public function fly();
}

class FlyWithWings implements FlyBehavior{
    public function fly(){
        echo "I am flying!
";
    }
}

class FlyNoWay implements FlyBehavior{
    public function fly(){
        echo "I cannot fly!";
    }
}

interface QuackBehavior{
    public function quack();
}

class QuackQuack implements QuackBehavior{
    public function quack(){
        echo "Quack
";
    }
}

class MuteQuack implements QuackBehavior{
    public function quack(){
        echo "Silence";
    }
}

class Squeak implements QuackBehavior{
    public function quack(){
        echo "Squeak";
    }
}

abstract class Duck{
    protected $quackBehavior;
    protected $flyBehavior;

    public function performQuack(){
        $this->quackBehavior->quack();
    }

    public function performFly(){
        $this->flyBehavior->fly();
    }

    abstract public function display();

    public function swim(){
        echo "All ducks float, even decoy";
    }

}

class MallardDuck extends Duck{
    public function __construct(){
        $this->quackBehavior=new QuackQuack();
        $this->flyBehavior=new FlyWithWings();
    }
    public function display(){
        echo "I am real Mallard duck!";
    }
}

$mallard=new MallardDuck();
$mallard->performQuack();
$mallard->performFly();

?>


texts:
This will get quite clumsy if I continue down the road with this design, so I'm asking you, enlightened ones, is there a way to make this prettier and easier to understand? Primarily the run-function (Especially in the else if where self.query and self.find are set), also, I want it to be chain-able, with .run being the last function.

db = function(dir){
    if(dir[dir.length - 1] == "/") this.dir = dir.slice(0, -1);
    else this.dir = dir;
    return this;
}

db.prototype.table = function(table){
    this.table = table;
    return this;
}

db.prototype.put = function(obj){
    this.put = obj;
    return this;
}

db.prototype.find = function(query){
    this.query = query;
    this.find = "all";
    return this;
}

db.prototype.pluck = function(){
    this.pluck = arguments;
    return this;
}

db.prototype.run = function(callback){
    var self = JSON.parse(JSON.stringify(this));
    for(var key in this){
        if(typeof this[key] != "function" && key != "dir" && key != "table") delete this[key];
    }
    helper.mkdb(self, function(err, created){
        helper.mktbl(self, function(err, created){
            var docs = [];
            if(self.put){
                helper.put(self, function(err, docs){
                    callback(err, docs);
                })
            }else if(self.query && self.find){
                helper.find(self, function(err, docs){
                    if(err) callback(err);
                    else{
                        self.docs = docs;
                        if(self.pluck){
                            helper.pluck(self, function(err, docs){
                                callback(err, docs);
                            })
                        }else{
                            callback(err, docs);
                        }
                    }
                })
            }else if(self.pluck){
                helper.pluck(self, function(err, docs){
                    callback(err, docs);
                })
            }else callback(new Error("Cannot execute \".run()\" without any functions before it"));
        })
    });
}


texts:
rags-to-riches of Convert seconds to hours, minutes and seconds.

In that question, BigDecimal was chosen to be the model class, which doesn't seem like a right fit for temporal amounts.

Sure, doing arithmetic should be the simpler and faster way, but I thought of using the Duration class to make this more 'API-driven'.

DurationFormatter

public final class DurationFormatter {

    private DurationFormatter() {
        // empty
    }

    public static String displayReadable(long seconds) {
        return displayReadable(Duration.ofSeconds(seconds));
    }

    public static String displayReadable(Duration duration) {
        if (Objects.requireNonNull(duration).isNegative()) {
            throw new IllegalArgumentException("seconds must not be negative.");
        }
        long hours = duration.toHours();
        long minutes = duration.minusHours(hours).toMinutes();
        long leftover = duration.minusHours(hours).minusMinutes(minutes).getSeconds();
        return replaceLast(
                Stream.of(append(hours, ChronoUnit.HOURS),
                            append(minutes, ChronoUnit.MINUTES),
                            append(leftover, ChronoUnit.SECONDS))
                        .filter(s -> !s.startsWith("0"))
                        .collect(Collectors.joining(", ")), ", ", " and");
    }

    private static String append(long value, ChronoUnit unit) {
        return String.format("%d %s", Long.valueOf(value),
                value == 1 ? singular(unit) : unit).toLowerCase();
    }

    private static String singular(ChronoUnit unit) {
        String toString = unit.toString();
        return toString.substring(0, toString.length() - 1);
    }

    private static String replaceLast(String input, String target, String replacement) {
        int lastIndex = input.lastIndexOf(target);
        return lastIndex == -1 ? input : input.substring(0, lastIndex) + replacement
                + input.substring(lastIndex + 1);
    }
}

DurationFormatterTest

public class DurationFormatterTest {

    enum TestCase {
        ZERO(0, ""),
        ONE_SEC(1, "1 second"),
        TWO_SECS(2, "2 seconds"),
        ONE_MIN(60, "1 minute"),
        TWO_MINS(120, "2 minutes"),
        ONE_MIN_ONE_SEC(61, "1 minute and 1 second"),
        ONE_HR(3600, "1 hour"),
        TWO_HRS(7200, "2 hours"),
        ONE_HR_ONE_SEC(3601, "1 hour and 1 second"),
        ONE_HR_ONE_MIN(3660, "1 hour and 1 minute"),
        ONE_HR_ONE_MIN_ONE_SEC(3661, "1 hour, 1 minute and 1 second"),
        MAX(Long.MAX_VALUE, "2562047788015215 hours, 30 minutes and 7 seconds");

        private final long seconds;
        private final String expected;

        private TestCase(long seconds, String expected) {
            this.seconds = seconds;
            this.expected = expected;
        }

        void verify() {
            assertThat(DurationFormatter.displayReadable(seconds), equalTo(expected));
        }

        @Override
        public String toString() {
            return String.format("%d seconds => \"%s\"", Long.valueOf(seconds),
                    expected);
        }
    }

    @DataProvider(name = "test-cases")
    public Iterator<Object[]> getTestCases() {
        return EnumSet.allOf(TestCase.class).stream().map(v -> new Object[] { v })
                .iterator();
    }

    @Test(dataProvider = "test-cases")
    public void testCases(TestCase testCase) {
        testCase.verify();
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testNegativeValue() {
        try {
            DurationFormatter.displayReadable(-1);
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage(), equalTo("seconds must not be negative."));
            throw e;
        }
    }

    @Test(expectedExceptions = NullPointerException.class)
    public void testNullValue() {
        DurationFormatter.displayReadable(null);
    }
}


texts: Simple TCP Send Receive with multithreading c#

texts:
Wondering how this sample program can be made better. Specifically what exceptions should I expect to handle? Right now it's working as expected. I put a breakpoint after the statement:

int numBytesReadFromStream = stream.Read(bytes, 0, bytes.Length);

to check to see if the bytes variable had data in it and it did.

using System.Threading;
using System.Net;
using System.Net.Sockets;
using System;

namespace ConsoleApp2
{
    class Program
    {
        public static void Main()
        {
            var localIP = IPAddress.Parse("10.10.10.117");
            var listenerPort = 20000;
            var senderPort = listenerPort + 2;
            IPEndPoint listenerEndpoint = new IPEndPoint(localIP, listenerPort);
            IPEndPoint senderEndpoint = new IPEndPoint(localIP, senderPort);
            TcpListener tcpListener = new TcpListener(listenerEndpoint);
            StarttcpListenerThread(tcpListener);
            Thread.Sleep(300);
            StartTCPSendingThread(listenerEndpoint, senderEndpoint);
            while (true)
            {
            }
        }

        static void StarttcpListenerThread(TcpListener tcpListener)
        {
            tcpListener.Start();
            Thread tcpListenerThread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        byte[] bytes = new byte[1024];
                        TcpClient currentConnection = tcpListener.AcceptTcpClient();
                        NetworkStream stream = currentConnection.GetStream();
                        int numBytesReadFromStream = stream.Read(bytes, 0, bytes.Length);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }

                }
            });
            tcpListenerThread.Start();
        }

        static void StartTCPSendingThread(IPEndPoint listenerEndpoint, IPEndPoint senderEndpoint)
        {
            TcpClient tcpClient = new TcpClient(senderEndpoint);
            tcpClient.Connect(listenerEndpoint);
            Thread tcpSendingThread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        tcpClient.Client.Send(new byte[] { 1, 2, 8 });
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            });
            tcpSendingThread.Start();
        }
    }
}


texts: Finding whether there exists a pair of numbers in a set having a given product

texts:
Devise an algorithm that will operate on a number x and a set of n
  distinct numbers such that in \$O(n \lg n)\$ time, the algorithm indicates
  whether or not there are two numbers in the set that have a product of
  x. Explain why your algorithm works.

My algorithm:

Sort the set //\$ O(n \lg n)\$
For every element in the set check if x % element =0 // \$O(n)\$
If so check if the dividend x/element exists in the set // \$O(\lg n)\$
If dividend exists and is not equal to element, the two numbers in the set (element and dividend) have a product of x.

This algorithm works because it only returns true when the condition(x=element*dividend where element and dividend are in the set) to be satisfied is met. And upon quick Analysis we can see that the algorithm is running at \$O(n\lg n)\$ for the sort and \$O(n)*(\lg n)\$ for checking if the two elements exists. Therefore it is running at \$O(n \lg n) + O(n \lg n) = O(2n \lg n) = O(n \lg n)\$

Can I have some feedback on my solution — whether you think it is correct or not and where you think it can be improved?

def findIfProdExists(x,items):
    items = mergeSort(items) # O(nlgn)
    for item in items:
        if(item!=0):
            if x%item ==0:
                if item!=x/item and find(x/item,items):  #binary Search O(lgn)
                    return True
    return False

def mergeSort(aList):
    size = len(aList)
    first = aList[:int(size/2)]
    second = aList[int(size/2):]

    if(size ==1):
         return aList
    if(size ==2):
        if(aList[1]<aList[0]):
            return list([aList[1],aList[0]])
        else:
            return aList
    else:
        return merge(mergeSort(first),mergeSort(second))

def merge(list1,list2):
        newList =[]
        i1 =0
        i2 =0
        while i1<len(list1) and i2 <len(list2) :
            if list1[i1] <list2[i2] :
                newList.append(list1[i1])
                i1+=1
            elif list1[i1]>list2[i2] :
                newList.append(list2[i2])
                i2+=1
            else:
                newList.append(list1[i1])
                i1+=1
        newList.extend(list1[i1:] +list2[i2:])
        return newList

def find(x,items):
    lo = 0
    hi = len(items)
    while lo<hi:
        mid = (lo + hi) // 2
        if x == items[mid]:
            return True
        elif x < items[mid]:
            hi = mid
        else:
            lo = mid + 1
    return False


texts:
Problem:

  Write a program that manages robot factory settings.

  When robots come off the factory floor, they have no name.

  The first time you boot them up, a random name is generated, such as
  RX837 or BC811.

  Every once in a while we need to reset a robot to its factory
  settings, which means that their name gets wiped. The next time you
  ask, it will respond with a new random name.

  The names must be random: they should not follow a predictable
  sequence. Random names means a risk of collisions. Your solution
  should not allow the use of the same name twice when avoidable. In
  some exercism language tracks there are tests to ensure that the same
  name is never used twice.

Code:

import java.util.Random;
import java.util.Set;
import java.util.HashSet;

public class Robot {
  private static final String ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  private static final Set<String> generatedNames = new HashSet<>();
  private String name;

  public String getName() {
    while (name == null) {
      name = generateName();
      if (generatedNames.contains(name)) name = null;
    }
    generatedNames.add(name);
    return name;
  }

  public void reset() {
    name = null;
  }

  private String generateName() {
    StringBuilder builder = new StringBuilder();
    int i;
    for (i = 0; i < 2; i++) {
      builder.append(ALPHABETS.charAt(generateRandomInRange(0, 25)));
    }
    for (i = 0; i < 3; i++) {
      builder.append(generateRandomInRange(0, 9));
    }
    return builder.toString();
  }

  private int generateRandomInRange(int min, int max) {
    return new Random().nextInt((max - min) + 1) + min;
  }
}

Test Suite:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertEquals;

public class RobotTest {

    private static final String EXPECTED_ROBOT_NAME_PATTERN = "[A-Z]{2}\\d{3}";
    private final Robot robot = new Robot();

    @Test
    public void hasName() {
        assertIsValidName(robot.getName());
    }

    @Test
    public void differentRobotsHaveDifferentNames() {
        assertThat(robot.getName(), not(equalTo(new Robot().getName())));
    }

    @Test
    public void resetName() {
        final String name = robot.getName();
        robot.reset();
        final String name2 = robot.getName();
        assertThat(name, not(equalTo(name2)));
        assertIsValidName(name2);
    }

    private static void assertIsValidName(String name) {
        assertThat(name.matches(EXPECTED_ROBOT_NAME_PATTERN), is(true));
    }
}

Question:

Apart my naming and data structure I am interested in knowing if my solution would scale well or not?

Reference: Exercism


texts:
I am working on an open Chess data-set (~15500 rows after cleaning), and I create nodes and edges. But the way I create the edges takes a bit of time.
A sample of my nodes tibble:

player

1
bougris

2
a-00

3
ischia

...
...

A sample picture of the per_game tibble:

The way I do it:

I iterate for each node/player in nodes tibble,
searching the games where he played as black in per_game,
and exchanging values of column white_d with black_id, while changing the winner in winner column (using the swap() method I created).
Then, with calc_victories() method, I group all games for the specific player, with every opponent he has faced, and calculating how many times he won, or lost, from the opponent (I store it to player_result). An example picture:

Then I append the player_result to a tibble, with all previous players' results.
Finally, I delete from the per_game tibble the node I just handled, both from black and white columns.

Here is my code:
for(i in 1:dim(nodes)){
    # Exchange values of white with black column, only where black_id is the specific player
    per_game[per_game$black_id == nodes[[1]][i], c('white_id', 'black_id', 'winner')] <-
        per_game[per_game$black_id == nodes[[1]][i], c('black_id', 'white_id', swap('winner'))]

    # Calculate the victories, for each opponent of the specific player
    player_results <- calc_victories(nodes[[1]][i])

    # Append the player's matches with the rest.
    all_results <- rbind(all_results, player_results)

    # Delete all matches with the specific player, either if he/she is black or white
    per_game <- subset(per_game, white_id != nodes[[1]][i] & black_id != nodes[[1]][i])
}
all_results

Here are the functions calc_victories() and swap():
# A method to group the matches for a player, and sum his victories against each opponent
calc_victories <- function(i='-') {
    player_results <- per_game %>%
        filter(white_id==i | black_id==i) %>% # Finds matches with the specific player
        group_by(white_id, black_id) %>%
        rename(player1=white_id, player2=black_id) %>%
        summarise_at(vars(total_matches), list(victories = sum)) %>% # Summarize total matches
        arrange(desc(victories)) %>% # Sorts descending
        ungroup()

    return (player_results)
}

# A method to change the winner, because of white-black column exchange
swap <- function(winner='draw') {
    if(winner=='black'){
        gets = 'white'
    } else if(winner=='white'){
        gets = 'black'
    } else {
        return (winner)
    }
    return(gets)
}

The code executes for about 5 minutes, to handle all nodes. I think that this is happening, mainly because I iterate for each node. Maybe I should use something like map, but I am not so sure. Thank you.


texts:
I have this code but it takes over a minute to run. I'm looking at around 400 entries being brought back for the first loop. Any ideas on how it could be improved for speed?

<?php

    $context = stream_context_create(array(
        'http' => array(
            'method' => 'GET',
            'header' => "Authorization: Basic abc123\r\nContent-Type: application/json\r\n"//,'content' => json_encode($postData)
        )
    ));

    // Send the request
    $response = file_get_contents('https://localhost', FALSE, $context);

    // Check for errors
    if($response === FALSE){
        die('Error');
    }
    // Decode the response
    $responseData = json_decode($response, TRUE);

    // Print the date from the response
    foreach($responseData as $row) {
       foreach($row as $k) {
             $response = file_get_contents('https://localhost/answers'.$k['id'], FALSE, $context);
             $responseDataAns = json_decode($response, TRUE);
                 echo $responseDataAns['summary']." / ".$responseDataAns['solution']."\r\n";
       }
    }
    ?>

This is the REST API I am using specifically. This is used to retrieve all answers then this to get an instance.

I want to use the REST API to list all questions, allow someone to go into a question and then update it.


texts:
I have a personal project that runs the backend under spring boot that implements websocket for real-time functionality and I apply it to a crud operations.

Although the code is working and work as expected I doubt if I do the correct implementation of spring websocket here.

I've used React as my frontend as call the crud function on their @MessageMapping annotation.

The way I implement the backend to my frontend is.

Fetching all Person records and store in an array state.
Then for create Person record I just append in to the new record to the persons state array

I doubt if I do it correctly because when I debug the websocket client, I found out that it.

@Autowired
private SimpMessagingTemplate template;

@Autowired
public PersonController(PersonRepository personRepository) {
    this.personRepository = personRepository;
}

@MessageMapping("/person/add")
public void createPerson(Person person) {
    Person savePerson = new Person(person.getFirstName(), person.getLastName());
    personRepository.save(savePerson);
    this.template.convertAndSend("/topic/person", viewPersons());
}

@RequestMapping("/person")
@ResponseBody
public List<Person> viewPersons(){
    List<Person> persons = personRepository.findAll();
    return persons;
}

@MessageMapping("/person/delete")
public void deletePerson(@Payload PersonDeleteRequest request) {
    Person person = personRepository.findById(request.getId()).orElseThrow(() -> new RuntimeException("No id found."));
    personRepository.delete(person);
    this.template.convertAndSend("/topic/person", viewPersons());
}

@MessageMapping("/person/update")
public void updatePerson(@Payload Person requestPerson) {
    Person person = personRepository.findById(requestPerson.getId()).orElseThrow(() -> new RuntimeException("No id found."));
    person.setFirstName(requestPerson.getFirstName());
    person.setLastName(requestPerson.getLastName());
    personRepository.save(person);
    this.template.convertAndSend("/topic/person", viewPersons());
}


texts: Screen recorder producing huge AVI files

texts:
I'm currently trying to make a screen recorder in C#, and so far it works but the problem is that something as simple as a 20second video will take about 1GB of space. I have it setup so a timer continuously takes screenshots with this method:

void takeScreenshot()
{
    Rectangle bounds = Screen.FromControl(this).Bounds;
    using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            //Add screen to bitmap:
            g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
        }
        //Create and save screenshot:
        string name = path + "//screenshot-" + fileCount + ".jpeg";
        bitmap.Save(name, ImageFormat.Jpeg);
        inputImageSequence.Add(name);
        fileCount++;

        //Dispose of bitmap:
        bitmap.Dispose();
    }
}

And then it stores those pictures in a temporary folder in the D:// drive, and then when it's done it takes all the pictures and creates an AVI video out of them like this:

//Set bounds of video to screen size:
Rectangle bounds = Screen.FromControl(this).Bounds;
int width = bounds.Width;
int height = bounds.Height;

var framRate = 5;

using (var vFWriter = new VideoFileWriter())
{
    //Create new video file:
    vFWriter.Open(outputPath+"//video.avi", width, height, framRate, VideoCodec.Raw);

    //Make each screenshot into a video frame:
    foreach (var imageLocation in inputImageSequence)
    {
        Bitmap imageFrame = System.Drawing.Image.FromFile(imageLocation) as Bitmap;
        vFWriter.WriteVideoFrame(imageFrame);
        imageFrame.Dispose();
    }
    vFWriter.Close();
}
//Delete the screenshots and temporary folder:
DeletePath(path);

Any help on reducing the inefficiency of this is appreciated, I'm fairly new to this kind of programming.


texts: Dragable infinite loop carousel, performance issues on dragging large number (25+) of slides

texts:
I have two instances of this carousel to test with, one with 7 slides and the other with 25. They run the exact same code. The 7 slide instance drags smoothly forever as intended, but the 25 slide instance is choppy when dragging.

Something in the dragMove event is slowing down execution when the slide count is higher, and I'd like to find a way to improve it so that the slide count has no effect on performance.

I've already tried a few optimizations, like replacing:

$slider.children().last()

with

$Slider[0].lastChild

To bypass instantiating of all those unnecessary Jquery objects just to get the last one, but dragging is still choppy.

Here's the dragMove event:

function dragMove(event){
  var ev = event.originalEvent || event || window.event;
  var MousePosition = GetEventCoordinates(ev);
  var MouseMoveDistance = (MousePosition.x-locals.StartingMousePosition.x);
  var DistanceDifference = (locals.LastMouseMoveDistance-MouseMoveDistance);
  var MoveDirection = (DistanceDifference === 0 || isNaN(DistanceDifference)) ? locals.LastMoveDirection : (DistanceDifference>0) ? '<' : '>' ; // negative to the left
  var StepsMoved = Math.floor(MouseMoveDistance/base.protected.ItemWidth);
  var StepsDifference = (locals.LastStepsMoved-StepsMoved);

  if(StepsDifference !== 0 || locals.LastMoveDirection !== MoveDirection){
     // Steps has changed, recalculate!
     var oEdgeCounts = base.GetEdgeCounts();

     if(oEdgeCounts.left<1 && MoveDirection==='>'){
        // There are non to the left, but we need some!
        if(StepsDifference===0){StepsDifference=1;}
        for(var i=0; i<Math.abs(StepsDifference); i++){
           $Last = $(base.protected.$Slider[0].lastChild);
           base.protected.$Slider.prepend($Last);
        }
        locals.PopAdjustment = (locals.PopAdjustment+(Math.abs(StepsDifference)*base.protected.ItemWidth));
     }

     if(oEdgeCounts.right<1 && MoveDirection==='<'){
        //There are none to the right, but we need some!
        if(StepsDifference===0)StepsDifference=1;
        for(var i=0; i<Math.abs(StepsDifference); i++){
           $First = $(base.protected.$Slider[0].firstChild);
           base.protected.$Slider.append($First);
        }
        locals.PopAdjustment = (locals.PopAdjustment-(Math.abs(StepsDifference)*base.protected.ItemWidth));
     }
  }

  locals.NewSliderLeft = GetEventCoordinates(ev).x - locals.DragStartTouchOffsetX-locals.PopAdjustment;

  // Save values so we can compare on next event
  locals.LastSampleMousePosition = MousePosition;
  locals.LastMouseMoveDistance = MouseMoveDistance;
  locals.LastMoveDirection = MoveDirection;
  locals.LastStepsMoved = StepsMoved;

  base.protected.$Slider.css('left',locals.NewSliderLeft);
}

Here is the get Edge count function. It uses simple math to determin the number of slides off the left and off the right sides. I don't think it's speed is impacted by slide count.

GetEdgeCounts = function(){
   var base = this;
   var SliderLeft = parseInt(base.protected.$Slider.css('left'),10);
   var OffLeftCount = Math.abs(SliderLeft)/base.protected.ItemWidth;
   var OffLeftFloor = Math.floor(OffLeftCount);
   var OffRightCount = base.protected.TotalItems-base.protected.ItemsPerPage-OffLeftCount;
   var OffRightFloor = Math.floor(OffRightCount);

   OffRightFloor = (OffRightFloor >=0) ? OffRightFloor : 0;
   OffLeftFloor = (OffLeftFloor >=0) ? OffLeftFloor : 0;
   return{
      left:OffLeftFloor,
      right:OffRightFloor,
      center:base.protected.ItemsPerPage
   };
}

I'm looking for any ideas on how to make dragging with larger slide counts less choppy.


texts:
I have developed a few web applications according to my own coding style similar to MVC architecture. I'm a self learner. But there is no controller class or model class. In my way, I don't split the URL. I have mentioned below an example URL. Now I'm familiar with this process, but I know this is not a professional level coding, so I tried to move to MVC. Now I can easily manage any javascript, ajax call. I don't know how to use JavaScript and Ajax in MVC.

Basically my question is:  Shall I continue in this way?

My project file structure.

Below example based on this URL

/root
  -/images
  -/include
  ---database.php
  ---user.php
  ---course.php
  -/layout
  ---/user
  ---/course
  ---index.php
  -index.php
  -config.php

Cofig.php

require("include/database.php");
require("include/user.php");
require("include/course.php");

$db = Database::getInstance();
$user = new user();
$course = new course();

index.php

<?php
include('config.php');

//get view page using url
$view_page = isset($_GET['view']) ? $_GET['view']: 'home';

?>

      <?php
        include('layout/index.php');
      ?>

layout/index.php

<?php
    include($_SERVER['DOCUMENT_ROOT'].'/layout/'.$view_page.'.php');
?>

layout/user/index.php

//this page will be displayed : www.mysite.com/index.php?view=user/index&uid=234
// user/index = (folder/page) or (view/action)
// these details will be dispalyed with

<?php

$userDetails = $user->getUserDetails($_GET['uid']);

  echo $userDetails['username'];
  echo $userDetails['email'];

?>


texts: Uses SeekBar to adjust the data displayed in UI from my Room database

texts:
I wrote code that takes the value of the progress bar in my Android app which influences what is displayed on the UI. If the user's progress bar value is above or below a certain number, data will be either displayed or not displayed. Here is the following code:

    public class DetailsFirstTabFragment extends Fragment {

    private DetailsFirstTabViewModel viewModel;
    private RecyclerView recentThings;
    private TextView progressTextView;
    final RecentThings adapter = new RecentThings();
    private List<ThingEntity> thingEntities;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel =
                ViewModelProviders.of(this).get(DetailsFirstTabViewModel.class);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_first_page_expense_details, container, false);

        recentThings = root.findViewById(R.id.recycler_view_recent_things);
        recentThings.setLayoutManager(new LinearLayoutManager(getContext()));
        recentThings.setHasFixedSize(true);

        recentThings.setAdapter(adapter);

        final float[] totalSum = {0};
        final TextView textViewTotalSum = root.findViewById(R.id.textViewStuffTotalSum);

        SeekBar seekBar = root.findViewById(R.id.seekBarStuffDetails);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        progressTextView = root.findViewById(R.id.textViewProgress);

        viewModel.getAllThings().observe(this, new Observer<List<ThingEntity>>() {
            @Override
            public void onChanged(List<ThingEntity> thingEntities) {
                for (ThingEntity thing : thingEntities) {
                    totalSum[0] = totalSum[0] + thing.getThingAmount();
                }
                textViewTotalSum.setText(String.valueOf(totalSum[0]));
                adapter.setThingEntityList(thingEntities);
                setThingEntities(thingEntities);
            }
        });
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Bundle args = getArguments();
    }

    public void setThingEntities(List<ThingsEntity> thingEntities) {
        this.thingEntities = thingEntities;
    }
    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        int progressValue = 0;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            String progressText = "Date " + String.valueOf(progress);
            progressValue = progress;
            progressTextView.setText(progressText);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            List<ThingEntity> shownThings = new ArrayList<>();
            for (ThingEntity entity : thingEntities) {
                if (entity.getThingAmount() > progressValue) {
                    shownThings.add(entity);
                }
            }
            adapter.setThingEntityList(shownThings);
        }
    };
}

So I am wondering if I am treating this need in a good way. I am not sure if getting all the entities and then looping over them to see if the condition is met to display is a good implementation. Additionally, I am wondering if the rest of the code makes sense. I am also not sure if I am creating viewmodels and observers in a resource-mindful manner. Any insight to these concerns (or ones I have not observed) would be very much appreciated (I am a beginner :))


texts: Count the different positions reached in a cycle of permutations

texts:
I have come across a problem on cyclic permutations. It is about swapping numbers around.
It starts out with input N < 100,000 which makes the first N natural numbers as orders: 1 2 3 ... N-1 N
Then we get the next input K < 200,000 as the period
Next N input lines are the swaps:
For example, the input is
5 4
1 3
1 2
2 3
2 4

There are 5 numbers and the swap period is 4. The first swap switches number at position 1 with position 3. The second swap is between position 1 and position 2. The third swap is between position 2 and position 3. The fourth swap is between 2 and 4. K+1th swap is same as first. K+2th swap is same as second. Etc.
The simulation for this is:
1 2 3 4 5
3 2 1 4 5
2 3 1 4 5
2 1 3 4 5
2 4 3 1 5
3 4 2 1 5
4 3 2 1 5
4 2 3 1 5
4 1 3 2 5
3 1 4 2 5
1 3 4 2 5
1 4 3 2 5
1 2 3 4 5

We can see that the original number at position 3 can go to positions 1, 2, and 3. The original number at position 1 can go to positions 1, 2, 3, 4. The original number at position 2 can go to positions 1, 2, 3, 4. The original number at position 4 can go to positions 1, 2, 3, 4. The original number at position 5 can go to positions 5.
Position 1 goes to 4 positions. Position 2 goes to 4 positions. Position 3 goes to 3 positions. Position 4 goes to 4 positions. Position 5 goes to 1 position.
Given that each output line is represented by y, the output is the number of totals positions the yth original position goes to. Output for this example is:
4
4
3
4
1

The memory limit is 256MB and the time limit is 2 seconds for noninterpreted languages such as C++ and 4 seconds for interpreted languages such as Java.

z, d = map(int, input().split())

S = []

pos = {}

for i in range(1, z+1):
  pos[i] = [i,]

permute = list(range(1, z+1))
for i in range(d):
  S.append(list(map(int, input().split())))

Flag = True

while Flag:
  Flag = False
  for i in S:
    if i[0] not in pos[permute[i[1]-1]]:
      Flag = True
      pos[permute[i[1]-1]].append(i[0])
    if i[1] not in pos[permute[i[0]-1]]:
      Flag = True
      pos[permute[i[0]-1]].append(i[1])
    permute[i[0]-1], permute[i[1]-1] = permute[i[1]-1], permute[i[0]-1]

for i in pos:
  print(len(pos[i]))

My solution takes too much space/time. Can you help me fix this?
I know this problem has DFS but I don't know what the graph to do DFS on looks like?


texts: Substitution cipher algorithm performance boost

texts:
This algorithm is meant to read a string of numbers on an input, a naive substitution cipher code (A = 1, B = 2, ..., Z = 26) and output the number of ways the code could be interpreted (e.g. 25114 could mean 'BEAN', ‘BEAAD’, ‘YAAD’, ‘YAN’, ‘YKD’ and ‘BEKD’, hence output is 6).

It is working properly, but not fast enough, though.  Is there a way to improve its performance? I commented it heavily, so it is easy to read.

#include <iostream>
#include <string>

using namespace std;

//Those are global, because handled by both functions
int ways;       //number of ways the code could be interpreted
string s;       //input

//Takes account of all the tuples after the one on position "start" using
//recursion
void findNextPossible(size_t start) {
    if(start + 2 <= s.length()){
        //Tuple considered
        string ss = s.substr(start, 2);
        //Otherwise not interpretable as a letter
        if(ss <= "26") {
            ways++;
            for(size_t i = 0; i <= s.length(); i++) findNextPossible(start+2+i);
        }
    }
}

int main() {
    size_t pos;
    bool test, someDeletedInTheMiddle;
    //Until zero on input
    while(cin >> s, s.at(0) != '0') {
        ways = 0;
        test = true;
        someDeletedInTheMiddle = false;
        pos = s.find('0');
        //In this while I look for zeros
        while(pos != string::npos) {
            //Code with 30,40,... is not valid -> output 0
            if(s.at(pos - 1) > '2') {
                test = false;
                break;
            }
            //If delete some in the middle, output smaller by 1
            if((pos >= 2 && pos < s.length()-1) && s.length() > 2) someDeletedInTheMiddle = true;
            //Don't cosider the tuple with zero in it anymore
            s.erase(pos-1, 2);
            //Any other zero?
            pos = s.find('0', pos);
        }
        if(test) {
            if(!someDeletedInTheMiddle) ways++;
            //Process the rest
            for(size_t i = 0; i < s.length(); i++) {
                findNextPossible(i);
            }
        }
        cout << ways << endl;
    }
    return 0;
}


texts:
I want to use this function to store 1024 bit keys in my Mysql database. If you call generateKey(128), you'll get a 128 byte string, same as 1024 bit string. I want to know if there is something wrong with this code or if I should be worried about inter-operability issues with MySQL, Java, Android, File Read/Write, etc.

    public function generateKey($size){

    $randomString = "";
    $charUniverse = "";
    for($i=0;$i<256;$i++){
        $charUniverse .= chr($i);
    }
    for($i=0;$i<$size;$i++){
        $randInt=mt_rand(0, strlen($charUniverse)-1);
        $randChar=$charUniverse[$randInt];
        $randomString=$randomString.$randChar;
    }
    return $randomString;
}


texts: DRY version of this one line if/else for property's existence

texts:
I have an object for which I wish to modify a property if a condition is met, else leave it virginal.

I find my current code to be very repetitive and would instead like to use a more succinct form, but am unsure of how to lambda-fy it or at least tell it to pass if condition not met:

my_object.unique_id = 'TBC' if not my_object.unique_id else my_object.unique_id

I guess this is nicer, but still repetitive:

if not my_object.unique_id: my_object.unique_id = 'TBC'

I would like something more like

my_object.unique_id = 'TBC' if None

Is there a way to only reference the property once?


texts: Implementation of Permutation Algorithm A from Topor, 1982

texts:
This is Algorithm A from Functional Programs for Generating Permutations (Topor, 1982). The author states that the algorithm was described in TAoCP Vol 1.

We have implemented Algorithm A in F# as follows.

let rec put (a: 't) (p: List<'t>) (q: List<'t>) : List<'t> =
    if p = q then a :: q
    else p.Head :: (put a p.Tail q)

// a: an element
// p: a list of elements
// q: a sublist of p
// ps: a list of permutations
let rec insert (a: 't) (p: List<'t>) (q: List<'t>) (ps: List<List<'t>>) : List<List<'t>> =
    if q.Length = 0 then (put a p q) :: ps
    else (put a p q) :: (insert a p q.Tail ps)

let rec mapinsert (a: 't) (ps: List<List<'t>>) : List<List<'t>> =
    if ps.Length = 0 then List.empty<List<'t>>
    else insert a ps.Head ps.Head (mapinsert a ps.Tail)

// x: a list of elements
// returns a list of permutations
let rec permute1 (x: List<'t>) : List<List<'t>> =
    if x.Length = 0 then [x]
    else mapinsert x.Head (permute1 x.Tail)

Here is a usage example

permute1 [1;2;3] |> List.iter (printf "%A ")
// [1; 2; 3] [2; 1; 3] [2; 3; 1] [1; 3; 2] [3; 1; 2] [3; 2; 1]

We would like a review to make our F# more canonical. That is, we would like to adjust our code to be in keeping with common F# styles and techniques.

Alternatively, we would like a reviewer to show alternative techniques (if not better ones) for implementing Algorithm A in F#.


texts: Binary search use in simple guessing game

texts:
I'm making a simple guessing game in C. Basically what I need is some help double-checking my work, more specifically a verification that the my binary search in my case statements look okay. The goal is to have an initial guess of 50, then work off that. If "L" is selected, the search goes from 51-100, if "H", it would be 1-49, blah-blah - the usual stuff scaling down to the correct guess.

Is this correct?

I'm also getting a C99 function implementation error using the actual letters as case labels -- just to explain why they're the ASCII equivalents.

#include <stdio.h>
#include <ctype.h>

int main(int argc, const char * argv[])
{
int low;
int high;
int guess;
int response;

 printf("Pick an integer from 1 to 100 and I will try to guess it.\n");
 printf("If I guess too low, respond with a L.\n");
 printf("If I guess too high, respond with a H.\n");
 printf("If I guess correctly, respond with a Y.\n");

high = 100;
low = 1;

while(response != 'Y')
{
guess = (high + low) / 2;

printf("Okay, let's start. Is it %d?\n", &guess);
printf("Please respond with L, H, or Y.\n");
scanf("%d", &response);
response = toupper(response);

switch(response)
{
    case 72: high = guess - 1;
            break;
    case 76: low = guess + 1;
            break;
    case 89: printf("Yes! I knew I could do it.\n");
          break;
    default:  printf("I didn't get that; you gave an invalid response.\n");
              printf("Please try again.\n");
}

}
return 0;
}


texts: Rename and move images to a destination directory based on a text file followup

texts:
This is my third (and hopefully final) time re-writing this program. It was recommended I use Pathlib and it simplified my code, it's easier to read and understand than the first two monstrosities.

I also changed the way it functions, instead of the user providing a text file, the user creates a directory called Repository, which contains sub directories of images that will be renamed, and a destination directory (R:\Pictures for me).

Suppose I have the following directories under Repository:

C:\Users\Kiska\Repository\Computers
   - comp-amd-12342.jpg
   - 7546345233-pcmag.jpg

C:\Users\Kiska\Repository\Landscape
   - land-345345.jpg
   - end-field.jpg

The program will move and rename it like this:

R:\Pictures\Pictures\Computers
   - computers_1.jpg
   - computers_2.jpg

R:\Pictures\Pictures\Landscape
   - landscape_1.jpg
   - landscape_2.jpg

Code:

import os
from pathlib import Path
import shutil

def check_if_folder_exists(folder : Path):
    if not Path.exists(folder):
        raise FileNotFoundError("{0} is not available".format(folder))

def main():

    try:

        repository = Path("{0}\\{1}".format(os.getenv("USERPROFILE"), "Repository"))
        desination_root = Path("R:\\Pictures")

        check_if_folder_exists(folder=repository)
        check_if_folder_exists(folder=desination_root)

        for folder in repository.iterdir():
            destination = Path(desination_root).joinpath(folder.stem)
            Path.mkdir(destination, exist_ok=True)

            start = len(os.listdir(destination)) + 1

            for number, image in enumerate(folder.iterdir(), start=start):
                image_name = "{0}_{1}{2}".format(folder.stem.lower().replace(" ","_"), number,image.suffix)
                destination_image = Path(destination).joinpath(image_name)
                print(f"{image} will be named {destination_image}")
                shutil.move(image, destination_image)

    except(ValueError, FileNotFoundError, OSError) as error:
        print(error)
    finally:
        pass

if __name__ == '__main__':
    main()


texts: Euclidean algorithm to determine GCD (greatest common divisor) in C -- alternative method

texts:
Been looking into some simple algorithms, I came up with the following piece of code in C to implement the Euclidean algorithm iteratively (I like to be clear here, I don't want the recursive implementation for now).
I've seen various other implementations and in fact most books prefer a different pseudo code.
I'm wondering if the following implementation is any better or worse?
#include <stdlib.h>

void swap_numbers(void *a, void *b)
{
  int temp = *(int *)a;
  *(int *)a = *(int *)b;
  *(int *)b = temp;
}

unsigned euklid_iterative(unsigned a, unsigned b)
{
  while ((a = a % b))
    swap_numbers(&a, &b);
  return b;
}


texts: Replace HTML input file element with custom styled button

texts:
I've been working on a solution to replace the HTML input file element with a custom styled button.

jsFiddle: https://jsfiddle.net/Lau1989/4jLz04pc/5/

First route the click event to the actual file input

//route click event on styled button to the actual file input
button.addEventListener('click', function() {
    input.click();
}, false);

Then replace the full/fake path of the file to display only the file name and its extension

//display the name of the selected file
input.addEventListener('change', function() {
    console.log('val', input.value);
    //Remove the full/fake path to display only the file name
    var file_name = input.value.replace(/[A-Za-z]:\\fakepath\\/i, '');
    output.innerText = file_name;
}, false);

Although this code works so far on all tested browsers, I have no idea if it really should be used in production in terms of security or cross-browser compatibility.

Is there any downside to this approach I don't see yet ? If so, what would be a better approach to do this ?


texts: OOP design for multiple user authentication

texts:
I'm learning OOPs design principles and design patterns. As an exercise, I came up with this model for multiple user authentication using OOPs. I plan to build this on top of a Flask server, but I've just mocked the behavior for now.

Please let me know your thoughts about the implementation design. Thanks in advance.

  User Model:

class User:
    def __init__(self, name: str = None, ph_no: str = None, username: str = None, password: str = None):
        self.username = username
        self.password = Utils.encrypt(password)
        self.ph_no = ph_no
        self.name = name

        Utils.persist_in_db(self)

    def update_password(self, old_password: str, new_password: str):
        if Utils.encrypt(old_password) == self.password:
            self.password = Utils.encrypt(new_password)
        else:
            raise PasswordNotCorrectException()

    def authenticate(self, password) -> bool:
        return self.password == Utils.encrypt(password)

    def __repr__(self):
        return f'<User: {OrderedDict(self.__dict__)}>'

  Core logic:

import threading
import time
from login_service import LoginService
from models.user import User

class BMSApp:
    def __init__(self):
        self.mock()

    @staticmethod
    def mock():
        user1 = UserThread(name='Rick',
                             username='ricky',
                             ph_no='xxxxx',
                             password='password1234')

        user2 = UserThread(name='Morty',
                             username='morty',
                             ph_no='xxxx',
                             password='lifeisawesome')

        user1.start()
        user2.start()

        user1.join()
        user2.join()

class UserThread(threading.Thread):
    def __init__(self, **kwargs):
        super().__init__()
        self.kwargs = kwargs

    def run(self) -> None:
        BookingStrategy.execute(**self.kwargs)

class BookingStrategy:
    @staticmethod
    def execute(**kwargs):
        login_result = LoginService.login(**kwargs)
        if login_result[0]:
            print(f"Login succeeded for user {login_result[1]}")
        else:
            print(f"Login failed for user {login_result[1]}")

  Mock Login service:

class LoginService:
    @staticmethod
    def login(**kwargs):
        #         TODO: implement proper login functionality
        user = User(**kwargs)
        return random.choice([(True, user), (False, user)])


texts: Python script to calculate the Collatz conjecture

texts:
Here is the code.

# Collatz.py - The Collatz conjecture
initiate = True
while True:
    if initiate == True:
        initiate = False
        try:
            number = float(input('Enter a number: '))
        except:
            print('Error! Please try again.')
            number = 1
    if number % 2 == 0:
        number /= 2
    elif number == 1:
        if input('Quit? (y/n)') == 'y':
            break
        else:
            initiate = True
    else:
        number *= 3
        number += 1
    print(number,end='\n----\n')


texts: Initialising numerical properties from a text-based properties file

texts:
This is a Spring Framework-based datasource instantiator which reads its properties from the Spring Framework context, i.e. the values are initially all String from properties files and numbers have to be tested for presence and validity.

Normally it would be totally superfluous in Spring Framework because the purpose of Spring Framework is to allow Java developers to by-pass it all. However sometimes as in this case, something is different and it has to be done manually.

My main concern with this method is the repeated use of the couldBe variable which is an attempt to make it more readable.

couldBe is the possibly hopefully valid number retrieved from the properties file, which could in fact be invalid.

This is all that is in the class:

private final Pattern testForInt =
    Pattern.compile(GeneralUtils.REGEX_TEST_FOR_INT);

@Bean
@ConfigurationProperties(prefix = "tardis.datasource")
public Map<String, String> dataSourceProperties() {
    // Spring populates the map with properties prefixed as above
    return new HashMap<>();
}

@Bean
public DataSource dataSource() {
    Map<String, String> props = dataSourceProperties();
    HikariConfig dataSourceConfig = new HikariConfig();
    dataSourceConfig.setDriverClassName(props.get("driver"));
    dataSourceConfig.setUsername(props.get("username"));
    dataSourceConfig.setPassword(props.get("password"));
    dataSourceConfig.setJdbcUrl(props.get("url"));
    String couldBe = props.get("maximumPoolSize");
    if (couldBe != null && testForInt.matcher(couldBe).find()) {
        dataSourceConfig.setMaximumPoolSize(Integer.valueOf(couldBe));
    }
    couldBe = props.get("maxLifeTime");
    if (couldBe != null && testForInt.matcher(couldBe).find()) {
        dataSourceConfig.setMaxLifetime(Long.valueOf(couldBe));
    }
    couldBe = props.get("leakDetectionThreshold");
    if (couldBe != null && testForInt.matcher(couldBe).find()) {
        dataSourceConfig.setLeakDetectionThreshold(Long.valueOf(couldBe));
    }
    couldBe = props.get("connectionTimeout");
    if (couldBe != null && testForInt.matcher(couldBe).find()) {
        dataSourceConfig.setConnectionTimeout(Long.valueOf(couldBe));
    }
    return new HikariDataSource(dataSourceConfig);
}


texts:
I have just started learning functional programming (Haskell) for fun after using imperative languages my whole life. I am looking for quick and simple tips from pros on how the particular code I just wrote (a simple program solving a simple task - factoring an integer) can be simplified and made more beautiful.

-- FactorInt: Factoring n to prime integers

import Data.Maybe

-- Takes the head maybe
headMaybe :: [t] -> Maybe t
headMaybe [] = Nothing
headMaybe (x:_) = Just x

-- Takes the first available divizor
takeDivizor :: Int -> Maybe Int
takeDivizor n = headMaybe $ filter (\i -> n `mod` i == 0) $ takeWhile (\i -> i^2 <= n) [2..]

-- Takes the maximum power of k in n
maxPower :: Int -> Int -> Int
maxPower n k
    | (n `mod` k) /= 0   = 0
    | otherwise          = 1 + maxPower (n `div` k) k

-- Factors an integer to a list of divizors
factorInt :: Int -> [(Int, Int)]
factorInt 1 = []
factorInt n = case (takeDivizor n) of
    Nothing -> [(n, 1)]
    Just a  -> (a, k) : factorInt (n `div` a^k) where k = maxPower n a

-- Pretty printing powers
prettyPowers :: (Int, Int) -> String
prettyPowers (a, 1) = show a
prettyPowers (a, b) = (show a) ++ "^" ++ (show b)

-- Pretty printing factors
prettyFactors :: [(Int, Int)] -> String
prettyFactors factors = foldl1 (\ a b -> a ++ "*" ++ b) $ map prettyPowers factors

-- Program
main = do
    nStr <- getLine
    let n = read nStr :: Int
    putStrLn $ prettyFactors $ factorInt n


texts:
I'm working on a CMS, currently on being able to create static pages, manage menus etc.
so.. I have This function that reads from the DB and finds all the static pages, and their position in the menu.
I want to know what Do you think.

function update_menu(&$pdo, $filepath){
$qry = "SELECT * FROM pages WHERE top = 1";
$exec = $pdo->query($qry);
$string = "
";
while($row=$exec->fetch(PDO::FETCH_ASSOC)){
    $string.= "
".$row['title']."";
        $qry = "SELECT * FROM pages WHERE parent = ?";
        $child_ex = $pdo->prepare($qry);
        $child_ex->bindValue(1, $row['id'], PDO::PARAM_INT);
        if($child_ex->execute()){
            $i=0;
            while($child=$child_ex->fetch(PDO::FETCH_ASSOC)){
                if($i==0){
                    $string.="
";
                }
                $string.="
".$child['title']."";
                $i++;
            }
            if($i != 0)
                $string.="
";
        }
    $string.="
";
}
$string.="
";
file_put_contents($filepath, $string);

};

Output html:

Page1

append1
append2

page2

append1b

page3


texts:
I want to find the lowest hop count from source to destination.
The challenge, in summary:

  The first line contains the number of test cases T, 1 ≤ T ≤ 100000.
  The next T lines each contains three integers A, B, and M.  1 ≤ A ≤ B ≤ 1012.  1 ≤ M ≤ 1012.

  For each test case, print the number of multiples of M that are in the range [A, B] (inclusive).

My output is correct but the execution time of my program is like 1.0015 seconds when given 100000 entries. But I need to do the program within 1 second time frame. I have tried a lot to reduce the execution time but couldn't. Can anybody help me to achieve an execution time within 1 sec.

#include<stdio.h>
int main()
{
    unsigned int n, i, j, k, h,count=0,l=0;
    scanf("%u", &n);
    for (i=0;i<n;i++)
    {
        scanf("%u %u %u", &j, &k, &h);
        l=j;
        count = 0;
        while(l<=k)
        {
          if(l%h==0)
          {
            count=count+1;
          }
          l++;
        }
        printf("%u\n", count);
    }
    return 0;
}

sample input-> 1 10 2

sample output-> 5


texts:
I'm trying to make a login system for my website which I'll be releasing in public later on. I have inserted some main samples of my code in here and I would like some useful advise or suggestions. Also if I'm doing anything unsafe or anything which may cause problems in future please let me know. Thanks

login.inc.php:

<?php
    error_reporting(0);
    $error_message = "Website ran into an error";
    session_start();
    if (isset($_SESSION['user_id'])) {
        exit();
    }
    $parameters = json_decode(file_get_contents('php://input'), true);

    if (isset($parameters["inserted_id"]) && isset($parameters["inserted_password"])) {
        // FOR TEST USE I'M USING xampp server, localhost
        $connection = mysqli_connect("localhost", "root", "", "users") or die($error_message);
        $inserted_id = $parameters['inserted_id'];
        $inserted_password = $parameters['inserted_password'];

        $statement = mysqli_stmt_init($connection) or die($error_message);
        if (mysqli_stmt_prepare($statement, "SELECT id, account_name, password FROM user WHERE account_name=? OR email=?;")) {
            mysqli_stmt_bind_param($statement, "ss", $inserted_id, $inserted_id);
            mysqli_stmt_execute($statement) or die($error_message);
            if (($row = mysqli_fetch_assoc(mysqli_stmt_get_result($statement))) == null) {
                echo("No records found with inserted inputs");
                mysqli_stmt_close($statement);
                mysqli_close($connection);
                exit();
            } else {
                if (password_verify($inserted_password, $row['password'])) {
                    $_SESSION['user_id'] = $row['id'];
                    $_SESSION['account_name'] = $row['account_name'];
                    echo("pass");
                } else {
                    echo("Wrong password");
                }
                mysqli_stmt_close($statement);
                mysqli_close($connection);
                exit();
            }
        }
        mysqli_close($connection);
        exit();
    }
?>

login.js:

var request_sent = false;
document.querySelector("button").onclick = function () {
  if (!request_sent) {
    var inserted_id = document.getElementById("inserted_id").value;
    var inserted_password = document.getElementById("inserted_password").value;
    if (inserted_id == "" || inserted_password == "") {
      alert("Both fields need to be filed out");
    } else {
      request_sent = true;
      http_request("login.inc.php", JSON.stringify({"inserted_id":inserted_id, "inserted_password":inserted_password}));
        }
    }
}

function http_request(url, params) {
  $.ajax({
    type: "POST",
    url: url,
    data: params,
    success: function(data) {
      if (data == "pass") {
          window.open("../website", "_self", "", false);
      } else {
          alert(data);
      }
      request_sent = false;
    }
  });
}

login.html:

<html>
<head>
  <title></title>
</head>
<body>
  <input id="inserted_id" type="text" placeholder="Account Name/e-mail"/>
  <input id="inserted_password" type="password" placeholder="Password"/>
  <button>SUBMIT</button>
  <script src="login.js"></script>
</body>
</html>


texts: Producing all allocations by n items from a list

texts:
I have strong feeling that the code below is ugly at least as there are 2 same "cons".
I would appreciate if you advise me ways to improve it.

The code produces all allocation by n items from list lst.

(defun allocations (lst n)
  (if (= n 1)
      (loop for i in lst
       collect (cons i nil))
      (loop for i in lst
   append (mapcar #'(lambda (l) (cons i l))
                      (allocations (remove i lst) (- n 1))))))


texts:
Today I just completed a personal POST function that emulates jQuery's using $.ajax, but also implementing a possible redirect. I just finished up and it looks like it is functional, but since this is something I want to keep long term and integrate in many projects, I want to make sure it is as functional as possible.

function postR(url, params, redir = false, callback = null) {
    if(redir){
        var form = document.createElement('form');
        form.method = 'post';
        form.action = url;
        for (var key in params) {
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = key;
            input.value = params[key];
            form.appendChild(input);
        }
        document.body.appendChild(form);
        form.submit();
    }else{
        if(callback && typeof(callback) === "function"){
            $.ajax({
                type: "POST",
                url: url,
                data: params,
                success: function(data){
                    callback(data)
                }
            });
        }else{
            $.ajax({
                type: "POST",
                url: url,
                data: params
            });
        }
    }
}

The purpose for building this was because I wanted to use jQuery's post function to do some JS work with a form before it was submitted, but also wanted to redirect alongside the POST request, like a natural form.


texts: Defining an OOP structure for a Student class in NodeJS

texts:
Most of my coding experience is in C#. The way object oriented programming is laid out in C# is a bit different from NodeJS, hence this is my first NodeJS OOP for a Student class.

I'm trying to translate this C# structure of creating a class, object and methods to NodeJS:

class Student
    {
        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private string _id;

        public string ID
        {
            get { return _id; }
            set { _id = value; }
        }
   }

Sample usage:

Student student = new Student();
student.Age = 12;
student.Name= "Tolani";
student.ID = "Pokemon1234";

NodeJS code:

// Constructor
   function Student(name, age, id)
    {
        // always initialize all instance properties
        this.name = name;
        this.age = age;
        this.id = id;
    }
    // Get the student Name
    Student.prototype.getStudentName = function()
    {
        return this.name;
    };

    // Gets the student Age
    Student.prototype.getStudentAge = function()
    {
        return this.age;
    };

    // Gets the student's ID
    Student.prototype.getStudentId = function()
    {
        return this.id;
    };
    // export the class
    module.exports = Student;
    var student = new Student('Tolani', 23, 'ddr1234');
    console.log('The student name is ' + student.getStudentName());

In general, can this be improved?


texts:
Since I am new to Java, I wanted to see if there were better ways of answering the same question. Are parts of my code redundant or maybe there's an easier way to get the same result?

Problem J4: Big Bang Secrets

The encoding algorithm is a Caesar cipher with a shift (\$S\$) that depends on a parameter (\$K\$) and its position in the word (\$P\$, where \$P = 1\$ for the first letter of each word): \$S = 3\$, \$P + K\$.  For example, when \$K = 3\$, ZOOM is encoded as FXAB:

\$S_1 = 3 \cdot 1 + 3 = 6\$, so Z \$\rightarrow\$ F
\$S_2 = 3 \cdot 2 + 3 = 9\$, so O \$\rightarrow\$ X
\$S_3 = 3 \cdot 3 + 3 = 12\$, so O \$\rightarrow\$ A
\$S_4 = 3 \cdot 4 + 3 = 15\$, so M \$\rightarrow\$ B

The challenge is to write a decoder. The first line of input contains \$K\$ (\$K \lt 10\$).  The second line contains the encoded message, containing up to 20 characters in uppercase.

public class Decoder {

public static void main(String[] args) {
    try {

        BufferedReader in = new BufferedReader(new InputStreamReader(
                System.in));
        int k = Integer.parseInt(in.readLine());
        String word = in.readLine();

        char[] cArray = word.toCharArray();

        for (int i = 0; i < word.length(); i++) {

            char out = (char) ((cArray[i]) - (((3 * (i + 1)) + k) % ('Z' - 'A')));

            if (out < 'A') {
                char wrap = (char) (('Z' + 1) - ('A' - out));
                System.out.print(wrap);
            } else {

                System.out.print(out);
            }
        }

    } catch (IOException e) {

        System.out.println("Error");

    }
}
}


texts: How to handle multiple return statements

texts:
I am trying to restructure a function more clearly and readable that has multiple return statements.
Usecase
Get a token:

if the token does not exist in the database then generate a new one and return it.
if the token exists  -check if expired, if expired update it with a new one,   -if not expired then return the same token.

Code
 export const GetToken = async () => {

        const db = new DB();

        const check = await db.GetItem();

        if(check.Count === 0) {
            const token = await GenerateToken();
            return token;
        }

        if(check.Count >= 1) {

            const db_token = check.Items[0];
            const isExpired = isTokenExpired(db_token);

            if(isExpired) {
                const token = await UpdateToken(db_token);
                return token;
            }
            return db_token;
        }
    }

There are 3 return statements in this function and there is not a base return function.


texts: Throwing exception in the singleton pattern in C#

texts:
I'm implementing an HTTP client shell that's going to be used for the lifetime of my application in C#.  It needs to be initialized before the instance can be accessed.  It looks something like this:

public static class AssetSyncServiceClient {
    private static object _lock = new object();
    private static bool _initialized = false;
    private static HttpClient _client = null;

    /// <summary>
    /// Indicates whether the client has been initialized.
    /// </summary>
    /// <returns>Whether the client is initialized.</returns>
    public static bool IsInitialized() {
        lock (_lock) {
            return _initialized;
        }
    }

    /// <summary>
    /// Creates and configures HTTP client.
    /// </summary>
    public static void Initialize(string baseUrl, bool onlyRequestJson = true) {
        lock (_lock) {
            if (_initialized) { throw new Exception("Client has already been initialized."); }

            _client = new HttpClient();
            _client.BaseAddress = new Uri(baseUrl);

            if (onlyRequestJson) {
                _client.DefaultRequestHeaders.Accept.Clear();
                _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }

            _initialized = true;
        }
    }

    /// <summary>
    /// Closes / disposes of the HTTP client.
    /// </summary>
    public static void Close() {
        lock (_lock) {
            if (_initialized && _client != null) {
                _client.Dispose();
            }
        }
    }

    /// <summary>
    /// Gets client instance.
    /// </summary>
    public static HttpClient Instance {
        get {
            lock (_lock) {
                if (!_initialized) { throw new Exception("HTTP client has not been initialized."); }
                return _client;
            }
        }
    }
}

The trouble is, this throws up a warning in Visual Studio because of style rule CA1065 - Microsoft say you shouldn't throw an exception in a property.  I just don't agree with this - it seems fine to me.  If you try to access .Instance before it's initialized you get an exception.  It's clearly a property whose code could throw an exception, and not a "dumb field".  I could turn Instance into a GetInstance method but I just prefer the look of accessing it from calling code as a property.

So does it make sense to just suppress the warning here, or am I designing this badly?  Is there a better way?  Should I bite the bullet and make Instance a method?

UPDATE:
It looks like I probably want something other than a singleton because singletons are hard to test (although actually MS Fakes can mock static methods so maybe it's OK), so what would be a better design pattern for this functionality that's unit testable?


texts:
On Codewars, there is a challenge where the goal is to justify an str into a certain len. Here are the rules:

  Use spaces to fill in the gaps between words.
  Each line should contain as many words as possible.
  Use '\n' to separate lines.
  Gap between words can't differ by more than one space.
  Lines should end with a word not a space.
  '\n' is not included in the length of a line.
  Large gaps go first, then smaller ones    ('Lorem--ipsum--dolor--sit-amet,' (2, 2, 2, 1 spaces)).
  Last line should not be justified, use only one space between words.
  Last line should not contain '\n'
  Strings with one word do not need gaps ('somelongword\n').

I have managed justify text correctly but there a few flaws that I am stumped on: a word that are too long for a length, and short length that causes nothing to happen. I would appreciate any possible solutions, feedback, advice, other flaws, etc. I am a beginner in JavaScript so code may seem messy.

function justify(str, len) {
   let splitStr = [];

   for (let i = 0; i < str.split(' ').length; i++) {
       if (str.split(' ')[i].length) {
           splitStr.push(str.split(' ')[i])
       }
   }

   let lines = [];
   let justified = [];

   while (true) {
       let line = [];
       let currentLine = true;

       while (currentLine) {
           if ((line.join(' ') + splitStr[0]).length < len) {
               line.push(splitStr.shift());

               if (splitStr.length === 0) {
                   break;
               }
           } else {
               break;
           }
       }

       lines.push(line.join(' '));

       if (splitStr.length === 0) {
           break;
       }
   }

   for (let i = 0; i < lines.length; i++) {
       line = lines[i].split('');

       if (line.length < len && i !== lines.length-1) {
           let neededSpaces = len - line.length;
           let spaces = [];

           for (let j = 0; j < line.length; j++) {
               if (line[j] === ' ') {
                   spaces.push(line[j]);
               }
           }

           while (neededSpaces > 0) {
               for (let k = 0; k < spaces.length; k++) {
                   spaces[k] = spaces[k] + ' ';
                   neededSpaces--;

                   if (neededSpaces === 0) {
                       break
                   }
               }
           }

           for (let j = 0; j < line.length; j++) {
               if (line[j] === ' ') {
                   line[j] = spaces.shift();
               }
           }

           justified.push(line.join(''));
        }
   }

   return justified.join('\n');
}
console.log(justify('Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making ' +
'it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, '+
'from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections ' +
'1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ' +
'ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard \n\
\chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero \n\
are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.', 30)


texts: Call center dispatch using object-oriented Python

texts:
I am looking for tips on improving my implementation of an OOP design problem in Python3

Here is the problem (paraphrasing to save space):

There is a call center with three levels of employees - Respondent, Manager and Director.
A call that goes to the center propagates as Respondent -> Manager -> Director depending on whether or not

a) The respondent is free and can handle the call

b) The manager is free and can handle the call

The call center needs to have a dispatchCall() method that assigns the call to the first available employee

Here is the code

#! /usr/bin/env python3
from abc import ABCMeta, abstractmethod
from random import random

class CallCenter():
    """
    A call center class that will be inherited from by the director

    Attributes:
        name: Name of the employee
        number: Mobile phone number of the employee
        level: Define level of the employee - respondent, manager or director
    """
    __metaclass__ = ABCMeta

    def __init__(self, name, number, level):
        self.name = name
        self.number = number
        self.level = level

    def canEmployeeHandle(self):
        canHandle = random()
        if canHandle > 0.5:
            return True
        else:
            return False

    def isEmployeeBusy(self):
        busy = True if random() <= 0.5 else False
        return busy

    @staticmethod
    def dispatchCall():
        return respondent.answerCall()

    @abstractmethod
    def answerCall(self):
        """Print a string indicating that this employee is currently
        answering the call or propogate up the chain"""
        pass

class Director(CallCenter):
    """
    A class definition for the director who will be the third in chain
    to answer the call
    """
    def answerCall(self):
        print("The director is now on call with you")

class Manager(Director):
    """
    A class definition for the manager who will be the second in chain to
    answer the call
    """
    def answerCall(self):
        if not self.isEmployeeBusy() and self.canEmployeeHandle():
            print("The manager is answering your call")
        else:
            super(Manager, self).answerCall()

class Respondent(Manager):
    canHandle = random() #class variable to check if respondent can handle call
    """
    A class definition for the respondent who will be the first in chain
    to answer the call
    """
    def answerCall(self):
        if not self.isEmployeeBusy() and self.canEmployeeHandle():
            print("The respondent is answering your call")
        else:
            super(Respondent, self).answerCall()

if __name__ == "__main__":
    director = Director("Alex", "+17654736791", "director")
    manager = Manager("Unai", "+331577285782", "manager")
    respondent = Respondent("Mark", "+16574872817", "respondent")

    CallCenter.dispatchCall()


texts: Banking application - Optimizing java multi-threading code

texts:
I created a simple Bank application to make multiple transactions between multiple accounts. It is working as expected. But I want to know can I make the code more optimized.

public class BankingApplication {
    public static void main(String[] args) throws  Exception{
        ExecutorService service = Executors.newFixedThreadPool(100);
        Bank bankObj = new Bank();
        for(int i =0; i <= 10000; i++){
            service.submit(bankObj);
        }
        service.shutdown();
        service.awaitTermination(1, TimeUnit.DAYS);
        bankObj.getTotalBalanceWithStats();
    }
}
class Account{
    String accountName;
    int balance;
    Object lock1 = new Object();
    Object lock2 = new Object();
    Object lock3 = new Object();
    Account(String name, int balance){
        this.accountName = name;
        this.balance = balance;
    }
    void deposit(int amount){
        synchronized (lock1) {
            this.balance = getBalance() + amount;
        }
    }
    void withdraw(int amount) throws Exception {
        synchronized (lock2) {
            int balance = getBalance() - amount;
            if(balance <= 0){
                throw new Exception("Invalid Transaction");
            }
            this.balance = getBalance() - amount;
        }
    }
    int getBalance(){
        synchronized (lock3){
            return this.balance;
        }
    }
}
class Bank implements Runnable{

    List<Account> accountList = new ArrayList<>();
    Bank(){
        for(int i=0; i <= 30; i++){
            accountList.add(new Account("A"+i, 1000));
        }
        getTotalBalanceWithStats();
    }

    public void run() {
        Random random = new Random();
        Account from = null;
        Account to = null;
        while(true) {
            int a1 = random.nextInt(30);
            int a2 = random.nextInt(30);
            if(a1 == a2) continue;
            from = accountList.get(a1);
            to = accountList.get(a2);
            break;
        }
        doTransaction(from, to, random.nextInt(400));
    }

    private void doTransaction(Account from, Account to, int nextInt) {
        System.out.println("Transaction from " + from.accountName + " to " + to.accountName);
        try {
            from.withdraw(nextInt);
            to.deposit(nextInt);
        } catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    void getTotalBalanceWithStats(){
        int total = 0;
        for(Account acc : accountList){
            System.out.println("Account " + acc.accountName + " balance " + acc.getBalance());
            total += acc.getBalance();
        }
        System.out.println("Total Balance " + total);
    }
}

As per my knowledge I feel deposit(), withdrawal() and getBalanace() API are independent of each other so creating different mutex for each process.

Some scenarios which I am trying to test

What I am trying to achieve is when Account1 is trying to send money to Account2 at the same time Account3 can also send money to Account2 or vice versa.

When Account1 is sending money to Account2 at same time Account2 can also send money to Account1.

When Account1 is sending money to Account2 and at same time Account3 is sending money to Account1. withdraw() method of Account1 should not block deposit().


texts:
I'm trying to implement my own API. This code excerpt should show the basic working routines. The storage is temporary an in-memory-array and the only HTTP method for now is POST.

I outsourced the parsing into ParseRecordRequest(), because I use the code twice for POST and PUT requests and will extend it with further conditions.

All responses (errors and records) are generated by GenerateJSON(), which allows me to customize the response header etc. within a single place.

But what should I do, if GenerateJSON() can't marhsal the JSON? All usual errors are sent back with an HandlerError struct, that can't be marshalled in this case.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

type Record struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

var DB []Record
var latestID int = 0

type HandlerError struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
}

func CreateRecord(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
    payload, err := ParseRecordRequest(w, r)

    if err != nil {
        GenerateResponse(w, err)
        return
    }

    latestID++
    record := Record{latestID, payload.Name}
    DB = append(DB, record)
    GenerateResponse(w, record)
}

func ParseRecordRequest(w http.ResponseWriter, r *http.Request) (*Record, *HandlerError) {
    data := new(Record)
    err := json.NewDecoder(r.Body).Decode(data)

    if err != nil {
        return nil, &HandlerError{http.StatusInternalServerError, "Can't decode the JSON."}
    }

    if data.Name == "" {
        return nil, &HandlerError{http.StatusBadRequest, "Invalid record name."}
    }

    return data, nil
}

func GenerateResponse(w http.ResponseWriter, data interface{}) {
    payload, err := json.MarshalIndent(data, "", "    ")

    if err != nil {
        // How should the error be handeled?
        // Sending an ErrorHandler is impossible,
        // because the Marshaler doesn't work
    }

    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.Header().Set("Accept", "application/json")
    w.Write(payload)
}

func main() {
    router := httprouter.New()
    router.POST("/api/record", CreateRecord)

    fmt.Println("Server is running...")
    http.ListenAndServe(":8080", router)
}


texts: Time Limit Exceeded for CodeChef Easy problem - STRQ (Chef and Strings)

texts:
I was working through a codechef easy problem here.

I've got to a solution, but it only passes the Subtask #1. For the other two subtasks, it shows TLE (Time Limit Exceeded - which is 1 second).

package com.codechef.solutions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.StringTokenizer;

public class ChefAndStrings {

  private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  private static StringTokenizer tokenizer;

  private static String specialString = "";
  private static int numberOfQueries = 0;

  public static void main(String[] args) {
    PrintStream out = System.out;
    try {
      specialString = br.readLine();
      numberOfQueries = Integer.parseInt(br.readLine());

      for (int i = 0; i < numberOfQueries; i++) {
        String nextQuery = nextQuery();
        out.println(getGoodStringCounts(nextQuery));
      }
    } catch (IOException ex) {
      out.println("Exception occurred while reading input");
    }
  }

  private static String nextQuery() throws IOException {
    return br.readLine();
  }

  private static int getGoodStringCounts(String query) {
    tokenizer = new StringTokenizer(query, " ");
    char startLetter = tokenizer.nextToken().charAt(0);
    char endLetter = tokenizer.nextToken().charAt(0);
    int startIndex = Integer.parseInt(tokenizer.nextToken()) - 1;
    int endIndex = Integer.parseInt(tokenizer.nextToken()) - 1;

    int[] startLetterIndices = allIndicesGreaterThanMin(startLetter, startIndex);
    int[] endLetterIndices = allIndicesLessThanMax(endLetter, endIndex);

    int total = 0;
    int beginEndIndexFrom = 0;

    for (int i = 0; i < startLetterIndices.length; i++) {
      int index = startLetterIndices[i];
      for (int j = beginEndIndexFrom; j < endLetterIndices.length; j++) {
        if (endLetterIndices[j] > index) {
          beginEndIndexFrom = j;
          total += (endLetterIndices.length - beginEndIndexFrom);
          break;
        }
      }
    }

    return total;
  }

  private static int[] allIndicesGreaterThanMin(char letter, int startIndex) {
    int[] indices = new int[specialString.length() / 2];
    int currentIndex = 0;
    int index = specialString.indexOf(letter, startIndex);
    while (index != -1) {
      indices[currentIndex++] = index;
      startIndex = index + 1;
      index = specialString.indexOf(letter, startIndex);
    }
    int[] result = new int[currentIndex];
    System.arraycopy(indices, 0, result, 0, result.length);
    return result;
  }

  private static int[] allIndicesLessThanMax(char letter, int endIndex) {
    int[] indices = new int[specialString.length() / 2];
    int currentIndex = 0;
    int index = specialString.indexOf(letter);
    while (index != -1 && index <= endIndex) {
      indices[currentIndex++] = index;
      index = specialString.indexOf(letter, index + 1);
    }
    int[] result = new int[currentIndex];
    System.arraycopy(indices, 0, result, 0, result.length);
    return result;
  }
}

Initially I used List<Integer> to store the indices, but then moved to int[], after I got the error first time. Still it isn't accepting. Can you see some possible optimization there?