texts:
I keep having to write state machines that depend on time for various experiments I run and I'd like to know how to write them better. This state machine is for training a neural network by feeding in keys and expected values.

import numpy as np

dt = 0.001
period = 0.1

class SimpleEnv(object):

    def __init__(self, keys, values, env_period=0.1):
        self.keys = keys
        self.values = values
        self.env_idx = np.arange(len(keys))

        self.idx = 0
        self.shuffled = False

        self.i_every = int(round(env_period/dt))
        if self.i_every != env_period/dt:
            raise ValueError("dt (%s) does not divide period (%s)" % (dt, period))

    def get_key(self):
        return self.keys[self.idx]

    def get_val(self):
        return self.values[self.idx]

    def step(self, t):
        i = int(round((t - dt)/dt))  # t starts at dt
        ix = (i/self.i_every) % len(self.keys)
        if ix == 0 and not self.shuffled:
            print("shuffling")
            np.random.shuffle(self.env_idx)
            self.shuffled = True
        elif ix == 1:
            self.shuffled = False
        self.idx = self.env_idx[ix]

        return ix

# note the toy keys and values for testing purposes
s_env = SimpleEnv(np.arange(4), np.arange(1, 5), env_period=period)
key = -1
val = -1
ix = -1
# iterate through keys and values twice
run_time = 4 * period * 2

# the event loop
# starts at dt because of reasons
for t in np.arange(dt, run_time, dt):

    last_ix = ix
    ix = s_env.step(t)
    key = s_env.get_key()
    val = s_env.get_val()
    assert key + 1 == val

    if last_ix != ix:
        print("Key: %s, Value: %s" %(key, val))

The results should look something like:

shuffling
Key: 2, Value: 3
Key: 0, Value: 1
Key: 3, Value: 4
Key: 1, Value: 2
shuffling
Key: 2, Value: 3
Key: 1, Value: 2
Key: 3, Value: 4
Key: 0, Value: 1

How can I write this better or more efficiently? Is there a state machine library in Python that would stop me from having to rewrite variations of this class all the time?


texts: Automated Teller Machine (ATM) implementation in Java

texts:
I am trying to improve my Java skill, so I wrote a simple ATM program.
I would like a review, to help me make the code more effective.
Main
public static void main(String[] args) {
    ATM a = new ATM("A", "S", 20000);
    Scanner in = new Scanner(System.in);
    while(true){
        System.out.println("Please choose: " + "\n" +
                "1. Deposit" + "\n" + "2. Withdraw" + "\n" + "3. Info" + "\n" + "4. Exit");
        int option = in.nextInt();
        switch (option) {
            case 1:
                System.out.println("How much would you like to Deposit?");
                double depositValue = in.nextDouble();
                a.deposit(depositValue);
                System.out.println("Your current balance is : " + a.getBalance() + "\n") ;
                break;

            case 2:
                System.out.println("How much would you like to Withdraw?");
                double withdrawValue = in.nextDouble();
                a.withdraw(withdrawValue);
                break;

            case 3:
                System.out.println(a.toString() + "\n" );
                break;

            case 4:
           System.exit(0);

        }
    }

}

ATM
private String name;
private String lastName;
private double balance;

public ATM(String name, String lastName, double balance) {
    this.balance = balance;
    this.lastName = lastName;
    this.name = name;
}

public String getName(){
    return this.name;
}

public String getLastName(){
    return this.lastName;
}

public double getBalance(){
    return this.balance;
}

public void setBalance(int newValue){
    this.balance = newValue;
}

public void deposit(double value){
    balance += value;
}

public void withdraw(double value){
    if(value > balance){
        System.out.println("You can't withdraw that amount of money." +"\n"+ "Your balance is: " + getBalance() + "\n");
    } else {
        balance -= value;
        System.out.println("You withdraw " + value +"from your account!" + "\n");
    }
}
public String toString(){
    return "First name: " + getName() +"\n" + "Last name: " + getLastName() + "\n" + "Your balance: " +getBalance();
}


texts:
I have a view that looks like this:

@transaction.commit_on_success
def view(request):
    do_stuff(...)
    if condition(...):
        result = do_other_stuff(...)
        transaction.commit()
        send_email(result)
    return HttpResponse(...)

Assume everything with (...) can touch the database.

There are currently two main cases:

condition is true, do_stuff() and do_other_stuff() are done in transaction 1, the transaction is saved, then the e-mail is sent and HttpResponse is done in transaction 2
condition is false, everything happens in transaction 2

I want to rewrite this with transaction.atomic. The important requirement is: the e-mail should only be sent if do_other_stuff() really gets saved.

Obviously I can't use @atomic around the whole view, because I wouldn't be able to commit, so my first shot looks something like:

def view(request):
    should_send_email = False
    with transaction.atomic:
        do_stuff(...)
        if condition(...):
            result = do_other_stuff(...)
            should_send_email = True
        response = HttpResponse(...)
    if should_send_email:
        should_send_email(result)
    return response

It's kind of acceptable, but it clobbers the control flow. How to rewrite it better?

I was thinking about something like:

def view(request):
    with AtomicWithContinuation as a:  # new context manager
        do_stuff(...)
        if condition(...):
            result = do_other_stuff(...)
            a.after_commit(lambda: send_email(result))
        return HttpResponse(...)

which looks easier on the eyes, so I've rolled up a context manager like:

class AtomicWithContinuation(object):

    def __init__(self, *args, **kwargs):
        self.atomic = transaction.atomic(*args, **kwargs)
        self._after_commit = []
        self._after_rollback = []

    def after_commit(self, cb):
        self._after_commit.append(cb)

    def after_rollback(self, cb):
        self._after_rollback.append(cb)

    def __enter__(self):
        self.atomic.__enter__()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
            self.atomic.__exit__(exc_type, exc_val, exc_tb)
        except Exception:
            # atomic.__exit__ itself threw an exception
            # - assume a rollback has been done
            for cb in self._after_rollback:
                cb()
            raise
        if exc_val is not None:
            # Wrapped block raised an exception,
            # so atomic had to do a rollback
            for cb in self._after_rollback:
                cb()
        else:
            for cb in self._after_commit:
                cb()

Does this implementation make sense? Is this a good approach to take? Also, can I trust my assumptions in __exit__?


texts:
Can this be optimized for Java 8 and can it be more efficient? I am using streams and lambdas.

public String LanguageString(Set<Locale> languageSet) throws Exception {
JSONObject json = new JSONObject();
JSONObject tempj = new JSONObject();
JSONArray jArr = new JSONArray();
try {
  for (Locale locale : languageSet) {
    if (locale != null) {
      tempj = new JSONObject();
      tempj.put("lcode", locale.toLanguageTag());
      tempj.put("ldisplay", locale.getDisplayName());
      jArr.put(tempj);
    }
  }
  json.put("root", jArr);
} catch (JSONException e) {
  //
}
return json.toString();
}


texts: Check if images are loaded (ES6 Promises)

texts:
I wrote a small function that checks if an image or multiple images are loaded. For that purpose, I decided to use ES6 promises, but I'm not really sure if my way of handling errors is the best way.

const loadImg = function loadImg(src) {
    'use strict';

    const paths = Array.isArray(src) ? src : [src];
    const promise = [];

    paths.forEach((path) => {
        promise.push(new Promise((resolve, reject) => {
            const img = new Image();

            img.onload = () => {
                resolve({
                    path,
                    status: 'ok',
                });
            };

            // Call `resolve` even if the image fails to load. If we were to
            // call `reject`, the whole "system" would break
            img.onerror = () => {
                resolve({
                    path,
                    status: 'error',
                });
            };

            img.src = path;
        }));
    });

    return Promise.all(promise);
};

// Usage
loadImg([
    'IMG.png',
    'IMG.jpg',
    'IMG.jpg',
    'IMG.jpg',
]).then(function(e) {
    console.log(e);
});

It works, but I'm worried that using objects as error messages rather than reject has some disadvantages that I'm not aware of (e.g. potential memory leaks or people don't expect to see errors in then())? Is there any way I can improve this function?


texts:
I have written AI for Tic-Tac-Toe using Negamax in JavaScript. The Negamax object is translated from an implementation written in Python. The code runs on a Node.js server and the player interacts with it via web socket. The code works and the game is unbeatable meaning it always wins if it can and if it can't, will force a tie.

I am looking for advice on how to optimize this implementation of MiniMax. I am also fairly new to Node.js and am wondering if this will run in a non-blocking way (assuming an instance of the object for each connected user.

Minimax Object:

var MiniMax = function(){
  //init values and options
  this.bestMove = 0;
  this.MAX_DEPTH = 6;
}

MiniMax.prototype = {
  //function called from game, bestmove will return the computer move
  buildTree: function(board, player, cb){
    this.bestMove = 0;
    var alpha = this.buildTree_r(board, player, 0);
    cb(this.bestMove);
  },
  //recursive function to build minimax tree and rate the value of the board
  buildTree_r: function(board, currPlayer, depth){
    if(depth > this.MAX_DEPTH){
      return 0;
    }
    //Set the otherplayer for the next game state and to check for loss
    var otherPlayer;
    if(currPlayer == board.X){
      otherPlayer = board.O;
    } else {
      otherPlayer = board.X;
    }
    //check for a winner in the boardstate, if currPlayer we win, else we lose in this tree
    var winner = board.getWinner();
    if(winner == currPlayer){
      return 1;
    } else if(winner == otherPlayer){
      return -1;
    }
    //check for a full board and therefore cats game in this true
    if(board.isFull()){
      return 0;
    }
    //this is where we begin to rank moves, get an array of moves, set alpha low, instantiate parallel
    //subAlpha list  to movelist to remember move ranks
    var moveList = board.getMoves();
    var alpha = -1;
    var saList = [];
    for(var i=0; i<moveList.length; i++){

      var boardCopy = board.copy(); //Copy current gamestate
      boardCopy.move(currPlayer, moveList[i]); //Make a move for in the gamestate for each possible move
      //console.log(boardCopy.gamestate);

      var subalpha = -this.buildTree_r(boardCopy, otherPlayer, depth + 1); //pass new gamestate into recursion
      if(alpha < subalpha){ //if move is better than alpha, increase alpha
        alpha = subalpha;
      }
      if(depth == 0){ //only if we are looking at REAL gamestate do we push an alpha to the list
        saList.push(subalpha);
      }
    }
    if(depth == 0){
      var posMoves = [];
      for(var n=0; n<saList.length; n++){
        if(saList[n] == alpha){
          posMoves.push(moveList[n]);
        }
      }
      this.bestMove = this.rand(posMoves); //in future pick random..
    }
    return alpha;
  },
  rand: function(list){
    var item = list[Math.floor(Math.random() * list.length)];
    return item;
  }
}

Board Object:

var Board = function(){
  this.empty = 0;
  this.X = 1;
  this.O = 2;
  this.wins = [
    [0,1,2],
    [3,4,5],
    [6,7,8],
    [0,3,6],
    [1,4,7],
    [2,5,8],
    [0,4,8],
    [2,4,6]
    ];
  this.gamestate = [0,0,0,0,0,0,0,0,0];
}

Board.prototype = {
  copy: function(){
    var b = new Board();
    for(var i=0; i<9; i++){
      b.gamestate[i] = this.gamestate[i];
    }
    return b;
  },
  move: function(player, pos){
    this.gamestate[pos] = player;
  },
  getMoves: function(){
    var moves = [];
    for(var i=0; i<9; i++){
      if(this.gamestate[i] == this.empty){
        moves.push(i);
      }
    }
    return moves;
  },
  isFull: function(){
    for(var i=0; i<9; i++){
      if(this.gamestate[i] == this.empty){
        return false;
      }
    }
    return true;
  },
  getWinner: function(){
    for(var i=0; i<this.wins.length; i++){
      var a, b ,c;
      a = this.gamestate[this.wins[i][0]];
      b = this.gamestate[this.wins[i][1]];
      c = this.gamestate[this.wins[i][2]];

      if(a == b && a == c && a != this.empty){
        return a;
      }
    }
    return this.empty;
  }
}


texts: Returning direct status changes of user statuses

texts:
I have a query which returns direct status changes (no intermediary changes) of user statuses:

SELECT u.id         uId,
       pro.id       pId,
       uaud2.status oldStatus,
       uaud1.status newStatus,
       uaud1.statuschangereason,
       uaud1.statuschangedate
FROM   cs_program pro
       JOIN cs_programpatient pp
         ON pro.id = pp.program_id
       JOIN cs_patient p
         ON pp.patient_id = p.id
       JOIN cs_user u
         ON p.user_id = u.id
       JOIN cs_user_aud uaud1
         ON u.id = uaud1.id
       JOIN cs_user_aud uaud2
         ON uaud1.id = uaud2.id
            AND uaud1.rev > uaud2.rev
WHERE  NOT EXISTS (SELECT uaud3.id
                   FROM   cs_user_aud uaud3
                   WHERE  uaud1.id = uaud3.id
                          AND uaud1.rev > uaud3.rev
                          AND uaud3.rev > uaud2.rev)
       AND pro.id IN ( 248 )
       AND uaud2.status <> uaud1.status
       AND uaud2.status IN ( 0, 1, 2, 3,
                             4, 5, 6 )
       AND uaud1.status IN ( 0, 1, 2, 3,
                             4, 5, 6 )
ORDER  BY uaud1.statuschangedate DESC;

The query works as intended but has performance issues even on relatively small data sample. When I ran explain select it showed indices are used and joins are mostly good (const, ref, and eq_ref).

Is this a good way to filter out non-sequential status change records? Can I somehow modify this query so it's more efficient?


texts: Concisely adding values in a loop to a column

texts:
In my data frame I assign values to the column Register by checking another column (Source) for specific values. Based on those values, the output in Register changes.

I am relatively new to R, but I have some coding knowledge. The following code contains lines that are all so similar that I can't help but wonder if it can't be done way simpler with a condition. In JavaScript, for instance, I'd do this with a case-function. I do not know, however, if something similar is possible in R.

d$Register <- "Banana placeholder"
d$Register[grep(".*/comp-a/.*", d$Source, perl=TRUE)] <- "a: spont-conv"
d$Register[grep(".*/comp-b/.*", d$Source, perl=TRUE)] <- "b: interv-ler-nl"
d$Register[grep(".*/comp-(c|d)/.*", d$Source, perl=TRUE)] <- "c/d: telefoon"
d$Register[grep(".*/comp-e/.*", d$Source, perl=TRUE)] <- "e: onderhandeling"
d$Register[grep(".*/comp-f/.*", d$Source, perl=TRUE)] <- "f: interv-radio-tv"
d$Register[grep(".*/comp-g/.*", d$Source, perl=TRUE)] <- "g: debat"
d$Register[grep(".*/comp-h/.*", d$Source, perl=TRUE)] <- "h: les"
d$Register[grep(".*/comp-i/.*", d$Source, perl=TRUE)] <- "i: spont-comm-radio-tv"
d$Register[grep(".*/comp-j/.*", d$Source, perl=TRUE)] <- "j: reportage-radio-tv"
d$Register[grep(".*/comp-k/.*", d$Source, perl=TRUE)] <- "k: nieuws-radio-tv"
d$Register[grep(".*/comp-l/.*", d$Source, perl=TRUE)] <- "l: comm-radio-tv"
d$Register[grep(".*/comp-m/.*", d$Source, perl=TRUE)] <- "m: misviering"
d$Register[grep(".*/comp-n/.*", d$Source, perl=TRUE)] <- "n: college"
d$Register[grep(".*/comp-o/.*", d$Source, perl=TRUE)] <- "o: voorgelezen"


texts: Transferring data from one file stream to another

texts:
I am currently reading Clean Code and for fun and profit, I intended to refactor some of the Java Tutorials and since I wanted to improve my Exception handling, the Byte Stream one with its lots of IOExceptions seemed nice.

This code does work, but is it better now? As far as I can tell it's more readable now, though there are much more methods. Can someone more experienced with clean code tell me what to improve on this?

This code just copies bytes from one file to another:

public class Tutorial {

    public static void copyBytes() {

        FileInputStream input = getNewFileOutputStream();
        FileOutputStream output = getNewFileInputStream();

        try {
            transferBytesFrom(input, output);
        } finally {
            closeStreams(input, output);
        }
    }

    private static void closeStreams(FileInputStream input, FileOutputStream output) {
        try {
            input.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void transferBytesFrom(FileInputStream input, FileOutputStream output) {
        int singleByte;

        while ((singleByte = readByteFrom(input)) != -1) {
            writeByteTo(output, singleByte);
        }
    }

    private static void writeByteTo(FileOutputStream output, int singleByte) {
        try {
            output.write(singleByte);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static int readByteFrom(FileInputStream input) {
        try {
            return input.read();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        return -1;
    }

    private static FileOutputStream getNewFileInputStream() {
        try {
            return new FileOutputStream("output.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        return null;
    }

    private static FileInputStream getNewFileOutputStream() {
        try {
            return new FileInputStream("xanadu.txt");
        } catch (FileNotFoundException e) {
            System.out.println("ERROR: Input file not found!");
        }

        return null;
    }
}


texts: Checking to see if all values in an array are equal

texts:
I have an array that might be either one-dimensional, two-dimension, or three-dimensional. I'm wanting to check to see if all values in a given direction are constant.

Here are 3 functions:

# Check to see if all values in the first dimension are equal
def constant1D(arr)
  arr.inject(true) { |same, val| same and val == arr[0] }
end

# Check to see if all values in the second dimension are equal
def constant2Dy(arr)
  arr.inject(true) { |same, x| same and constant1D(x) }
end

# Check to see if all values in the third dimension are equal
def constant3Dz(arr)
  arr.inject(true) { |same, x| same and constant2Dy(x) }
end

And here is the code that would be checking:

constantX = constant1D(values)
constantY = ((mapType == :twoD) and constant2Dy(values))
constantZ = ((mapType == :threeD) and constant3Dz(values))

Here are some sample runs:

threeDa = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]]
threeDb = [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[4, 5, 6], [4, 5, 6], [4, 5, 6]], [[7, 8, 9], [7, 8, 9], [7, 8, 9]]]
threeDc = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]], [[7, 7, 7], [8, 8, 8], [9, 9, 9]]]
>> constant1D(threeDa)
=> true
>> constant1D(threeDb)
=> false
>> constant1D(threeDc)
=> false
>> constant2Dy(threeDa)
=> false
>> constant2Dy(threeDb)
=> true
>> constant2Dy(threeDc)
=> false
>> constant3Dz(threeDa)
=> false
>> constant3Dz(threeDb)
=> false
>> constant3Dz(threeDc)
=> true

Is this the most "Ruby" way, or is there a better way? E.g., referencing arr[0] in the above has a little bit of code smell to me, but perhaps I'm overthinking it.


texts:
I know exactly how I would handle this in PHP, Python, JS, and AS, but I want to confirm that this is the correct approach to Enums in Java.

I have a database view which has a status column. It will only ever have one of four values (in MySQL, I would have made it an enum type column, but the type doesn't really matter in my current context). Each directly maps to one of the values defined below.

public enum StatusDefinitions {
    NOT_STARTED("not started"),
    IN_PROGRESS("in progress"),
    COMPLETE("opted out"),
    OPTED_OUT("complete");

    private String desc;

    private StatusDefinitions(String desc)
    {
        this.desc = desc.toLowerCase();
    }

    public String getDescription()
    {
        return desc;
    }

    public static StatusDefinitions getStatus( String desc )
    {
        desc = desc.toLowerCase();
        for( StatusDefinitions it: StatusDefinitions.values() )
        {
            if( it.getDescription().equals( desc ) ) return it;
        }
        return StatusDefinitions.NOT_STARTED;
    }
}

Now, in my JSP, I loop for(StatusDefinitions it: StatusDefinitions.values()) and have selected="selected" based on if(modelObjStatus == it). When pulling this from/pushing it to the db, I have status = StatusDefinitions.getStatus( rs.getString( "status" ) );. And there is where I have this sensation that I've missed something. Looping through all of the Strings and comparing them seems like I lose the benefit of the Enum. It would almost seem better to have a series of public static final Strings.

(Before anyone asks, because of the scope of this particular project, it doesn't make sense to make this an ORM.)


texts: Python Converting numbers to words, using Recursive

texts:
My function recursively calls itself until it decodes every numbers. rec_ntw

face_value_count -> (Incremental variable) denotes ones, tens, hundreds and thousands
face_value -> (Dictionary) denotes the dictionary containing corresponding the word value for numbers.

result -> (String) Contains final result to return.

teen -> (Integer) to decode the teen numbers from eleven to ninteen

number % 10 to get the last element

number // 10 to remove the last element and pass it on to recursive the function.

def rec_ntw(number, face_value_count=0):
        result = ""
        teen = 0
        if number <= 0:
                if face_value_count == 0:
                        result = "Zero"
                print (result)
                #return result
        else:
                if face_value_count == 0:
                        result = (singleton[int(number % 10)])
                        teen = number % 10
                elif face_value_count == 1:
                        if number % 10 == 1:
                                result = (face_value[1][1][int(teen)]) + " "
                        else:
                                result = (face_value[int(face_value_count)][int(number % 10)]) + " " + result
                                teen = 0
                elif face_value_count == 2:
                        if number % 10 != 0:
                                result = (singleton[int(number % 10)] + " " + str(face_value[int(face_value_count)]) + " ") + result
                else:
                        result = (singleton[int(number % 10)] + " " + str(face_value[int(face_value_count)]) + " ") + result
                face_value_count += 1
                rec_ntw(number // 10, face_value_count)

Please review my code and lemme know how to write effectively.


texts: Click textbox to show answer and highlight related text

texts:
Is this JavaScript code robust? It is for an interactive book about a card game. When the reader clicks on the checkbox, an answer is revealed and related text is highlighted. I need to get this right before I write more chapters.

JSBin

<!DOCTYPE html>

   <title>Quiz</title>

<form name="form1">

Q1: 3  5   10
 Click
<input onclick="hlt_showhide(this)" type="checkbox" name=""  answer="1">

A1:  revealed text refers to 2nd & 3rd highlighted numbers

Q2:  7  28  37
 Click
<input onclick="hlt_showhide(this)" type="checkbox" name="" answer="2">

A2:  revealed text refers to 1st & 3rd highlighted numbers

</form>


texts: Send messages to multiple passed recipients or a default recipient

texts:
I have a function that accepts false as a default value but can be passed an array.

protected function sendMessages ($recipients = false) {

    //cast to an array
    $recipients = is_array($recipients) ? $recipients : [$recipients];

    // if no recipients are passed get email from current object (default)
    if (isset($recipients[0]) && $recipients[0] === false) {
        array_pop($recipients);
        array_push($recipients, 'email' => $this->author->email);
    }

    foreach ($recipients as $recipient) {
        //some logic.
    }
}

The whole, check if the first element is false, and if so swap it out seems a little convoluted / backwards to me. But I'm not sure of a cleaner method. The default value could be changed but is needed so that older calls to the method that specify no parameters don't choke.


texts:
I have written this code after studying from Introduction to Algorithm. I think this code is very basic and simple. I want to modify it.

#include <iostream>
int tail;
int head;

void initialise_head_tail(){
tail=0;
head=0;
}

void enqueue(int a[],int x,int s){
a[tail]=x;
if( tail+1==s)
    tail=0;
else
    tail++;
}

int dequeue(int a[],int s){
int x=a[head];
if(head+1==s)
    head=0;
else
    head++;
return x;
}
int main()
{
    initialise_head_tail();
    int a[5];
    enqueue(a,15,5);
    enqueue(a,6,5);
    enqueue(a,9,5);
    enqueue(a,8,5);
    enqueue(a,4,5);
    for(int i=0;i<5;i++){
        std::cout<<a[i]<<" ";
    }
    std::cout<<"\n"<<dequeue(a,5);
    return 0;
}

I want to learn if I can apply some better logic. I was thinking to use vector instead of array but there are already methods push_back() and pop_back(). Can we use vector?


texts: Parsing a tabular log file into a hashmap

texts:
I have this method that reads a file into a hashmap. I feel like there are too many levels in this code with all these tries, ifs and so on. How do you think this can be improved?

public static ExchangeHistory loadHistory(String path){
    Map<Integer, Date> rtcHistory = new HashMap<Integer, Date>();
    Map<Integer, Date> almHistory = new HashMap<Integer, Date>();

    ExchangeHistory exchHist = new ExchangeHistory(rtcHistory, almHistory);

    File file = new File(path);

    BufferedReader reader = null;
    try{
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        String line;
        int lineNumber = 1;

        // read file line by line
        while ((line = reader.readLine()) != null){
            String[] tokens = line.split("\\s");
            if (tokens.length != 3){
                log.error("Unable to parse exchange history file at line: " + lineNumber);
                continue;
            }

            // try to parse line. if parsing fails, just skip it
            try {
                int id = Integer.parseInt(tokens[1]);
                long timeInMillis = Long.parseLong(tokens[2]);

                if (tokens[0].equals(System.RTC)){
                    rtcHistory.put(id, new Date(timeInMillis));
                } else if (tokens[0].equals(System.ALM)){
                    almHistory.put(id, new Date(timeInMillis));
                }

            } catch (Exception e){
                log.error("Unable to parse exchange history file at line:" + lineNumber, e);
            }

            lineNumber++;
        }

    } catch (FileNotFoundException e){  // try to create a new file in case it doesn't exist

        log.warn("No exchange history file found at " + path);

        try {
            file.createNewFile();
            log.info("Created new exchange history file at "  + path);
        } catch (IOException ioe){
            log.error("Unable to create exchange history file at " + path
                    + ". Exchange session info won't be saved", ioe);
        }
        // return an empty history list cause there are no records in new file
        return exchHist;
    } catch (IOException e) {
        log.error("Unable to read exchange history file at " + path
                + ". All items will be synchronized anew", e);
        return exchHist;
    } finally{
        if (reader != null){
            try {
                reader.close();
            } catch (IOException e) {
                log.error("Unable to close input stream. Resource leak possible", e);
            }
        }
    }

    return exchHist = new ExchangeHistory(rtcHistory, almHistory);
}


texts: Passing objects atomically across threads without locks or data races for audio synchronization

texts:
I am learning about one of the hardest parts of Audio development: the synchronization between the audio thread and the GUI thread.  Per the discussion here https://forum.juce.com/t/timur-doumler-talks-on-c-audio-sharing-data-across-threads/26311 and here: https://stackoverflow.com/questions/15460829/lock-free-swap-of-two-unique-ptrt
I'm wondering if the following class solves the problem or comes close to solving it.

template<typename T>
struct SmartAtomicPtr
{
    SmartAtomicPtr( T* newT )
    {
        update( newT );
    }
    ~SmartAtomicPtr()
    {
        update(nullptr);
    }
    void update( T* newT, std::memory_order ord = memory_order_seq_cst )
    {
        keepAlive.reset( atomicTptr.exchange( newT, ord ) );
    }
    std::shared_ptr<T> getShared(std::memory_order ord = memory_order_seq_cst)
    {
       return std::make_shared<T>( atomicTptr.load(ord) );
    }
    T* getRaw(std::memory_order ord = memory_order_seq_cst)
    {
         return atomicTptr.load(ord);
    }
private:
    std::atomic<T*> atomicTptr{nullptr};
    std::shared_ptr<T> keepAlive;
};

I know that whatever value ends up in the shared_ptr won't be deleted until the SmartAtomicPtr goes out of scope, which is fine.

the ultimate goal would be a lock-free, wait-free solution.

an example of where this might get used is the following interleaving of the audio and message thread.  The goal is to keep the returned object from dangling

/*
AudioProcessor owns a SmartAtomicPtr<T> ptr that the message
thread has public access to.
*/
/* audio thread */ auto* t = ptr.getRaw();
/* message thread */ processor.ptr.update( new T() );
/* audio thread */ t->doSomething(); //t is a dangling pointer now

with getShared(), I believe that t no longer dangles:

/* audio thread */ auto t = ptr.getShared();
/* message thread */ processor.ptr.update( new T() );
/* audio thread */ t->doSomething(); //t is one of 2 shared_ptrs
//holding the previous atomic value of ptr

I ran into some double-deletes, but I believe I have solved them, and also prevented the shared_ptr member from being stomped on in the event you call getShared() and update() at the same time, and also kept it leak-free.

any thoughts?


texts:
I am implementing Unix sort in Clojure. This is my first program, and I would like some feedback regarding any non-idiomatic, harmful code and any other best practices I can include in future versions. I tried my best to follow the coding standards, but went with camelCase instead of hyphen-case for variable and function names.

Main class: sort.core

(ns sort.core
  (:gen-class)
  (:use clojure.contrib.core)
  (:use clojure.tools.cli)
  (:require [sort.lib :as lib]))

(defn -main [& args]
  (let [[options args banner] (cli args
                                   ["-h" "--help" "Show help" :default false :flag true]
                                   ["-i" "--input" "The input file" :default nil]
                                   ["-d" "--delim"  "The delimitter" :default ","]
                                   ["-f" "--field" "The column to parse(1 indexed)" :parse-fn #(Integer. %)])
        {:keys [delim field input]} options]

    (lib/help options args banner)

    (when (= (lib/fileKind input) "file")
        (lib/printOutVector delim
                            (lib/sortVector field
                                            (lib/splitFile input delim ))))

    (System/exit 0)))

Library: sort.lib

(ns sort.lib
  (:require [clojure.string :as str])
  (:import java.io.File))

(defn splitFile
  "splits a file into a 2d array"
  [s delim]
  (pmap #(str/split % (re-pattern delim))
        (str/split(slurp s) #"\n")))

(defn printOutVector
  "prints out the 2dVector formatted by the delim arg"
  [delim coll]
  (println
    (apply str
           (interpose "\n" (map #(apply str (interpose delim %)) coll)))))

(defn sortVector
  "sorts a 2d vector by the given index"
  [index coll]
  (sort-by #(nth % index) coll))

(defn help
  "custom help message for sort.core"
  [opts args banner]
  (when (:help opts)
    (println (str "input: " (:input opts)))
    (println (str "field: " (:field opts)))
    (println (str "delim: " (:delim opts)))
    (println banner)
    (System/exit 0)))

(defn fileKind [filename]
  (let [f (File. filename)]
    (cond
      (.isFile f)      "file"
      (.isDirectory f) "directory"
      (.exists f)      "other"
      :else            "(non-existent)" )))


texts: Unit tests for a simple function thats part of a public API

texts:
Given I have to write a simple function that essentially just does a http-fetch
 to the given URL but is part of a public API that will be used by thousands.

I have two main questions about the problem:

Since this is a public API Im not sure how to handle inproper input. Should I return undefined or throw an error? (I rather throw errors to make it most obvious what types are expected). I've seen other API's however just returning undefined, which to me seems pretty stupid, as surely you dont want to be handling undefined in high level code?

function at(_url, _options) {

    if (!_options)
        throw new ReferenceError("No options provided.")

    if (typeof _options !== "[Object object]")
        throw new TypeError("No options provided.")

    if (typeof _url !== "string")
        throw new TypeError("URL must be a string.")

    ...

Is it too much to actually test if each possible inproper input is at hand?
(I find myself writing the same test code for each function I write and after a while it seemed kind "wrong" to be doing typechecking in JS. Is there a standard for typechecking inside API's in JS?)

const expect = require("chai").expect
const fetchWithOptions = require("./../index")

describe("me()", () => {
    it("should throw error if no options are provided", () => {
        expect(() => fetchWithOptions.at("some-url")).to.throw(ReferenceError)
    })

    it("should throw an error if options are not an object", () => {
        expect(() => fetchWithOptions.at("some-url", "string options")).to.throw(TypeError)
    })

    it("should throw an error if the provided url is not a string", () => {
        expect(() => fetchWithOptions.at(123123, {someOption: "someOption"})).to.throw(TypeError)
    })

})


texts:
I have generated code which reads a file containing ways, take the individual waypoints and writes them into a new file, but only if the waypoint is not already present. At this moment my program stores the waypoint in a vector. Before the new found waypoint is written to the file the program checks if the waypoint is not already in the vector.

The program read and wrote the first 140,000 waypoint is 12 minutes, but as there are more then 13 million ways (expected 90 million waypoints) to read, examine and written this is going to take days.

I would much appreciate if anyone of you could give me a suggestion to improve the code.

struct NodeTemplate{
  string ID;
  string NodeID;
  string latitude;
  string longitude;
};
vector <NodeTemplate> NodesOut;

void split(const string& s, char c,
           vector<string>& v) {
   string::size_type i = 0;
   string::size_type j = s.find(c);

   while (j != string::npos) {
      v.push_back(s.substr(i, j-i));
      i = ++j;
      j = s.find(c, j);

      if (j == string::npos)
         v.push_back(s.substr(i, s.length()));
   }
}

int main(int argc, char *argv[])
{
      string filenameIn="ways.txt";
      ifstream myfile ((filenameIn).c_str( ));

      string fileNameNodes2="nodes2.txt";
      fstream myfile3;

      myfile3.open(fileNameNodes2.c_str(),fstream::out | fstream::trunc);
      myfile3.close();

      myfile3.open(fileNameNodes2.c_str(),fstream::out | fstream::app);

      if (myfile.is_open())
            {while ( getline (myfile,line1) )
                {

                    string s1=line1;
                    vector<string> v1;
                    split(s1, ';', v1);

                    string s2=v1[4];
                    vector<string> v2;
                    split(s2, ',', v2);
                    for (int t=0;t<v2.size();t++)
                        {
                            NodePresent=false;
                            for(int tt=0;tt<NodesOut.size();tt++)
                                {
                                  if(atoi(v2[t].c_str())==atoi((NodesOut[tt].ID).c_str()))
                                    {   NodePresent=true;
                                        break;
                                    }
                            }

                                if(!NodePresent)
                                    {
                                        stringstream ss;
                                        ss<<CounterLine;
                                        stringstream ss2;
                                        ss2<<v2[t];
                                        NewLine=ss.str()+";"+ss2.str()+"\n";
                                        myfile3.flush();
                                        myfile3<<NewLine;
                                        if(myfile3.fail()){cout<<"can't write...\n";}
                                        cout<<CounterLine<<"\r";
                                        CounterLine++;

                                        NodesOut.push_back(NodeTemplate());
                                        NodesOut[NodesOut.size()-1].ID=ss.str();
                                        NodesOut[NodesOut.size()-1].NodeID=ss2.str();

                                    }
                            }

                }
    }
  return EXIT_SUCCESS;
}


texts: Faster Django CSV generation for several million database entries

texts:
I am writing a CSV file generator that's filtering through about seven million database entries (MySQL backend).  This part is especially slow and I was wondering if there is a way to make it much faster. I was thinking of wiring to a temp file first before serving it and then deleting the file.

The Station.header() returns a list with header names ['a','b','c'], etc.

Is there an advantage to this? Is there a better way?

def metadata_file(request):
    """Gets metadata for sensors"""
    if request.GET.has_key('all'):
        s101 = Station.objects.all().filter(fwy='101', dir='S',
                                    abs_pm__gte=420.80, abs_pm__lte=431.63)
        s280 = Station.objects.all().filter(fwy='280', dir='S',
                                    abs_pm__gte=41.16, abs_pm__lte=56.49)
        q = s101|s280
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename="all_stations.csv"'

        writer = csv.writer(response)
        writer.writerow(Station().header())
        for x in q:
            writer.writerow(x.line())
        return response


texts: Format conversion of localization files | 3txt to xliff

texts:
I'm trying to build an xliff for localization from 3 specific files: one contains a list of IDs, the other a list of source strings and the last, a list of translated strings.

Basically, each file contains 200,000 strings, and the process is taking so much time. How can I speed up this loop?

I use sed to replace < with &lt; and the same for >. If you have better ideas, please tell me.

FILE_ID=$1
FILE_SOURCE=$2
FILE_TARGET=$3
TOT_STRING=$(wc -l < $FILE_ID)
time=$(date +"%Y-%m-%d %H:%M")

echo "<?xml version='1.0' encoding='utf-8'?>"
echo "<xliff xmlns=\"urn:oasis:names:tc:xliff:document:1.1\" version=\"1.1\">"
echo " <file source-language=\"en-US\" datatype=\"plaintext\">"
echo "    <body>"
echo "      <trans-unit xml:space=\"preserve\" id=\"1\" approved=\"no\" restype=\"x-gettext-domain-header\">"
echo "        <source>Project-Id-Version: 1.0"
echo " Report-Msgid-Bugs-To: email@example.com"
echo "POT-Creation-Date: $time+0200"
echo "PO-Revision-Date: $time+0200"
echo "Last-Translator: JohnnyKing"
echo "Language-Team: JohnnyKing"
echo "MIME-Version: 1.0"
echo "Content-Type: text/plain; charset=UTF-8"
echo "Content-Transfer-Encoding: 8bit"
echo "X-Generator: csv2xliff.sh"
echo "</source>"
echo "        <target state=\"translated\">Project-Id-Version: 1.0"
echo " Report-Msgid-Bugs-To: email@example.com"
echo "POT-Creation-Date: $time+0200"
echo "PO-Revision-Date: $time+0200"
echo "Last-Translator: JohnnyKing"
echo "Language-Team: JohnnyKing"
echo "MIME-Version: 1.0"
echo "Content-Type: text/plain; charset=UTF-8"
echo "Content-Transfer-Encoding: 8bit"
echo "X-Generator: csv2xliff.sh"
echo "</target>"
echo "      </trans-unit>"

    COUNTER=1

        while [  "$COUNTER" -le "$TOT_STRING" ]; do

        ROW_ID=$(sed -n $(( $COUNTER ))p $FILE_ID)
        ROW_SOURCE=$(sed -n $(( COUNTER ))p $FILE_SOURCE)
        ROW_TARGET=$(sed -n $(( COUNTER ))p $FILE_TARGET)

        if [ "$ROW_SOURCE" = "$ROW_TARGET" ]; then
            echo "      <trans-unit xml:space=\"preserve\" id=\"$ROW_ID\">"
            echo "        <source>$(echo $ROW_SOURCE | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</source>"
            echo "        <target></target>"
            echo "      </trans-unit>"
        else
            echo "      <trans-unit xml:space=\"preserve\" id=\"$ROW_ID\" approved=\"yes\">"
            echo "        <source>$(echo $ROW_SOURCE | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</source>"
            echo "        <target state=\"translated\">$(echo $ROW_TARGET | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</target>"
            echo "      </trans-unit>"
        fi

        COUNTER=$(( $COUNTER + 1 ))
        done

echo "       </trans-unit>"
echo "    </body>"
echo "  </file>"
echo "</xliff>"

exit


texts:
I'm curious if this is the right way of going about the issue:

function sortWordsByIncorrectAnswers(array) {
    array = array.slice(0)
    var sortedArray = array.sort(function (a, b) {
        a = a.fields.false;
        b = b.fields.false;
        return a < b ? -1 : a > b ? 1 : 0;
    });
    return sortedArray
}

I want to return a new version of the array, and not change 'array' passed into the method (deep copy).

This works as I want it to, but is this the correct way of doing this? It seems off.


texts: Recursive comment function echoes HTML inside function

texts:
To display comments recursively I'm using this:

function fetch_article_comments($article_id, $parent_id) {
$app = new Connection();

    if ($parent_id <= 0) {
        $parent_id = NULL;
    }
    $sql = "SELECT * FROM recursive WHERE article_id = :article_id AND comment_parent <=> :parent_id ORDER BY comment_timestamp ASC";
    $query = $app->getConnection()->prepare($sql);

    $query->execute(array(':article_id' => $article_id,
                          ':parent_id' => $parent_id));

    return $query->fetchAll();
}

And to display the comments:

function display_comments ($article_id, $parent_id=0, $level=0) {
$comments = fetch_article_comments($article_id, $parent_id);
  foreach($comments as $comment) {
        $comment_id = $comment->comment_id;
        $member_id = $comment->member_id;
        $comment_text = $comment->comment_text;
        $comment_timestamp = $comment->comment_timestamp;  //get timeAgo

        // RENDER
      ?>

              <?= timeAgoInWords($comment_timestamp); ?>

          <?= $comment_text ?>

              <a href="#" class="replyLink" data-comment-id="<?= $comment_id ?>"> reply
              <a href="recursive.php?delete=<?= $comment_id ?>"> delete

    <form action="recursive.php" method="post" class="uk-form comment_form" id="<?= $comment_id ?>">
    <fieldset data-uk-margin>
        <input type="hidden" name="id" value="<?= $article_id ?>" />
        <input type="hidden" name="parent" value="<?= $comment_id ?>" />
        <input type="text" placeholder="Comment" name="svar">
        <button class="uk-button">Comment</button>
    </fieldset>
</form>

<?php
        //Recurse
        display_comments($article_id, $comment_id, $level+1);
                echo '
 ';
    }

}
?>

And the comments is then echoed on the page calling the display_comments().

<?= display_comments(2); ?>

(the 2 is the post ID)

As you can see there's a lot of HTML inside the function, it's not ideal. How can the code be improved to remove the HTML and maybe foreach the results?


texts:
I was wondering if I can make this better:

public int BinarySearchIterative(int[]inputArray, int Key) {
        int min = 0;
        Array.Sort(inputArray);
        int max = inputArray.Length;
        return BinarySearchIterative(inputArray,Key,min,max,0);
    }

    public int BinarySearchIterative(int[] inputArray, int key, int min, int max,int LoopCount) {
        while(min <= max) {
            int mid = (min + max) / 2;
            if(key == inputArray[mid]) {
                return ++mid;
            } else if(key < inputArray[mid]) {
                max = mid - 1;
            } else {
                min = mid + 1;
            }
            LoopCount++;
        }
        return LoopCount;
    }


texts:
Based on the sample variants, I need to get all combinations of all variants. In the example I have 3x3x2=18 variants.
## SAMPLE VARIANTS
sizes = ['small', 'medium', 'large']
colors = ['red', 'green', 'blue']
materials = ['cotton', 'linen']

## ITERATE TO ALL VARIANTS
titles = []
sizes.each do |size|
  colors.each do |color|
    materials.each do |material|
      ## PUT THE VARIANT IN THE NEW ARRAY
      titles.push("#{size} - #{color} - #{material}")
    end
  end
end

puts titles.inspect

Is my nested each loop preferred or there is some better implementation for this?


texts: Uploading files through streaming with SignalR

texts:
I want to upload files from my Javascript client to my WebAPI.
With this I want to have a progress bar. My Idea was to cut the files up in chunks and then stream them via SingalR since we are using SingalR anyway.

This is my code:

API:

public async Task UploadStream(IAsyncEnumerable<string> stream)
{
    string buffer = "";

    await foreach (var item in stream)
    {
        buffer += item;
    }

    Console.WriteLine(buffer);
}

Javascript:

let base64 = data;
let chunks = base64.match(/.{1,25000}/g);

const subject = new signalR.Subject();
hub.getConnection().send("UploadStream", subject);

chunks.forEach((chunk: string) => {
    subject.next(chunk);
});

subject.complete();

Now, this works, and it takes about 0.3 seconds to upload a 2.8MB image on localhost. But, my question is: Is this a good or bad practice? Or is it better to upload files as a multipart request?


texts:
I need to refactor this code, targeted to Google Chrome (current+) to make it manageable going forward.

Here is a working JSBin of the idea.

The messiness comes from determining the accurate number of lines of text, and the real heights of elements. I know I am passing this information around too much, without enough structure, and recalculating too many things. I also know it is messy, especially inside scal_el and run_scan.

function scan_el(el_fin_callback,el,mask,sub_mask,real_height,real_width,push,lines,line) {
        line = line || 0;
        if(line >= lines) {
                el_fin_callback();
                return; // scan finished
        }
        var current_line = real_height*line;
        var line_os = $(el).offset();
        line_os.top += current_line;
        if(lines > 1) {
                $(mask)[0].style.height = real_height+'px';
        }
        $(sub_mask).css( {
                'height' : $(el).height()-real_height-current_line } );
        $(mask).offset(line_os);
        line_os.top += real_height;
        var length = Math.ceil($(el).text().length*real_width)+push;
        if(lines > 1) {
                length = $(el).width();
        }
        $(sub_mask).offset(line_os);
        function next_line() { // callback after scan complete
                scan_el(el_fin_callback,el,mask,sub_mask,real_height,real_width,push,lines,line+1);
        }
        run_line_scan(length,mask,next_line);
}


texts: A* algorithm optimization and implementation

texts:
I am implementing the A* algorithm in Python and have successfully completed the task. It works and even spits out the coordinates from the start to the end.

However, I am programming a bot for a game which times out after 2 seconds if no commands are sent. My code just to run takes 2.3 - 2.4 seconds each time and not to mention that moving from coordinate to coordinate is a waste. The game utilises angles and speed to move a ship around. I am baffled as to how I can incorporate my code to the bot to:

minimize execution
use the coordinates somehow to move the ship.

My code:

class GridWithWeights(SquareGrid):
    def __init__(self, width, height):
        super().__init__(width, height)
        self.weights = {}

    def cost(self, from_node, to_node):
        x = from_node[0]
        y = from_node[1]

        results = {(x-1, y+1):14, (x, y+1):10, (x+1, y+1):14,
                   (x-1, y):10,                (x+1,y):10,
                   (x-1, y-1):14, (x, y-1):10, (x+1, y-1):14
                   }

        try:
            return results[to_node]
        except Exception:
            return 0

    def in_bounds(self, id):
        (x, y) = id
        return 0 <= x < self.width and 0 <= y < self.height

    def passable(self, id):
        return id not in self.walls

    def neighbors(self, id):
        (x, y) = id
        results = [(x-1, y+1), (x, y+1), (x+1, y+1),
                   (x-1, y),                (x+1,y),
                   (x-1, y-1), (x, y-1), (x+1, y-1)
                   ]
        if (x + y) % 2 == 0: results.reverse() # aesthetics
        results = filter(self.in_bounds, results)
        results = filter(self.passable, results)
        return results

import heapq

class PriorityQueue:
    def __init__(self):
        self.elements = []

    def empty(self):
        return len(self.elements) == 0

    def put(self, item, priority):
        heapq.heappush(self.elements, (priority, item))

    def get(self):
        return heapq.heappop(self.elements)[1]

def reconstruct_path(came_from, start, goal):
    current = goal
    path = []
    while current != start:
        path.append(current)
        current = came_from[current]
    path.append(start) # optional
    path.reverse() # optional
    return path

def heuristic(a, b):
    (x1, y1) = a
    (x2, y2) = b
    return abs(x1 - x2) + abs(y1 - y2)

def a_star_search(graph, start, goal):

    frontier = PriorityQueue()
    frontier.put(start, 0)
    came_from = {}
    cost_so_far = {}
    came_from[start] = None
    cost_so_far[start] = 0

    while not frontier.empty():
        current = frontier.get()

        if current == goal:
            break

        for next in graph.neighbors(current):
            new_cost = cost_so_far[current] + graph.cost(current, next)
            if next not in cost_so_far or new_cost < cost_so_far[next]:
                cost_so_far[next] = new_cost
                priority = new_cost + heuristic(goal, next)
                frontier.put(next, priority)
                came_from[next] = current

    return came_from, cost_so_far

diagram4 = GridWithWeights(360, 240)
diagram4.walls = [(2,5),(1, 7), (1, 8), (2, 7), (2, 8), (3, 7), (3, 8)]  # Obstructions

start, goal = (141, 42), (54, 190)
came_from, _ = a_star_search(diagram4, start, goal)
print(reconstruct_path(came_from, start=start, goal=goal))

Disclaimer: This is a competition (Halite 2) where the rules are leniant about taking help from outside and even promote creating a new pathfinding function/algorithm

Read 'A Journey of a Thousand Li Starts Beneath One’s Feet'.

Read 'Community Policies'


texts:
I have written a small and simple ThreadPool class for rather simple multithreading applications.

The Threadpool class manages a vector with the actual threads.
The Thread struct is used to store the thread's function.
ThreadPoolElement keeps track of the thread and its state.

#pragma once

#include <vector>
#include <thread>
#include <mutex>

namespace frm { namespace util {

template <typename F, typename ... Args>
struct Thread {
    Thread(F&& f)
    : func(f) {
    }
    std::function<void(Args...)> func;
};

class Threadpool {

public:

    Threadpool(const size_t& capasity = std::thread::hardware_concurrency())
        : m_capacity(capasity) {
        m_threads.reserve(m_capacity);
    }

    virtual ~Threadpool() {
        for (auto& t : m_threads) {
            t.thread.join();
        }
    }

    template <typename Thread, typename ... Args>
    void getThread(Thread& t, Args... args) {

        while (m_threads.size() >= m_capacity) {
            cleanup();
        }

        std::lock_guard<std::mutex> lock(m_mutex);
        m_threads.emplace_back(ThreadPoolElement());
        ThreadPoolElement& elem = m_threads[m_threads.size() - 1];
        elem.thread = std::thread([&] (ThreadPoolElement* e, Thread& t, Args... args) {
            t.func(args...);
            e->is_done = true;
        }, &elem, t, args...);
    }

    size_t activeThreads() const {
        return m_threads.size();
    }

    size_t reservedThreads() const {
        return m_capacity;
    }

    void cleanup() {
        for (int i = 0; i < m_threads.size(); i++) {
            if (m_threads[i].is_done) {
                std::lock_guard<std::mutex> lock(m_mutex);
                m_threads[i].thread.join();
                m_threads.erase(m_threads.begin() + i--);
            }
        }
    }

private:

    struct ThreadPoolElement {
        std::thread thread;
        volatile bool is_done = false;
    };

    size_t m_capacity;
    std::mutex m_mutex;
    std::vector<ThreadPoolElement> m_threads;

};

} }

My questions are pretty simple:

Has this implementation any significant downsides that would make it a 'Please do not use this' implementation?
What are the most important parts I'm missing?


texts: PHP class which preserves line break by splitting the line into as many line break as it have

texts:
Can anyone here please review my PHP code which preserves line break by splitting the line into as many line break as it have?

class PerserveLineBreak
{
    //Preserves line break in HTML element content while stripping by splitting the html element content into two items
    protected $text;
    protected $pattern;
    protected $preservedContent;

    function __construct($text, $pattern="
-")
    {
        $this->text = $text;
        $this->pattern = $pattern;
        $this->init();
    }

    function init(){
            $this->preservedContent = $this->perserveLineBreak($this->text,$this->pattern);
    }

    function preparePattern($pattern)
    {
        //adding delimiter and use preg_quote
        $pattern = "#" . $pattern . "#";
        return preg_quote($pattern);
    }

    function getPreservedContent(){
        return $this->preservedContent;
    }

    function perserveLineBreak($content, $searchPattern)
    {
        //looks in for
 by default
        return $this->stripListOfString((preg_split($this->preparePattern($searchPattern), $content)));
    }

    function stripListOfString($listString)
    {
        //strips the splitted html element
        $strippedList = array();
        foreach ($listString as $item) {
            array_push($strippedList, trim(strip_tags($item)));
        }
        return $strippedList;
    }

}

I am brand new to PHP programming language and interested in improving my coding standard and OOP design?

Please do review my code and give me constructive feedback?


texts:
I wrote a card class a while back in this post here: Previous Question
I know it has been a long time but I recently came back to the project and wrote it using an enum as suggested in the answer to increase readability and to make input less error prone. I've never really used enums in Python so the question is did I do it correctly or is there a better way to do it?

from enum import Enum

class Suit(Enum):
    CLUB, HEART, DIAMOND, SPADE = range(1, 5)

class Rank(Enum):
    TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN = range(2,11)
    JACK, QUEEN, KING, ACE = 'J', 'Q', 'K', 'A'

class Card(object):
    """Models a playing card, each Card object will have a suit, rank, and weight associated with each.

    possible_suits -- List of possible suits a card object can have
    possible_ranks -- List of possible ranks a card object can have
    Suit and rank weights are initialized by position in list.
    If card parameters are outside of expected values, card becomes joker with zero weight
"""

    def __init__(self, suit, rank, in_deck = False):
        if suit in Suit and rank in Rank:
            self.suit = suit
            self.rank = rank
            self.suit_weight = suit.value
            self.rank_weight = rank.value
        else:
            self.suit = "Joker"
            self.rank = "J"
            self.suit_weight = 0
            self.rank_weight = 0
        self.in_deck = in_deck

    def __str__(self):
        """Returns abbreviated name of card

        Example: str(Card('Spades', 'A') outputs 'AS'
        """
        return str(self.rank.value) + str(self.suit.name[0])

    def __eq__(self, other):
        """Return True if cards are equal by suit and rank weight"""
        return self.suit_weight == other.suit_weight and self.rank_weight == other.rank_weight

    def __gt__(self, other):
        """Returns true if first card is greater than second card by weight"""
        if self.suit_weight > other.suit_weight:
            return True
        if self.suit_weight == other.suit_weight:
            if self.rank_weight > other.rank_weight:
                return True
        return False

    def modify_weight(self, new_suit_weight = None, new_rank_weight = None):
        """Modifies weight of card object"""
        if new_suit_weight:
            self.suit_weight = new_suit_weight
        if new_rank_weight:
            self.rank_weight = new_rank_weight

    def is_in_deck(self):
        """Return True if card is in a deck, else false"""
        return self.in_deck

    def get_suit(self):
        return self.suit

    def get_rank(self):
        return self.rank

    def get_suit_weight(self):
        return self.suit_weight

    def get_rank_weight(self):
        return self.rank_weight


texts:
I have defined the tag that can sit on all the pages of my website and be easily integrated into the admin tool. It is the broadest category with properties that are relevant for all pages.

Can you please tell me if it is written correctly?

I am concerned that the URL code line might be picked up as a circular link and as a result be penalised by the Search Engine:

    TITLE OF PAGE
    CONTENT OF PAGE
    <link itemprop="url" href="jmb-active.com/?page=URL-OF-THIS-PAGE">TITLE OF PAGE


texts:
I am working on a script that collects all comments from my DB and inserts them into a hash. I then do a collect on the comments hash and split the comments into two separate comment hashes (vid_comments & wall_comments)

w_hash = Hash.new
    w_hash["comments"] = []
    contender.subscriber.videos.collect { |v| w_hash["comments"] << v.comments.where("created_at > DATE_SUB( NOW(), INTERVAL 1 DAY)") }
    w_hash["comments"] << contender.profile.comments.where("created_at > DATE_SUB( NOW(), INTERVAL 1 DAY)")
    w_hash["comments"].delete_if { |x| x.blank? }

    w_hash["vid_comments"] = w_hash["comments"].collect { |c| !c.media_id.nil? }
    w_hash["wall_comments"] = w_hash["comments"].collect { |w| w.parent_id == 0 }
    w_hash.delete("comments")

Is there anyway to shorten the code? I am pretty new to Ruby (PHP import) so excuse my ignorance in things I may be doing wrong.


texts: Submitting callable tasks to a variable number of Threads in a ThreadPool

texts:
I am getting into multithreading and I was wondering if the code below is good practice or not. This is one of my first tries at multithreading.

Is there a better way of getting the values from the Future<Integer> rather than saving them in a list and summing them up afterwards?

 // Counting the number of prime-numbers from 'from' to 'to' by using 'nrThreas' amount of threads.
public static int countParallel(final int from, final int to, final int nrThreads) throws ExecutionException, InterruptedException {

    int count = 0;
    int startFrom = 0;
    int numbersPerThread = (to - from)/nrThreads;

    ExecutorService threadPool = Executors.newFixedThreadPool(nrThreads);

    Future<Integer> countHelper = null;

    // Storing the futures in order to get the Integers after the tasks were submitted to its threads
    ArrayList<Future<Integer>> helperList = new ArrayList<>();

    // determining the amount if prime-numbers between 1 and 20.000.000.
    for(int i = 0; i < nrThreads; i++)
    {
        countHelper = threadPool.submit(new PrimeCounter(startFrom, startFrom + numbersPerThread));

        // gets the next chunk to be examined
        startFrom += numbersPerThread + 1;

        helperList.add(countHelper);

    }

    threadPool.shutdown();

    // summing up the helper.get() from the list
    for(Future<Integer> helper : helperList)
    {
        count += helper.get();
    }

    return count;
}


texts: Is this the best way to reverse a string in C (not in place)?

texts:
Here is my code. Is there anyway to make it more efficient?

/*
IN: string to have characters reversed
OUT: string containing characters in reversed order
*/
char* reverStr(const char *str)
{
        char* revStr = (char*)malloc(strlen(str));
        int i;
        for(i = strlen(str)-1; i >= 0; i--)
            revStr[strlen(str)-1-i] = str[i];
        return revStr;
}


texts:
This is loosely based on one of W3_School samples:

<!DOCTYPE html>

Hello World!

The DOM is very useful!

This example demonstrates forEach() function

Please let me know if any improvements need (could) be done to the script.


texts:
I am working on this question and have my answer as following?

A string is encoded by performing the following sequence of actions:

Replace each character with its ASCII value representation.
Reverse the string.

For example, the table below shows the conversion from the string  "HelloWorld" to the ASCII string "7210110810811187111114108100":
Character
H  e   l   l   o    W  o   r   l   d
ASCII Value
72 101 108 108 111  87 111 114 108 100

The ASCII string is then reversed to get the encoded string "0018014111117811180180110127".
The characters in encoded string are within the range 10 - 126 which include special characters.

Example:
asciidecode('111111') => '\x0b\x0b\x0b' or 'oo'
because we can split the
input 111111 (after reverse back: '111111') like 11,11,11 or 111,111
from typing import List

def asciidecode(self, s: str) -> List:
    if not s: return ''
    s = s[::-1]
    n = len(s)
    ch_map = {str(i): chr(i) for i in range(10, 127)}
    dp = [[''] for _ in range(n + 1)]
    dp[2] = [ch_map[s[:2]]] if s[:2] in ch_map else ''
    dp[3] = [ch_map[s[:3]]] if s[:3] in ch_map else ''
    dp[4] = [dp[2][0] + ch_map[s[2:4]]] if s[2:4] in ch_map else ''
    for i in range(5, n + 1):
        p1 = s[i - 2: i]
        p2 = s[i - 3: i]
        tmp = []
        if p1 in ch_map:
            tmp += [i + ch_map[p1] for i in dp[i - 2]]
        if p2 in ch_map:
            tmp += [i + ch_map[p2] for i in dp[i - 3]]
        dp[i] = tmp
    return dp[-1]


texts: Representing the opening and closing time for a business

texts:
I have an OpenClose class which just represents the hours of operation of a business by the opening and closing time. It takes the opening and closing times as arguments to its constructor, and each is a datetime object.

The data is coming from an external source in a string, formatted like "HH:MM (AM|PM)-HH:MM (AM|PM)"

I have the following function to turn this into an OpenClose object:

def __get_times(self, hours):
    return OpenClose(*map(lambda x: datetime.strptime(x, "%I:%M %p"), hours.split("-")))

What do you think of this? Is it too much for one line? Too confusing? Should I split it up into multiple lines?

It sort of bugged me when doing it with multiple lines, but I can certainly see how this would be more readable, despite my hatred of explicitly doing the datetime calculation twice:

format = "%I:%M %p"
open_time, close_time = hours.split("-")
open_time = datetime.strptime(format)
close_time = datetime.strptime(format)
return OpenClose(open_time, close_time)

An alternative would be to use a combination of these approaches:

format = "%I:%M %p"
hours = hours.split("-")
open_time, close_time = map(lambda x: datetime.strptime(x, format), hours)
return OpenClose(open_time, close_time)

Which of these is best?


texts:
Posting my code for a LeetCode problem, if you'd like to review, please do so. Thank you for your time!
Problem
For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Example 1 :
Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3

Output: [1]

Example 2 :
Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
      \ | /
        3
        |
        4
        |
        5

Output: [3, 4]

Note:
According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Code
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cout.tie(NULL);
    return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
#include <unordered_set>
#include <algorithm>

static const struct Solution {
        using ValueType = std::uint_fast16_t;

        static const std::vector<int> findMinHeightTrees(
            const int n,
            const std::vector<std::vector<int>>& edges
        ) {
            std::vector<int> buff_a;
            std::vector<int> buff_b;
            std::vector<int>* ptr_a = &buff_a;
            std::vector<int>* ptr_b = &buff_b;

            if (n == 1) {
                buff_a.emplace_back(0);
                return buff_a;
            }

            if (n == 2) {
                buff_a.emplace_back(0);
                buff_a.emplace_back(1);
                return buff_a;
            }

            std::vector<Node> graph(n);

            for (const auto& edge : edges) {
                graph[edge[0]].neighbors.insert(edge[1]);
                graph[edge[1]].neighbors.insert(edge[0]);
            }

            for (ValueType node = 0; node < n; ++node) {
                if (graph[node].isLeaf()) {
                    ptr_a->emplace_back(node);
                }
            }

            while (true) {
                for (const auto& leaf : *ptr_a) {
                    for (const auto& node : graph[leaf].neighbors) {
                        graph[node].neighbors.erase(leaf);

                        if (graph[node].isLeaf()) {
                            ptr_b->emplace_back(node);
                        }
                    }
                }

                if (ptr_b->empty()) {
                    return *ptr_a;
                }

                ptr_a->clear();
                std::swap(ptr_a, ptr_b);
            }
        }

    private:
        static const struct Node {
            std::unordered_set<ValueType> neighbors;
            const bool isLeaf() {
                return std::size(neighbors) == 1;
            }
        };
};

References

Problem

Discuss

Wiki


texts:
I have an in memory list that I am joining to results from a query using entity framework.  My list will most likely never be greater than 2500 records.  The results from the database can fluctuate, depending on the filters used and it will grow in size.  I've been able to join the results successfully but it feels a bit sluggish and I worry as the database grows that it could get worse.  Is there anything I can do to make this more efficient?  Please let me know if you need any additional information.  Thanks!

var query = from e in _context.Employees
            where (...filters...)
            select e;

var employees = query.AsEnumerable();
var offices = _officeService.GetAllOffices();

var employeeData = from e in employees
                   join o in offices on e.Office equals o.Code
                   select new EmployeeData
                   {
                       EmployeeId = e.EmployeeId,
                       FullName = e.FullName,
                       Office = e.Office,
                       Area = o.Area,
                       Region = o.Region,
                       OfficeName = o.Name,
                       Position = e.Position,
                       Languages = e.Languages
                   };

return employeeData;


texts: Saving search history with many checks and validations inside

texts:
I am absolutely confused by saveSearchHistory function. It seems dirty and unobvious.
Should I refactor it, and how?

SearchHistory.java

public class SearchHistory {
  public SearchHistory(Long userId, Long groupId, String searchString) {
        this.userId = userId;
        this.groupId = groupId;
        this.searchString = searchString;
    }
  ...
  //getters + setters
  ...
  public void validate() throws InvalidParameterException{
    if (searchString == null || searchString.length() < MIN_WORD_SIZE) {
      throw new InvalidParameterException("Wrong search word min size: "+searchString);
    }

    if (searchString.length() > MAX_WORD_SIZE) {
        searchString = searchString.substring(0, MAX_WORD_SIZE - 1);
    }
}
}

SearchHistoryController.java

@Repository
public class SearchHistorControllerImpl implements SearchHistoryController {

    @PersistenceContext(unitName = "userPU")
    private EntityManager userEm;

    @Override
    @Transactional
    public List<SearchHistory> getSearchHistories(Long userId) {
        return emptyIfNull(userEm.createNamedQuery("getSearchHistories")
                .setParameter("userId", userId)
                .getResultList());
    }

    @Override
    @Transactional
    public SearchHistory saveSearchHistory(Long userId, Long groupId, String word) throws InvalidParameterException{
        SearchHistory searchHistory = new SearchHistory(userId, groupId, word);
        searchHistory.validate(); //throws InvalidParameterException

        removeSameWord(userId, groupId, word);
        checkWordsSizeLimit(userId, groupId);

        searchHistory = userEm.merge(searchHistory);
        userEm.flush();
        return searchHistory;
    }

    private void removeSameWord(Long userId, Long groupId, String word) {
        userEm.createNamedQuery("removeSameWord")
                .setParameter("userId", userId)
                .setParameter("groupId", groupId)
                .setParameter("searchString", word)
                .executeUpdate();
    }

    private void checkWordsSizeLimit(Long userId, Long groupId){
        List<SearchHistory> searchHistoryIds = userEm.createNamedQuery("findOldSearchWordsIds")
                .setParameter("userId", userId)
                .setParameter("groupId", groupId)
                .setFirstResult(MAX_HISTORY_SIZE - 1)
                .getResultList();

        if (!searchHistoryIds.isEmpty()) {
            userEm.createNamedQuery("removeOldWords")
                    .setParameter("searchHistoryIds", searchHistoryIds)
                    .executeUpdate();
        }
    }
}

SearchHistory.html.xml

...
<query name="findOldSearchWordsIds">
    SELECT id
     FROM SearchHistory as searchHistory
     WHERE
        searchHistory.userId = :userId
        AND searchHistory.groupId = :groupId
     ORDER BY searchHistory.searchTime DESC
</query>

<query name="removeOldWords">
    DELETE FROM SearchHistory as searchHistory
    WHERE searchHistory.id in ( :searchHistoryIds )
</query>

<query name="removeSameWord">
    DELETE FROM SearchHistory as searchHistory
    WHERE
        searchHistory.searchString = :searchString
        AND searchHistory.userId = :userId
        AND searchHistory.groupId = :groupId
</query>
...

FullSearch.java

 ...
public void commandExecute() {
    buildSearchResult();

    if (whetherSaveRequestInHistory) {
        final String filteredString = StringUtils.removeEnd(filterString, "*");
        try {
            searchHistoryManager.saveSearchHistory(context.getUserId, groupId, filteredString);
        } catch (InvalidParameterException ipe) {
            log.info("Unable to save Search History to db: "+ ipe.getMessage());
        }
    }
}

...


texts:
I don't have much experience with testing but I'm trying to make it part of my routine to develop better software.

The class below is a service class in Laravel. It needs to save a record on the database, saving the customer's customer_id, a route (location_id_from and location_id_to) and which location to bill (location_id_bill). The billing location can be null, in which case it will try to determine which one to use.

The code works, but I don't see how to completely unit test the newJob function. From what I've learned so far, I could replace the static methods whereId with an injected repository in the constructor.

Regarding the validation, I'm currently doing the validation, and if it doesn't passes, it will throw an exception with all errors messages.

So:

how to test the actual job creation without touching the database
is there a better way to do the validation?

class Job
{

    public function newJob(int $customer_id, int $location_id_from, int $location_id_to, int $location_id_bill): \App\Models\Customer\Job
    {
        $location_from = Location::whereId($location_id_from);
        $location_to = Location::whereId($location_id_to);

        if ($location_id_bill === null) {
            $location_bill = Location::whereId($location_id_bill);
        } else {
            $location_bill = new Location();
        }

        $errors = $this->newJobValidate($customer_id, $location_from, $location_to, $location_bill);
        if (count($errors)) {
            throw ValidationException::withMessages($errors);
        }

        $job = new \App\Models\Customer\Job();
        $job->customer_id = $customer_id;
        $job->location_id_from = $location_from->id;
        $job->location_id_to = $location_to->id;
        $job->location_id_bill = $location_bill->id;
        $job->save();

        return $job;
    }

    private function newJobValidate(int $customer_id, Location $location_from, Location $location_to, Location $location_bill)
    {
        $errors = [];

        if ($location_to->type === Location::TYPE_COMMON && $location_from->type === Location::TYPE_COMMON) {
            // same location, but not customer's
            $errors[] = __('job.errors.same_location_common');
        }

        if ($location_to->type === Location::TYPE_CUSTOMER && $location_to->customer->customer_id !== $customer_id ||
            $location_from->type === Location::TYPE_CUSTOMER && $location_from->customer->customer_id !== $customer_id) {
            $errors[] = __('job.errors.location_doesnt_belong_to_customer');
        }

        if ($location_bill->id === null) {
            if ($location_to->type === Location::TYPE_CUSTOMER && $location_from->type === Location::TYPE_CUSTOMER) {
               $errors[] = __('job.errors.must_select_bill_location');
            } elseif ($location_from->type === Location::TYPE_CUSTOMER) {
                $location_bill->id = $location_from->id;
            } else {
                $location_bill->id = $location_to->id;
            }
        }

        if ($location_bill->id !== $location_from->id && $location_bill->id !== $location_to->id) {
            $errors[] = __('job.errors.bill_location_different');
        }

        return $errors;
    }
}
```


texts:
Here is my source code for my very first app in Java. I am completely new to the language; any help and criticism is welcomed!
package com.company;

import java.util.*;

public class Main {

    public static float multiply(float a, float b)
    {
        return a*b;
    }

    public static float divide(float a, float b)
    {
        return a/b;
    }

    public static float addition(float a, float b)
    {
        return a+b;
    }

    public static float subtraction(float a, float b)
    {
        return a-b;
    }

    public static void main(String[] args)
    {
        Scanner scanner;
        float firstNum, secondNum, result;
        String operation;

        scanner = new Scanner(System.in);
        while(true){
            System.out.println("Select operation (*,/,+,-)");
            operation = scanner.next();
            if (operation.matches("[*/+-]")) {
                break;
            } else {
                System.out.println("Invalid operation");
            }
        }
        System.out.println("Type in first number");
        firstNum = scanner.nextFloat();

        System.out.println("Type in second number");
        secondNum = scanner.nextFloat();

        switch(operation)
        {
            case "*": result = multiply(firstNum, secondNum); break;
            case "/": result = divide(firstNum, secondNum); break;
            case "+": result = addition(firstNum, secondNum); break;
            case "-": result = subtraction(firstNum, secondNum); break;
            default: result = 0;
        }

        System.out.println("Result of your operation is " + result);
    }
}


texts: Select the n most frequent items from a pandas groupby dataframe


texts:
Background

A subclass of java.util.Properties attempts to recursively resolve configured properties:

prop_a=Prop A is ${prop_b}
prop_b=Prop B is ${prop_c}
prop_c=Prop C.

After reading the file, prop_a should be Prop A is Prop B is Prop C.

Property Reference Semantics

Nest properties are not allowed, making the following invalid:

${property_name_a ${property_name_b}}

A valid property is:

name=Text for ${property_a}, followed by ${property_b}.

Source Code

Code that handles parsing:

/**
 * This will throw an IllegalArgumentException if there are mismatched
 * braces.
 *
 * @param s - The string with zero or more ${} references to resolve.
 * @return The value of the string, with all substituted values made.
 */
public String resolve( String s ) {
  StringBuffer sb = new StringBuffer( 256 );
  Stack<StringBuffer> stack = new Stack<StringBuffer>();
  int len = s.length();

  for( int i = 0; i < len; i++ ) {
    char c = s.charAt( i );

    switch( c ) {
      case '$': {
        if( i + 1 < len && s.charAt( i + 1 ) == '{' ) {
          stack.push( sb );
          sb = new StringBuffer( 256 );
          i++;
        }
        break;
      }

      case '}': {
        if( stack.isEmpty() ) {
          throw new IllegalArgumentException( "unexpected '}'" );
        }

        String name = sb.toString();

        sb = stack.pop();
        sb.append( super.getProperty( name, null ) );
        break;
      }

      default: {
        sb.append( c );
        break;
      }
    }
  }

  if( !stack.isEmpty() ) {
    throw new IllegalArgumentException( "missing '}'" );
  }

  return sb.toString();
}

Question

How would you simplify the code and detect/avoid infinite recursion?


texts: Compare two arrays and show number of matches in a percentage value

texts:
I wrote this to be able to compare two different arrays to figure out how many words were in common as a percentage value.

The use case is that I have array a which is a list of the most commonly known and used words in a language (normally something like 2000 different words).
In array b I have the text.

The end result is the percentage usage of commonly used words as a means to figure out total readability of the text.

Note:
The intersect_array function is used elsewhere in the full fledged application.

The full functioning CodePen can be viewed here: http://codepen.io/MarkBuskbjerg/pen/rWWRbX?editors=0010

The JS goes like this:

tinymce.init({
  selector: '#myTextArea',
  height: 300,
  setup: function(ed) {
    ed.on('keyup', run);
  },
  init_instance_callback: "run"
});

// helper function that matches two arrays with each other
function intersect_arrays(a, b) {
  var sorted_a = a.concat().sort();
  var sorted_b = b.concat().sort();
  var common = [];
  var a_i = 0;
  var b_i = 0;

  while (a_i < a.length && b_i < b.length) {
    if (sorted_a[a_i] === sorted_b[b_i]) {
      common.push(sorted_a[a_i]);
      a_i++;
      b_i++;
    } else if (sorted_a[a_i] < sorted_b[b_i]) {
      a_i++;
    } else {
      b_i++;
    }
  }
  return common;
}

// simple addition function
function add(a, b) {
  return a + b;
}

function run(inst) {
  var sum;
  var percentageUsage;
  var words = ["store", "javascript", "hammertime"];
  var result = {};
  var text = tinyMCE.get('myTextArea').getContent({
      format: 'text'
  })
    .replace(/<([^>]+)>|[\.\+\?,\(\)"'\-\!\;\:]/ig, "")
    .toLowerCase()
    .split(/[\s]/)
    .filter(Boolean);
  var textLength = text.length;
  var match = intersect_arrays(text, words);

  for (var y = 0; y < match.length; y++) {
    for (var i = 0; i < text.length; ++i) {
       if(text[i] === match[y]) {
         if (!result[text[i]])
            result[text[i]] = 0;
            ++result[text[i]];
       }
    }
  }

 sum = Object
    .values(result)
    .reduce(add, 0);

   percentageUsage = textLength / sum;

   document.getElementById('totalWords').innerHTML = textLength;
   document.getElementById('totalPercentage').innerHTML = percentageUsage;
}

Any ideas as to how I can handle the code more effective, easier or just in a more beautiful way is more than welcome. I'm quite new at JS so still wanna learn a lot about best practice and stuff.


texts: Reading a file without blocking the main thread

texts:
Background Info: Running Python 3.6 on Windows 10

I have a text file parsed like this:

Ann Marie,Smith,ams@cia.com

There can over 100+ names in the text file.

Goal: When the program starts up, read in the text file using a thread, and load the data into a combobox. The main thread can continue loading other GUI components and isn't blocked by the method reading the text file.

import wx
import concurrent.futures

class MyDialog(wx.Frame):

    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(250, 270))

        self.panel = wx.Panel(self, size=(250, 270))
        self.combo = wx.ComboBox(self.panel, -1, pos=(60, 100))
        self.start_read_thread()

        # code to load other GUI components

        self.Centre()
        self.Show(True)

    def read_employees(self,read_file):
        emp_list = []
        with open(read_file) as f_obj:
            for line in f_obj:
                emp_list.append(line)
        wx.CallAfter(self.combo.Append, emp_list)

    def start_read_thread(self):
        filename = 'employees.txt'
        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
            executor.submit(self.read_employees, filename)

app = wx.App(False)
frame = MyDialog(None, "Sample editor")
app.MainLoop()


texts: Horrible nested if statement for changing CSS based on RadioButton selection

texts:
I'm writing away for this website, and I've come into a problem. I need to display only one td based on the corresponding radio button pressed. However, there are two 'master' radio buttons that dictate how many radio buttons are shown, and after that, which are selected. - if that makes any sense!

Now, I am only showing a very small snippet of what I actually have at the moment - this nested if statement goes on 5 more times. So, as you can probably imagine, it looks horrendous. And I'm not sure if there is a better way, maybe there is a way to create functions that can be called? What do you all think?

$('input:radio').change(function () {
                if (this.id == prodMoveRadio) {
                    if ($("#ExtIdTd").is(":visible") === true) {
                        $("#ExtIdTd").css({ visibility: "hidden" });
                        $("#LocIdTd").css({ visibility: "visible" });
                        $("#" + locIdRadio).prop("checked", true);
                        $("#ExtIdTr").css({ visibility: "hidden" });
                    }
                    else {
                        $("#MainContent_DetailsPanel").css({ visibility: "hidden" });
                        $("#ExtIdTr").css({ visibility: "hidden" });
                        $("#LocIdTd").css({ visibility: "visible" });
                        $("#" + locIdRadio).prop("checked", true);
                    }
                }
                else if (this.id == opMoveRadio) {
                    if ($("#ExtIdTd").is(":visible") === false) {
                        $("#ExtIdTr").css({ visibility: "visible" });
                        $("#ExtIdTd").css({ visibility: "visible" });
                    }
                    else {
                        $("#MainContent_DetailsPanel").css({ visibility: "visible" });
                        $("#" + extIdRadio).prop("checked", true);
                        $("#ExtIdTr").css({ visibility: "visible" });
                        $("#ExtIdTd").css({ visibility: "visible" });
                        $("#LocIdTd").css({ visibility: "hidden" });
                    }
                }

Edit

Would it be 'clean' to put a class onto the td's I need to hide, and hide that whole class then set only the visibility to visible on the td I require? Thoughts?


texts:
Just working through the questions on 4Clojure as I learn the language. This is my solution for #69. Would appreciate feedback as this one gave me a little trouble.

(fn merge-with2 [f m & ms]
   (let [update-or-add (fn update-or-add [m1 k f arg]
                          (let [x (get m1 k)]
                            (if (nil? x)
                              (conj m1 {k arg})
                              (update-in m1 [k] f arg))))]
   (loop [m1 m m2 (first ms) ms ms
          k (keys m2)]
     (if-not (map? m2)
       m1
       (recur (reduce #(update-or-add %1 %2 f (get m2 %2)) m1 k)
              (first (next ms))
              (next ms)
              (keys (first (next ms))))))))

I suspect that it would be possible to replace the loop/recur with a nested reduce, but I'm not quite sure how to implement it.


texts: Print all subsets and permutations of a string

texts:
The following code is designed to accept a string from the user that is at most 5 characters long. It will then find each possible substring of the string and print all possible permutations of each substring.

This is the first time I've done my utmost to prevent memory leaks by freeing every malloc. Even Valgrind seems to be happy, but I'm wondering if anyone here will be able to spot any bad practices, especially regarding memory allocation.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * createString();
void genSubsets(char *);
char * genBetween(char *, int, int);
void swap(char *, char *);
void permute(char *, int, int);
int alreadyPermuted(char *);
char ** permutations;
unsigned int numPermuted = 0;

int main()
{
    permutations = malloc(sizeof(char*) * 120);
    memset(permutations, '\0', 120);
    int index = 0;
    for(index = 0; index < 120; index++)
    {
        permutations[index] = malloc(sizeof(char) * 6);
        memset(permutations[index], '\0', 6);
    }
    // 120 is 5!
    //So this will be the maximum space needed
    char * string  = createString();
    scanf("%5[^\n]s", string);
//  printf("%s\n", string);
    genSubsets(string);
    free(string);

    for(index = 0; index < 120; index++)
    {
        free(permutations[index]);
    }
    free(permutations);
    return 0;
}
char * createString()
{
    char * string = malloc(sizeof(char) * 6);
    if(string)
    {
        memset(string,'\0',6);
        return string;
    }
    else
    {
        puts("Malloc failed!");
        abort();
    }
}
void genSubsets(char * string)
{
    int counter1;
    int counter2;
    int size = strlen(string);
    //permute(string, 0, size);
    for(counter1 = 0; counter1 < size; counter1++)
    {
        for(counter2 = counter1; counter2 < size; counter2++)
        {
            char * generatedSubString = genBetween(string, counter1, counter2);
            if(generatedSubString[0] != '\0' && numPermuted < 120)
            {
        //      printf("Substring : %s\n", generatedSubString);
                permute(generatedSubString, 0 , strlen(generatedSubString));
            }
            free(generatedSubString);
        }
    }
}
char * genBetween(char * string, int begin, int end)
{
    char * subString = createString();
    int counter;
    if(!subString)
    {
        puts("Realloc failed.");
        abort();
    }
    for(counter = begin; counter <= end; counter++)
    {
        subString[counter-begin] = string[counter];
    }
    //free(string);
    return subString;
}
void swap(char * first, char * second)
{
    char temp = *first;
    *first = *second;
    *second = temp;
}
void permute(char * string, int begin, int end)
{
    int count = 0;
    if(begin == end && strlen(string) > 0 && !alreadyPermuted(string) && numPermuted < 120)
    {
        printf("%s\n", string);
        strcpy(permutations[numPermuted], string);
        numPermuted++;
        return;
    }
    for(count = begin; count <= end; count++)
    {
        swap(string+begin, string+count);
        permute(string, begin+1, end);
        swap(string+begin, string+count);
    }

}
int alreadyPermuted(char * string)
{
    int count = 0;
    for(count = 0;numPermuted < 120 &&  count <= numPermuted; count++)
    {
        if(strcmp(permutations[count], string)==0)
        {
            return 1;
        }
    }
    return 0;
}


texts: Automatically scan and resize buffer in C

texts:
I have a simple function that reads character by character from stdin, while resizing the buffer whenever needed. The implementation will only allow 256 characters to be read, but that can easily be modified. Are there an obvious problems with this function? ie. it relies on undefined behaviour. And how can performance be improved?

void scan(char **buffer) {
char *newBuffer;
unsigned char i = 0;
unsigned char size = 1;
*buffer = malloc(16);
(*buffer)[0] = 0;
while (1) {
    (*buffer)[i] = getchar();
    if ((*buffer)[i] == '\n') {
        (*buffer)[i] = 0;
        return;
    }
    if (i >= (size * 16)) {
        size++;
        newBuffer = realloc(*buffer, size * 16);
        *buffer = newBuffer;
    }
    i++;
}
}


texts: Memoization-based puzzle solution - sums in a triangle

texts:
I am trying to solve a problem at Codechef. As I am new to programming, I am not familiar with dynamic programming. However, I do know the basics of recursion and memoization. Hence I implemented a solution to the above mentioned problem. The problem with my solution is that it exceeds the time limit given. As far as I can guess, the problem seems to be with my memoization logic. Please help me optimize the code.

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

typedef vector<int> vector1D ;
typedef vector<vector1D > vector2D ; // Two Dimensional vector

int rownum;
int noOfCalls = 0;
vector2D a;
vector2D cache; // The cache to implement memoization

int solve (int i, int j)
{

    int t1,t2,total;
    if( i > rownum-1 ) {
        return 0;
    }
    else {
        if (cache[i][j] != 0 && ( i < 50) && ( j < 50)) { //for small values use memoization
            return cache[i][j];
        }
        t1 = solve(i+1,j);
        t2 = solve(i+1,j+1);
        total = max(t1,t2) + a[i][j];
        cache[i][j] = total;//store in cache
    }
    return total;
}
int main(int argc, char *argv[])
{
    int tries;
    cin>>tries;
    while(tries--) {
        cin>>rownum;
        int temp = rownum;
        for ( int i = 0 ; i < rownum ; i++) {
            a.push_back(vector1D(rownum,0));//initialize memory
        }
        for ( int j = 0; j < 10; j++) {
            cache.push_back(vector1D(10,0));//initialize cache
        }
        for ( int i = 0; i < rownum; i++) {
            for ( int j = 0 ; j <= i; j++) {
                cin>>a[i][j];
            }
        }
    cout<<solve(0,0)<<endl;//call the solving function
    cache.clear();
    }
    return 0;
}


texts:
I was in an interview and the guy asked me to do the typical FizzBuzz question of printing numbers 1-100, but for each factor of 3 print Fizz, each factor of 5 print Buzz, and each factor of both print FizzBuzz. I wrote the following:

public static void fizzbuzz(){
    for(int i=1;i<=100;i++){
        if(i%15 == 0){
            System.out.println("FizzBuzz");
        } else if (i%3 == 0) {
            System.out.println("Fizz");
        } else if (i%5 == 0) {
            System.out.println("Buzz");
        } else {
            System.out.println(i);
        }
    }
}

The interviewer had me change my answer so that it looked like this:

public static void fizzbuzz(){
    for(int i=1;i<=100;i++){
        String str = "";
        if(i%3 == 0){
            str = "Fizz";
        }
        if(i%5 == 0){
            str += "Buzz";
        }
        if(str.equals("")){
            str = i;
        }
        System.out.println(str);
    }
}

Then he asked me which I would prefer if I was handed that code, and said there was no wrong answer (which I should have known was a lie), but I foolishly said mine because it was easier for me to look and see that something different was happening for factors of 15 in my code by just glancing over it, whereas without actually looping through the code in my mind, I wouldn't know that about the second version.

Anyways, my question is, is his version better for some reason that I am missing? I'm at entry level skill, so I honestly think that both versions are completely identical efficiency and readability wise.


texts: Helper method to extract a specific string from long message

texts:
private string ExtractExceptionMesssage(string exceptionMessage)
{
    const string startWord = "Message&gt";
    int startWordLength = startWord.Length;
    const string endWord = "/Message&gt";
    var length = exceptionMessage.Length;
    int index = 0;
    var sb = new StringBuilder();

    while (index < length)
    {
        var startIndex = exceptionMessage.IndexOf(startWord, index, StringComparison.Ordinal);
        if (startIndex < 0)
            break;
        var endIndex = exceptionMessage.IndexOf(endWord, startIndex, StringComparison.Ordinal);
        if (endIndex < 0)
        {
            break;
        }
        var len = endIndex - 4 - (startIndex + startWord.Length); // -4 is ".&lt"
        sb.AppendLine(exceptionMessage.Substring(startIndex + startWordLength, len));
        index = endIndex + endWord.Length + 1;
    }

    if (sb.Length == 0) sb.Append("Unknown error");
    return sb.ToString();
}

I'll appreciate any idea of how to make it better


texts: Display a Text() with a foreground color based on a condition

texts:
I decided to write a simple tab bar for macOS using Swift.
tabs.swift
import SwiftUI
import Foundation
import Combine

class ViewRouter: ObservableObject {
  @Published var currentView = "home"
}

struct Tabs: View {

  @ObservedObject var viewRouter = ViewRouter()

  var body: some View {
    GeometryReader { geometry in
      VStack {
        if self.viewRouter.currentView == "home" {
          Text("Home")
        } else if self.viewRouter.currentView == "settings" {
          Text("Settings")
        }
        Spacer()

        HStack {
          { () -> Text in
            if self.viewRouter.currentView == "home" {
              return Text("Home").foregroundColor(Color.blue)
            } else {
              return Text("Home")
            }
          }()
          .onTapGesture {
            self.viewRouter.currentView = "home"
          }

          { () -> Text in
            if self.viewRouter.currentView == "settings" {
              return Text("Settings").foregroundColor(Color.blue)
            } else {
              return Text("Settings")
            }
          }()
          .onTapGesture {
            self.viewRouter.currentView = "settings"
          }
        }
      }.edgesIgnoringSafeArea(.bottom).padding(20)
    }
  }
}

In ContentView.swift, I just display this using Tabs() in the ContentView struct.
In the HStack, I use two anonymous functions to give the text in the tab bar a blue color when that item is selected:
{ () -> Text in
  if self.viewRouter.currentView == "home" {
    return Text("Home").foregroundColor(Color.blue)
  } else {
    return Text("Home")
  }
}()
  .onTapGesture {
    self.viewRouter.currentView = "home"
  }

I also do this for the second item in the tab bar.
Is this the best (fastest and most concise) way to do this, or is there a better way?