texts:
I wrote simple lock-free collection class for saving items from multithreading code. I did it just for fun and experience. Can you check my code for potentially problems please?

    public class InputBox<T>
    {
        private BoxItem<T> _current;

        public InputBox()
        {
            _current = null;
        }

        public void Add(T value)
        {
            var nextItem = new BoxItem<T>(value);
            BoxItem<T> initialItem = null;
            do
            {
                initialItem = _current;
                nextItem.Next = _current;
            } while (initialItem != Interlocked.CompareExchange(ref _current,
                                                                nextItem,
                                                                initialItem));
        }

        public bool TryAdd(T value)
        {
            var initialItem = _current;
            return initialItem ==
                   Interlocked.CompareExchange(ref _current,
                                               new BoxItem<T>(value, _current),
                                               initialItem);
        }

        public BoxResultCollection<T> TakeAll()
        {
            return new BoxResultCollection<T>(_current);
        }
    }

    internal sealed class BoxItem<T>
    {
        private readonly T _value;
        private BoxItem<T> _next;

        internal BoxItem(T value)
            :this(value, null)
        {
            // empty
        }

        internal BoxItem(T value, BoxItem<T> next)
        {
            _value = value;
            _next = next;
        }

        internal T Value
        {
            get { return _value; }
        }

        internal BoxItem<T> Next
        {
            get { return _next; }
            set { _next = value; }
        }
    }

    public class BoxResultCollection<T> : IEnumerable<T>
    {
        private readonly BoxItem<T> _root;

        internal BoxResultCollection(BoxItem<T> root)
        {
            _root = root;
        }

        public IEnumerator<T> GetEnumerator()
        {
            var current = _root;

            while (current != null)
            {
                yield return current.Value;
                current = current.Next;
            }

            yield break;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public bool IsEmpty
        {
            get { return _root == null; }
        }

        public IEnumerable<T> ToEnumerable()
        {
            return this;
        }
    }


texts:
I made some code to test my personal servers uptime. It logs in to my router page and sees if it returns status 200. A cron job runs it every 5 minutes. Please let me know if I can make the code more efficient.

<?php
//Date
date_default_timezone_set('America/Los_Angeles');
$date = date('m/d h:i:s a', time());

//Output
$myFile = dirname(__FILE__) . "/output.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");

//Count #
$count_file = dirname(__FILE__) . "/OK.txt";
$fil = fopen($count_file, r);
$dat = fread($fil, filesize($count_file));
fclose($fil);
$fil = fopen($count_file, w);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "MYURL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "USER:PASSWORD");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if($retcode==200){
    //fwrite($fh, "$date\tOK\n");
    $OK = $dat + 1;
    fwrite($fil, $OK);
    echo "$date\tOK\n";
    fclose($fh);
} else {
    fwrite($fh, "$date\t\tDOWN\n");
    echo "$date\tDOWN\n";
    fclose($fh);
}

//Count OK/DOWN
$read = file_get_contents($myFile);
$DOWN = preg_match_all("/DOWN/", $read, $matches) - 1;
$UP = 100*bcdiv($OK,$OK+$DOWN,4);

//Remove first line
$read = file($myFile);
array_shift($read);
$server_up = "Server Uptime: " . $UP . "%\nOK: " . $OK . ", DOWN: " . $DOWN . "\n";
$read[0] = $server_up;
file_put_contents($myFile, $read);

?>

One thing I wanted to do was to somehow assign $OK to a variable and retrieve it the next time the page is loaded but I do not think PHP can do this so I saved it to an external file (OK.txt) and I read the value every time and increment it every time my site returns 200.

Here is a sample output.txt file:

Server Uptime: 92.5%
OK: 37, DOWN: 3
09/30 06:48:28 pm DOWN
09/30 06:48:28 pm DOWN
09/30 06:48:28 pm DOWN


texts: Linked List in Java (Garbage Collection)

texts:
So I'm implementing a linked list in Java, and so far it looks like this:

public class List <T> {

    private class Node {
        T value;
        Node next;
    }

    private Node node_at(int n) {
        Node seeker = front;
        for (int i = 0; i < n; i++) {
            seeker = seeker.next;
        }
        return seeker;
    }

    Node front;
    int length;

    public int length() {
        return length;
    }

    public void insert(int index, T o) {
        if (index == 0) {
            Node n = new Node();
            n.value = o;
            n.next = node_at(0);
            front = n;
        } else {
            Node n1 = node_at(index-1);
            Node n2 = new Node();
            n2.next = n1.next;
            n1.next = n2;
            n2.value = o;
        }
        length++;
    }
    public void append(T o) {
        Node n = node_at(length);
        n.value = o;
        n.next = new Node();
        length++;
    }
    public void append(List<T> l) {
        node_at(length-1).next = l.front; // specific area of interest
        length += l.length;
    }

    public T at(int n) {
        Node seeker = node_at(n);
        return seeker.value;
    }

    List() {
        length = 0;
        front = new Node();
    }
}

The line that I marked specific area of interest is effectively cutting off a node (the last node in the receiver), leaving it homeless. Is that node going to get garbage collected?


texts: Customizing errors based on HTTP status code in golang

texts:
I want to collect errors and its causes by defining custom errors (HTTP status 40x & 50x). For example, if user's request was bad, I want more specific reasons for the error.

A customized error has its own code (not equal to HTTP status code, but related since the code format is $HTTP_STATUS (3-digit) + own code (2-digit). The reason it has its own error code is that I store this error data (as JSON) to Elasticsearch and query for each error's occurrences in Kibana.

I'd like to get reviews on the following codes. Best practice or any small tips for custom errors are welcome.

error.go :

package main

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

const (
    codeEmptyNameErr        = 40001
    codeInvalidAgeErr       = 40002
    codeMethodNotAllowedErr = 40501
    codeJSONMarshalErr      = 50001
)

// MyError contains custom code, error message, and HTTP status code.
type MyError struct {
    HTTPStatus int    `json:"-"`
    Code       int    `json:"code"`
    Message    string `json:"message"`
}

func (e *MyError) Error() string {
    return fmt.Sprintf("HTTPStatus: %v, Code: %v, Message: %q",
        e.HTTPStatus, e.Code, e.Message)
}

// WriteToResponse writes response for the error.
func (e *MyError) WriteToResponse(w http.ResponseWriter) {
    w.WriteHeader(e.HTTPStatus)
    fmt.Fprintf(w, e.ToJSON())
    // TODO: store e.ToJSON() to ElasticSearch for future analysis
}

// ToJSON returns JSON string for a MyError.
func (e *MyError) ToJSON() string {
    j, err := json.Marshal(e)
    if err != nil {
        return `{"code":50099,"message":"ScrapError.JSONStr: json.Marshal() failed"}`
    }
    return string(j)
}

// EmptyNameErr .
func EmptyNameErr(name string) *MyError {
    return &MyError{
        HTTPStatus: http.StatusBadRequest,
        Code:       codeEmptyNameErr,
        Message:    "name shoud not be empty",
    }
}

// InvalidAgeErr .
func InvalidAgeErr(age string) *MyError {
    return &MyError{
        HTTPStatus: http.StatusBadRequest,
        Code:       codeInvalidAgeErr,
        Message:    fmt.Sprintf("invalid age: %q", age),
    }
}

// MethodNotAllowedErr .
func MethodNotAllowedErr(method string) *MyError {
    return &MyError{
        HTTPStatus: http.StatusMethodNotAllowed,
        Code:       codeMethodNotAllowedErr,
        Message:    fmt.Sprintf("method %q is not allowed", method),
    }
}

// JSONMarshalErr .
func JSONMarshalErr(err error) *MyError {
    return &MyError{
        HTTPStatus: http.StatusInternalServerError,
        Code:       codeJSONMarshalErr,
        Message:    err.Error(),
    }
}

main.go :

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strconv"
)

func main() {
    // request example:
    // curl -X POST -d 'name=John%20Doe&age=10' localhost:8083/persons
    http.HandleFunc("/persons", newPersonHandler)
    log.Fatal(http.ListenAndServe(":8083", nil))
}

func newPersonHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    switch r.Method {
    case "POST":
        name, ageStr := r.FormValue("name"), r.FormValue("age")
        if name == "" {
            EmptyNameErr(name).WriteToResponse(w)
            return
        }
        age, err := strconv.ParseUint(ageStr, 10, 64)
        if err != nil {
            InvalidAgeErr(ageStr).WriteToResponse(w)
            return
        }

        resBody, err := json.Marshal(person{name, age})
        if err != nil {
            JSONMarshalErr(err).WriteToResponse(w)
            return
        }

        fmt.Fprintf(w, string(resBody))
    default:
        MethodNotAllowedErr(r.Method).WriteToResponse(w)
    }
}

type person struct {
    Name string `json:"name"`
    Age  uint64 `json:"age"`
}


texts: Script to execute arbitrary command on each Git project in a directory

texts:
The idea is simple, most people have some one directory containing all their projects as subdirectories. When you are in the top directory and you run this script like so for-each-git.sh git status it will run the command git status in each of the folders. I have another script called git-ffwd that fetches all remotes and fast forward updates them which I usually run each morning with this script.

#!/bin/bash
for dir in $(find . -maxdepth 1 -type d); do
    (
        cd ${dir}
        if [ -d ".git" ]; then
            pwd
            "$@"
            echo
        fi
    )
done

Some explanation:

The parenthesis is so we are able to easily go back to the project directory in case the commands you push in run cd or something. (It makes a subshell.)
pwd is so we know for sure which directory is being worked on and the echo is just so a new line separates everything a little more.

I know this is a small script but I am new-ish to writing Bash scripts and want to learn.

The lines pwd; "$@"; echo seem a little ugly, though they do work. Also I can't pass multiple commands in with a ; like echo hey; echo bye because the ; ends the statement in the "$@" line, so I am wondering if there's a better way to write that line (or pass them in).


texts:
I wrote the Sierpinski’s Gasket Triangle in JavaScript, but I feel the code can be better, especially from L32 to L47. Could you make it more organized?

var canvas = document.getElementById('chaos');
var ctx = canvas.getContext('2d');

const GenerateRand = () => Math.floor(Math.random() * 7);
const updateDot = (x, y, point) => {
  let X = Math.min(x,point.x)+(Math.max(x,point.x)-Math.min(x,point.x))/2;
  let Y = Math.min(y,point.y)+(Math.max(y,point.y)-Math.min(y,point.y))/2;
  return {x: X, y: Y};
}
const createDot = (obj) => {
  ctx.beginPath();
  ctx.arc(obj.x, obj.y, 1, 0, 2 * Math.PI, false);
  ctx.lineWidth = 1;
  ctx.strokeStyle = '#fc3';
  ctx.stroke();
}

const pA = {x: canvas.width/2, y: 5};
const pB = {x: 5, y: canvas.height-5}
const pC = {x: canvas.width-5, y: canvas.height-5}

createDot(pA);
createDot(pB);
createDot(pC);

const begin = (iterations) => {
  let x = canvas.width/4;
  let y = canvas.height/2;
    for(let i=0;i<iterations;i++) {
    createDot({x, y});
    let randN = GenerateRand();
    if(randN == 1 || randN == 2) {
      const currentDot = updateDot(x, y, pA);
      x = currentDot.x;
      y = currentDot.y;
    }
    else if(randN == 3 || randN == 4) {
      const currentDot = updateDot(x, y, pB);
      x = currentDot.x;
      y = currentDot.y;
    }
    else if(randN == 5 || randN == 6){
      const currentDot = updateDot(x, y, pC);
      x = currentDot.x;
      y = currentDot.y;
    }
  }
}

let time=0;
let timer = setInterval(() => {
   if(time >= 500) return clearInterval(timer)
   begin(500);
   time++;
}, 200);
<div>
      <canvas id="chaos" width="500" height="500"></canvas>
</div>


texts:
I supplied the following code as an answer to this question on SO, but I was wondering if there was a better way to write out all those array loops (i.e. perhaps using a Collection/Dictionary?) It seems clunky/cumbersome as-is.

Function ContainedInMonth(OriginalStartDate As String, _
    OriginalEndDate As String) As Boolean

    Dim MonthSet As Variant
    Dim AryCounter As Integer, ISOOffset As Integer
    Dim StartYear As Integer, EndYear As Integer
    Dim StartWeek As Integer, EndWeek As Integer
    Dim StartDay As Integer, EndDay As Integer
    Dim FormattedStartDate As Date, FormattedEndDate As Date

    ' This section may (will) vary, depending on your data.
    ' I'm assuming "YYYY-WW" is passed...
    ' Also, error/formatting checking for these values is needed
    ' and wil differ depending on that format.
    StartYear = Val(Left(OriginalStartDate, 4))
    StartWeek = Val(Right(OriginalStartDate, 2))
    EndYear = Val(Left(OriginalEndDate, 4))
    EndWeek = Val(Right(OriginalEndDate, 2))

    If StartYear <> EndYear Or StartWeek > EndWeek Then
        ContainedInMonth = False
    ElseIf StartWeek = EndWeek Then
        ContainedInMonth = True
    Else

        ' Using the calculation from wikipedia. Honestly, I'm not sure that
        ' I understand this bit, but it seemed to work for my test cases.
        ISOOffset = Weekday(CDate("1/4/" & StartYear), vbMonday) + 3
        StartDay = (StartWeek * 7) - ISOOffset ' Adding 0 for start of week
        EndDay = (EndWeek * 7) + 6 - ISOOffset ' Adding 6 for end of week

        ' Set the starting day for each month, depending on leap year.
        If StartYear Mod 4 = 0 Then
            MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
        Else
            MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
        End If

        FormattedStartDate = 0:FormattedEndDate = 0

        For AryCounter = 11 To 0 Step -1
            If StartDay > MonthSet(AryCounter) And FormattedStartDate = 0 Then
                ' Using MM/DD/YYYY format - this may be different for you
                FormattedStartDate = CDate(AryCounter + 1 & _
                    "/" & StartDay - MonthSet(AryCounter) & "/" & StartYear)
            End If

            If EndDay > MonthSet(AryCounter) And FormattedEndDate = 0 Then
                FormattedEndDate = CDate(AryCounter + 1 & _
                    "/" & EndDay - MonthSet(AryCounter) & "/" & EndYear)
            End If
        Next AryCounter

        ContainedInMonth = IIf(Month(FormattedStartDate) = Month(FormattedEndDate), True, False)
    End If

End Function

I had considered something like:

If StartYear Mod 4 = 0 Then
    TempArray = LeapSet
Else
    TempArray = NonLeapSet
End If

'Now do loops


texts:
I was refactoring an ugly piece of code, and I'm unsure if there is a better way of doing this, and whether I'm overdoing it with streams.

Basically I get a bunch of columns, which should be grouped by the name of the sheet they belong to, so that I can return a map of sheet names to a set of column names.

BTW, I can't change the return type (I know it should be a MultiMap).

@Override
public Map<String, Set<String>> getReferencedColumnNames(String columnName) {
    return _formulaSheetSchema.column(columnName).get().formula()
            .computeReferencedColumns(getSheetName()).stream()
            .collect(groupingBy(
                    ColumnRef::sheetName,
                    LinkedHashMap::new,
                    collectingAndThen(toSet(), set ->
                            set.stream().map(ColumnRef::columnName).collect(toSet()))));
}


texts: Short square matrix class in C++ using an array

texts:
I'm a novice at C++ in comparison with other languages, so as an exercise I wrote a square Matrix class that doesn't use STL.

#ifndef MATRIX_H
#define MATRIX_H
#include <initializer_list>
#include <algorithm>

class Matrix {
public:
  Matrix(std::size_t sz) : elements{new int[sz * sz]}, size{sz} {}
  Matrix(std::size_t sz, std::initializer_list<int> elem) : Matrix(sz) {
    std::copy(elem.begin(), elem.end(), elements);
  }
  ~Matrix() { delete[] elements; }

  /** Get the matrix element at row i and column j. */
  int get(std::size_t i, std::size_t j) const {
    return elements[convert(i, j)];
  }

  /** Set the value of the matrix at row i and column j and return the old value. */
  int set(std::size_t i, std::size_t j, int new_value) {
    std::size_t idx = convert(i, j);
    int old_value = elements[idx];
    elements[idx] = new_value;
    return old_value;
  }

  std::size_t width() const {
    return size;
  }

private:
  int *elements;
  std::size_t size;

  inline std::size_t convert(std::size_t i, std::size_t j) const {
    if (i >= size || j >= size) {
      throw std::exception("Matrix indices out of bounds");
    }
    std::size_t idx = i * size + j;
    return idx;
  }
};

#endif

Critiques are welcome!  In particular, I'd be happy to get advice on the following:

Is this an appropriate usage of exception handling?  Is there a better option than just tossing up a std::exception if the matrix indices are out of bounds?
Do the constructors and destructors make sense?
Any general comments on writing in idiomatic C++ style.


texts: OOP Decision Maker Class - ServerArbiter

texts:
I am writing a ServerArbiter, the job of which is to make a decision about which server to "choose" given a set of rules. The aim is to be able to add / remove rules at will - for ease of future maintenance. My language of choice is php, so please bear this in mind when answering.

Basically, a server will be chosen depending on various factors. One may be 'server load'. Imagine this arbiter is used to decide which server to add a torrent to - it will choose the server with the least number of torrents in the download queue.

Architecture

My current architecture for this solution consists of a ServerArbiter object:

public function __construct(RuleSet $ruleSet, array $servers);

The RuleSet is effectively just a list of Rule objects that implements \Iterator so it can be foreach()d around.

public function addRule(Rule $rule);

And the actual Rule objects implement the Rule interface:

public function resolve(Server $server);

A Server is just a (doctrine) Entity - that is, it contains class members, setters and getters, and some validation. These properties are populated with data from the servers database table. One of the properties is ipAddress.

Rules

I currently have rules such as the ServerActiveRule, which is just a property that is returned.

class ServerActiveRule implements Rule
{
    /**
     * {@inheritdoc}
     */
    public function resolve(Server $server)
    {
        return $server->isActive();
    }
}

For torrents example described above, I was going to have a ServerDownloadsComparisonRule:

class ServerDownloadsComparisonRule
{
    /**
     * @var Server[]
     */
    private $servers;

    public function __construct(array $servers)
    {
        // -- SNIP --
        // Make sure each $server is instance of Server entity
        // -- SNIP --
    }

    public function resolve(Server $server)
    {
        // I'm guessing this is where I will compare the downloads to get the one with the least number of downloads in
        // I haven't implemented this yet
    }
}

ServerArbiter::decide()

Finally, this is the current method I have of deciding which Server entity to return.

/**
 * Run each Server against each Rule in the RuleSet and return the Server that matched the most rules
 *
 * @return Server The one Server to rule them all
 *
 * @note If two servers match the same number of rules successfully, the first one will be returned
 */
public function decide()
{
    $decisions = [];

    /** @var Rule $rule */
    foreach ($this->ruleSet as $rule)
    {
        foreach ($this->servers as $server)
        {
            if (!array_key_exists($server->getId(), $decisions))
            {
                $decisions[$server->getId()]['successes'] = 0;
            }

            if ($rule->resolve($server))
            {
                $decisions[$server->getId()]['successes']++;
            }
        }
    }

    $decision = array_search(max($decisions), $decisions);

    return $decision;
}

Questions

Simple rules that return true / false are fine. But as soon as ServerDownloadsComparisonRule gets thrown into the mix, it has a different constructor requiring an array of servers. This spells mayhem for the ServerArbiter::decide() method as it's now doing a lot more work. How can I refactor all this to make it much simpler to let each rule individually do what it needs to do?
Obviously my rule for checking downloads will have to connect to the server via it's IP address. Is it okay to Inject a dependency to perform this data retrieval just for the rule?
How is the architecture, what can I do differently? What is stupid about it?
Is there anything else that I can do better?

Extra Info

I'm using a recursively instantiating dependency injection container. This means I can typehint for any object anywhere in my application, including in this service, and the object will automatically be passed in for me. Therefore, I don't have to worry about wiring - it needs to be more SOLID and simple to modify in the future.


texts:
Depending on the width of the screen the JavaScript animates a node and then loops another animation.

I'm trying to understand DRY but my JavaScript skills aren't quite up to scratch to get this code as optimised as possible. I'm also wanting to implement $(window).resize(function() { }); to detect this change without a refresh. Is using constants the best way to optimise this code? If so, how would this be achieved?

jsFiddle

'use strict';

/*jslint browser: true*/
/*global $, jQuery*/

/*
--------------------------------------------------------
VARIABLES
--------------------------------------------------------
*/

var width       = $(window).width(),        // window width
    down_dur,
    left_dur,
    up_dur,
    right_dur;

/*
--------------------------------------------------------
FUNCTION CODE TO BE EXECUTED
--------------------------------------------------------
*/

function animate_node(down, down_dur, left, left_dur, up, up_dur, right, right_dur) {

    down        = down  + 'px';
    left        = left  + 'px';
    up          = up    + 'px';
    right       = right + 'px';

    $('.node')
        .animate({top: down},
            { duration: down_dur, easing : 'linear', queue: true })
        .animate({marginLeft: left},
            { duration: left_dur, easing : 'linear', queue: true })
        .animate({top: up},
            { duration: up_dur, easing : 'linear', queue: true })
        .animate({marginLeft: right},
            { duration: right_dur, easing : 'linear', queue: true });
}

/*
--------------------------------------------------------
CALL THE FUNCTIONS
--------------------------------------------------------
*/

// fire the following when the dom is ready
$(function () {

    if (width > 840) {
        $('.node').each(function(i) {
            $(this).delay(1500 * (i + 1))
                .animate({top: '157px'},
                    { duration: 1000, easing : 'linear', queue: true })
                .animate({marginLeft: '264px'},
                    { duration: 1000, easing : 'linear', queue: true });
        });
        animate_node(425, 2000, -284, 2000, 157, 2000, 264, 2000);
        setInterval(function() {
            animate_node(425, 2000, -284, 2000, 157, 2000, 264, 2000);
        }, 2000);
    } else if (width < 840 && width > 600) {
        $('.node').each(function(i) {
            $(this).delay(1500 * (i + 1))
                .animate({top: '165px'},
                    { duration: 1000, easing : 'linear', queue: true })
                .animate({marginLeft: '179px'},
                    { duration: 1000, easing : 'linear', queue: true });
        });
        animate_node(490, 2000, -199, 2000, 165, 2000, 179, 2000);
        setInterval(function() {
            animate_node(490, 2000, -199, 2000, 165, 2000, 179, 2000);
        }, 2000);
    } else if ((!(document.documentElement.hasOwnProperty('ontouchstart'))) &&
            width < 600) {
        $('.node').each(function(i) {
            $(this).delay(1833.333 * (i + 1));
        });
        animate_node(1095, 5000, 102, 500, 165, 5000, -9, 500);
        setInterval(function() {
            animate_node(1095, 5000, 102, 500, 165, 5000, -9, 500);
        }, 2000);
    }

});


texts: Concise and exception-prone method for running method on component

texts:
I have a list of Components. When an actor is connected, I want to run onActorConnected on each component. However, if a component's onActorConnected method throws an exception for whatever reason, this cannot affect other components' execution of that method.
Here's a minimized extract of my code:
import static java.lang.String.format;

public class Match {
    private final Set<Actor> actors = ...;
    private final List<MatchComponent> components = ...;

    public void connectActor(@NotNull Actor actor) {
        if (actors.contains(actor))
            throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));

        actors.add(actor);

        // This is hard to read!
        // But I will be doing this in a lot of places, so I want to keep in short.
        components.forEach(c-> runOrLogException(() -> c.onActorConnect(actor), c.getName(), "onActorConnect"));
    }

    // The same pattern will be used in `disconnectActor` and other similar methods.

    private void runOrLogException(@NotNull Runnable runnable, @NotNull String instanceName, @NotNull String methodName) {
        try {
            runnable.run();
        } catch (Exception e) {
            logger.log(Level.SEVERE, format("'%s' on '%s' in '%s' threw an exception.", methodName, instanceName, this.getName()), e);
        }
    }
}

My question primarily is about whether this is a good way to do it? I fear I might be missing some way of using Java's lambdas to make this cleaner.
Bonus question is whether it's considered good practice to throw an exception if an "actor" is already connected. I considered just returning false if this is the case, but I do not ever expect myself to call this method if an actor is already connected. If that happens, something has gone wrong somewhere. I instead provide an isActorConnected method that the caller can use to explicitly handle such a case.


texts: Eliminate nested HTML elements for jQuery animation?

texts:
Background

When a user leaves a page, if they haven't submitted form data, a button is animated to draw the user's attention. (This is a poor UX choice--all the form data should be submitted--but it is what I have to work with at the moment).

Only the text, which is centered on the button, must wiggle: the button itself must not shake.

Problem

The solution entails adding a button, a div, and a span. Without these elements, the shaking does not seem to work as desired.

Code

Button code:

<button type="submit" id="accept-list" style="width:100%">
&#x2714;
</button>

jQuery code:

$("#accept-list > div > span").effect( "shake", { distance: 5 } );

Fiddle

Question

What is a simpler way (i.e., that does not require the inner div and span elements) to shake button text, which works cross-browser?


texts: Objective C implementation of Swift's if-let

texts:
This [Objective-]C-preprocessor macro currently handles single-variable if-let-not-nil and if-let-is-type, but doesn't handle multiple simultaneous tests and doesn't handle where clauses.

I prefer functions to macros, but I don't see any way to pass a local variable name to a function such that it would create a code block which can use that name internally when being compiled. Is there any way to make this a function?

This does not handle commas in code block: this can be worked around with () brackets, e.g.
     foo = @[1, 2];
         becomes
     foo = (@[1, 2]);, but I'd prefer something that doesn't surprise anyone using the macro, especially as the compiler error when commas are not wrapped in brackets is unhelpful.

#define IF_LET(tempType, temp, optional, code) \
if ((optional)!=nil && [optional isKindOfClass:tempType.class]) { \
    tempType *temp = (tempType*)optional;\
    {code}\
}

example usage:

for (SKNode *node in touchedNodes) {
    IF_LET(Tile, tile, node, {
        // Tile (capital) is one of my own classes
        // tile (lowercase) is defined at this point by the macro and only available within this code block
        SKAction *scale = [SKAction scaleBy: 1.2 duration: 0.15];
        SKAction *action = ([SKAction sequence:@[scale, scale.reversedAction]]);
        [tile runAction:action];
    })
}

SKLabelNode *t = nil;
IF_LET(SKLabelNode, temp, t, {
    // doesn't run: t was nil
})

t = [SKLabelNode labelNodeWithText:@"some text"];
IF_LET(NSObject, temp, t, {
    // this block runs, letting you do stuff with the local scope variable
    // NSObject *temp = (NSObject*)t;
}) else {
    // else block available for use, but
    // this one doesn't run because t is not nil and is a kind of NSObject
}

IF_LET(NSArray, temp, t, {
    // doesn't run, t is of wrong type
})

How can I improve this macro?


texts: Moving a value into another cell IF the destination does not have an adjacent border OR contain certain text

texts:
I've created a macro that finds the letter "O" in a range, then moves it up one cell if the destination cell does not have a "." or an adjacent border.

It works fine, but I've heard that the use of the "GoTo" statement is something that should be avoided as much as possible (leads to spaghetti code, etc.)

Is it okay to use in the following context? I've had a go at tweaking it to not use "GoTo" but haven't had any luck - I'm sure it's a very simple fix but my limited knowledge of VBA is holding me back. I tried using "If Not" instead of "If" but couldn't seem to get it to take into account both the border and the "." (it still moved the "O" into a cell containing a ".")

Sub MoveUp()

    Dim O As Range
    Set O = Range("A1:Z26").Find(What:="O", LookAt:=xlWhole, MatchCase:=True)

        If O.Offset(-1, 0) = "." _
        Or O.Offset(-1, 0).Borders(xlEdgeBottom).LineStyle <> xlNone _
        Then
        GoTo CancelSub
        Else

            O.Offset(-1, 0) = "O"
            O.ClearContents

        End If

CancelSub:

    Set O = Nothing

End Sub

PS. Please excuse me if there's some unorthodox formatting, still getting used to it!


texts: kryptein cryptography package for Node.js

texts:
I have written a cryptography NPM package called kruptein.  The code is also hosted on GitHub.

Having used multiple "best practices" with regards to key management, algorithm selection, key size, iv size etc. I could use someone with experience in this area to help validate the implementation.

I could use some help determining if I have flaws in any of the following:

Key sizes: _matrix(algo) - Are the appropriate key, iv & authentication tag sizes being identified and used correctly based on the algorithm selection? i.e. AES-128-CBC or AES-256-XTS

  _matrix(algo) {
    let obj = {
      at_size: 16,
      iv_size: 16,
      key_size: 32
    };

    if (algo.match(/ccm|ocb|gcm/i))
      obj.iv_size = 12;

    if (algo.match(/aes/) && algo.match(/ecb/))
      obj.iv_size = 0;

    if (algo.match(/aes/) && algo.match(/128/))
      obj.key_size = 16;

    if (algo.match(/aes/) && algo.match(/192/))
      obj.key_size = 24;

    if (algo.match(/aes/) && algo.match(/xts/))
      obj.key_size = 32;

    if (algo.match(/aes/) && algo.match(/xts/) && algo.match(/256/))
      obj.key_size = 64;

    return obj;
  }
}

Key derivation: _derive_key(secret) - When deriving keyed material from a provided secret are enough iterations used? Is there a problem with the salt generation used for the resulting keyed material? What about the resulting key? For both the IV and key I am concerned about possible weakening of the material when converting to a buffer and slicing to the appropriate sizes.

  _derive_key(secret) {
    let key, hash, salt, result, derived_key;

    try {
      hash = this.crypto.createHash(this.hashing);
      hash.update(secret);
      salt = hash.digest();
    } catch(err) {
      throw err;
    }

    salt = (Buffer.isBuffer(salt)) ?
      salt.slice(0, 16) : salt.substr(0, 16);

    key = this.crypto.pbkdf2Sync(secret, salt, 10000, 64, this.hashing);

    return Buffer.from(key.toString(this.encodeas)).slice(0, this.key_size);
  }

IV generation: _iv(iv_size) - When generating a new IV is there a problem with slicing the results. Most of the node.js crypto API functions use buffers and the sizes must match but I can't help but think it is weakening the IV.

  _iv(iv_size) {
    let iv = this.crypto.randomBytes(iv_size);

    return Buffer.from(iv.toString(this.encodeas),
      this.encodeas).slice(0, iv_size);
  }


texts:
The following snippet will return a list containing the words in all of the works of Shakespeare:

>>>def shakespeare_tokens(path = 'shakespeare.txt', url = 'http://inst.eecs.berkeley.edu/~cs61a/fa11/shakespeare.txt'):
        """Return the words of Shakespeare's plays as a list"""
        import os
        from urllib.request import urlopen
        if os.path.exists(path):
                return open('shakespeare.txt', encoding='ascii').read().split()
        else:
                shakespeare = urlopen(url)
                return shakespeare.read().decode(encoding='ascii').split()
>>>tokens = shakespeare_tokens()

Problem 1:

  Here's the idea: We start with some word - we'll use "The" as an example. Then we look through all of the texts of Shakespeare and for every instance of "The" we record the word that follows "The" and add it to a list, known as the successors of "The". Now suppose we've done this for every word Shakespeare has used, ever.

  Let's go back to "The". Now, we randomly choose a word from this list, say "cat". Then we look up the successors of "cat" and randomly choose a word from that list, and we continue this process. This eventually will terminate in a period (".") and we will have generated a Shakespearean sentence!

  The object that we'll be looking things up in is called a 'successor table', although really it's just a dictionary. The keys in this dictionary are words, and the values are lists of successors to those words.

  Here's an incomplete definition of the build_successors_table function. The input is a list of words (corresponding to a Shakespearean text), and the output is a successors table. (By default, the first word is a successor to '.').

  >>> table = build_successors_table(tokens)

Problem 2:

  Let's generate some sentences Suppose we're given a starting word. We can look up this word in our table to find its list of successors, and then randomly select a word from this list to be the next word in the sentence. Then we just repeat until we reach some ending punctuation. (Note: to randomly select from a list, first make sure you import the Python random library with import random and then use the expression random.choice(my_list)) This might not be a bad time to play around with adding strings together as well.

  >>> construct_sent('The', table)

Below is the solution for above 2 problems:

#Shakespeare and Dictionaries
def build_successors_table(tokens):
    table = {}
    prev = '.'
    for word in tokens:
        if prev in table:
            table[prev].append(word)
        else:
            table[prev] = [word]
        prev = word
    return table

def construct_sent(word, table):
    import random
    result = ''
    while word not in ['.', '!', '?']:
        result = result + word
        word = random.choice(table[word])
    return result + word


texts:
I made a commandline tool for renaming files, similar to the rename command in Ubuntu. Here is the code:

import scala.collection.mutable.Map

object Main extends App {
  val usage =
    """
      |A commandline tool for renaming files (written in Scala)
      |
      |Usage:
      |
      |  screname [-a] [-t] -s search_pattern -r replace_pattern filenames
      |
      |Type screname and return to print this message.
    """.stripMargin

  // Print usage and exit
  def printHelpExit() = {
    println(usage)
    System.exit(0)
  }

  if (args.length == 0) {
    printHelpExit()
  }
  val arglist = args.toList
  type OptionMap = Map[Symbol, Any]

  // Is the arg a switch?
  def isSwitch(s: String) = (s(0) == '-')

  // Function for parse args
  def nextOption(map: OptionMap, list: List[String]): OptionMap = {
    list match {
      // List is exhausted
      case Nil => map
      case "-a" :: tail => {
        nextOption(map ++ Map('replaceAll -> true), tail)
      }
      case "-t" :: tail => {
        nextOption(map ++ Map('testRun -> true), tail)
      }
      case "-s" :: searchPattern :: tail => {
        if (map.contains('searchPattern)) throw new IllegalArgumentException("Only one search pattern allowed.")
        nextOption(map ++ Map('searchPattern -> searchPattern), tail)
      }
      case "-r" :: replacePattern :: tail => {
        if (map.contains('replacePattern)) throw new IllegalArgumentException("Only one replace pattern allowed")
        nextOption(map ++ Map('replacePattern -> replacePattern), tail)
      }
      case filename :: tail => {
        map.update('files, filename :: (map.getOrElse('files, List())).asInstanceOf[List[String]])
        nextOption(map, tail)
      }
    }
  }

  val options = nextOption(Map(), arglist)
  // Validate options
  if (!options.contains('searchPattern)) throw new IllegalArgumentException("No search pattern provided")
  if (!options.contains('replacePattern)) throw new IllegalArgumentException("No replace pattern provided")
  if (options.getOrElse('files, List()).asInstanceOf[List[String]].size == 0) throw new IllegalArgumentException("No filenames provided")

  // Rename
  val fileRenamer = new FileRenameByPattern(options.getOrElse('files, List()).asInstanceOf[List[String]], options.getOrElse('searchPattern, "").asInstanceOf[String], options.getOrElse('replacePattern, "").asInstanceOf[String], options.getOrElse('replaceAll, false).asInstanceOf[Boolean])
  if (options.getOrElse('testRun, false).asInstanceOf[Boolean]) {
    fileRenamer.printFileNamePairs()
  } else {
    fileRenamer.rename();
  }
}

import java.io.File

/**
 * Created by IDEA on 17/08/15.
 */

class FileRenameByPattern(val oldFileNames: List[String], val searchPattern: String, val replacePattern: String, val replaceAll: Boolean) {
  val newFileNames = getNewFileNames()

  def getNewFileNames(): List[String] = {
    oldFileNames map {
      (x: String) =>
        if (replaceAll)
          x.replaceAll(searchPattern, replacePattern)
        else
          x.replaceFirst(searchPattern, replacePattern)
    }
  }

  def getFileNamePairs() = {
    oldFileNames zip newFileNames
  }

  def rename(): List[Boolean] = {
    rename(getFileNamePairs())
  }

  def rename(pairs: List[(String, String)]): List[Boolean] = {
    pairs map {
      case (o, n) => new File(o) renameTo new File(n)
    }
  }

  def printFileNamePairs() = {
    val w1 = oldFileNames.map(_.length).max
    val w2 = newFileNames.map(_.length).max
    getFileNamePairs() map {
      case (s1, s2) => println("%%%ds %%%ds".format(w1, w2).format(s1, s2))
    }
  }
}

The -t option is for a dry run.

I am thinking how to make it more extendable, like adding a sequence of numbers at the beginning, appending a date at the end, etc, but any suggestions on improvement are welcome.


texts:
I've got some constructors and a factory class that I would like to use in an Angular project. I would like to know how I can convert these to usable Angular services for my project.

Process Constructor

/**
 * A constructor for Process objects
 *
 * @param {Object} options An object with an integer processId and an array of roles containing
 *                         roles
 *
 * @return {Process} A new Process object
 */
function Process (options) {

    if ( typeof options.processId !== 'number' ) {
        throw 'Process ID is not a number';
    }

    if ( typeof options.roles !== 'object' || typeof options.roles.length === 'undefined' ) {
        throw 'Roles is not an array';
    }

    if ( options.roles.length === 0 ) {
        throw 'No roles passed';
    }

    this.processId = options.processId;
    this.roles     = options.roles;
    return this;

}

This is pretty straight forward. A bit of input checking then return the object.

Role Constructor

/**
 * A constructor for Role objects
 *
 * @param {Integer} processId An integer representing this role's parent process ID
 * @param {Integer} number    What number to assign the roleName attribute
 *
 * @return {Object Role} A brand new Role object
 */
function Role (processId, number) {

    // typecast
    processId = +processId;
    number    = +number;

    if ( !!isNaN(processId) || !!isNaN(number) ) {
        throw 'Both processId and number need to be numbers';
    }

    this.roleName  = 'role' + number;
    this.startDate = rand(0, new Date().getTime());
    this.endDate   = rand(this.startDate, new Date().getTime());
    this.href      = '/v1/transactions/' + processId + '/roles/' + this.roleName;
    return this;

}

Again, pretty straightforward. Some input validation, and then throw some data in and return the object.

Factory to create Process and Role objects

/**
 * A factory class to make some randomly generated processes
 * Based on http://addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript
 *
 * @return {Object Process} A new Process object with random data
 */
function processFactory () {}

/**
 * Returns a random 12 digit integer
 * @return {Integer} 12 digit integer
 */
processFactory.prototype.makeId = function () {
    return Math.round(Math.random() * Math.pow(10, 12));
};

/**
 * Makes a new process with random info
 *
 * @param  {Integer} numberOfRoles The amount of roles to put into the process
 *
 * @return {Object Process} A new Process object
 */
processFactory.prototype.makeProcess = function(numberOfRoles) {

    var i = 1;

    if ( typeof numberOfRoles === 'undefined' ) {
        numberOfRoles = Math.round(Math.random() * 10);
    }

    this.processId = processFactory.makeId();
    this.roles     = [];

    while ( numberOfRoles-- ) {
        i++;
        this.roles.push(new Role(this.processId, i));
    }

    return new Process(this);

};

var processFactory = new processFactory();

And here's the factory to build me some Processes and Roles for them. I'm not even sure if this is the best way to make a factory in Vanilla JS!

I want to be able to instantiate multiple processes and controllers.


texts: Marking projects as done when all tasks' progress are 100%

texts:
We have project.task model, where each task has many lines and each line has progress field indicating how much work has been done and how much still remaining (from 0 to 100 percent). The task cannot be done until all lines' progress is 100%.

@api.onchange('task_line_ids','task_line_rider_ids')
def progress_on_change(self):
    for record in self:
        if len(record.task_line_ids) != 0 and record.state in ('open', 'done'):
            all_done = True
            for line in record.task_line_ids or record.task_line_rider_ids:
                if line.progress != 100:
                    all_done = False
                    break
                if all_done == True:
                    record.state = 'done'
                else:
                    record.state = 'open'

However, SonarQube reported a code smell:

How can the complexity be reduced?


texts: Sample n items without replacement in Prolog

texts:
I have the following Prolog code which samples n items from a list without replacement:

samp(0,_,Sample,Sample).
samp(N,Domain0, Sample0, Sample):-
  N >= 0,
  length(Domain0,L),
  RandomNumber is random(L),
  nth0(RandomNumber, Domain0, X),
  delete(Domain0,X,Domain1),
  append(Sample0,[X],Sample1),
  N1 is N-1,
  samp(N1,Domain1,Sample1,Sample).

sample(Domain,N,Sample):-
  samp(N,Domain,[],Sample).

Is there a 'nicer' way to do this?


texts: Letter combinations of phone dial pad number

texts:
In preparation for interviews, I have written a solution to this question:

  Given a sequence of numbers (34128) and an input map such   as a dial
  pad on a phone (2->[a,b,c], 3->[d,e,f], 4->[g,h,i]) write an algorithm
  to return all possible words from the sequence. E.g. Input: 232
  Output: [ada, adb, adc, aea, aeb, aec, afa, afb, afc, bda, bdb, bdc,
  bea, beb, bec, bfa, bfb, bfc, cda, cdb, cdc, cea, ceb, cec, cfa, cfb,
  cfc]

  Also what will happen if this would have been a 12 digit international
  number? How would that effect your design.

Below is the solution I have:

public class DialPad {

    public static void main(String[] args) {
        System.out.println(letterCombinations("232"));
    }

    public static ArrayList<String> letterCombinations(String digits) {
        ArrayList<String> res = new ArrayList<String>();
        ArrayList<String> preres = new ArrayList<String>();
        res.add("");

        for (int i = 0; i < digits.length(); i++) {
            for (String str : res) {
                String letters = map.get(digits.charAt(i));
                for (int j = 0; j < letters.length(); j++)
                    preres.add(str + letters.charAt(j));
            }
            res = preres;
            preres = new ArrayList<String>();
        }
        return res;
    }

    static final HashMap<Character, String> map = new HashMap<Character, String>() {
        {
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }
    };
}

Is there any improvement I can make here? It looks to me like complexity is high in this code. How can I simplify this code better?


texts: Solving the Burst Balloon problem using Dynamic Programming

texts:
Continuing where I left off previously to solve the problem described here, I've now solved the same using dynamic programming (following Tikhon Jelvis blog on DP).

To refresh, the challenge is to find a sequence in which to burst a row of balloons that will earn the maximum number of coins. Each time balloon \$i\$ is burst, we earn \$C_{i-1} \cdot C_i \cdot C_{i+1}\$ coins, then balloons \$i-1\$ and \$i+1\$ become adjacent to each other.

import qualified Data.Array as Array

burstDP :: [Int] -> Int
burstDP l = go 1 len
  where
    go left right | left <= right = maximum [ds Array.! (left, k-1)
                                            + ds Array.! (k+1, right)
                                            + b (left-1)*b k*b (right+1) | k <- [left..right]]
                  | otherwise    = 0
    len = length l
    ds = Array.listArray bounds
           [go m n | (m, n) <- Array.range bounds]
    bounds = ((0,0), (len+1, len+1))
    l' = Array.listArray (0, len-1) l
    b i = if i == 0 || i == len+1 then 1 else l' Array.! (i-1)

I'm looking for:

Correctness
Program structure
Idiomatic Haskell
Any other higher order functions that can be used
Other optimizations that can be done


texts: Dependency Injection and Service Locator/DI Container

texts:
I have implemented clean architecture for my app, and I have a few questions.

Typically, pure DI is argued for over a Service Locator pattern, because it is very explicit and more testable.

However, I like the idea of having an object that contains all of my services or all of my repositories (a DI container), and I can just inject that one single object instead of injecting the various different services/repositories for ease of development.

But I'm not sure if this still follows SOLID principles.

For example, here is a typical DI:

// Database

type Database interface {
    Insert(...)
    Delete(...)
}

// User object

type User struct {}

// User Service

type UserService interface {
    Create(user User)
}

func NewUserService(userRepo UserRepository) UserService {
    return &userService{userRepo: userRepo}
}

type userService struct {
    userRepo UserRepository
}

func (s *userService) Create(user User) {
    s.userRepo.Create(user)
}

// User Repository

type UserRepository interface {
    Create(user User)
}

func NewUserRepository(db Database) UserRepository {
    return &userRepository{db: db}
}

type userRepository struct {
    db Database
}

func (r *userRepository) Create(user User) {
    r.db.Insert(user)
}

main() {
    // Create db
    db := database.New(...)

    // Create repo by injecting db
    userRepo := NewUserRepository(db)

    // Create service by injecting repo
    userService := NewUserService(userRepo)
}

As you see in the example above, that is following a pure DI approach.

The problem I have with this is the arguments can get to over 30 things being injected in a larger application.

So I came up with a different pattern which is to basically inject a single ServiceFactory or RepositoryFactory, and those will contain pointers to all of the other more granular service/repository classes.

So the new code can be changed to something like this:

// User Service

type UserService interface {
    Create(user User)
}

func NewUserService(repos RepositoryFactory) UserService {
    return &userService{repos: repos}
}

type userService struct {
    repos RepositoryFactory
}

func (s *userService) Create(user User) {
    s.repos.UserRepository.Create(user)
}

// Repository factory

type RepositoryFactory struct {
    UserRepository UserRepository
}

func NewRepositoryFactory(db Database) RepositoryFactory {
    return RepositoryFactory{
        UserRepository: NewUserRepository(db),
    }
}

main() {
    // Create db
    db := database.New(...)

    // Create repo factory
    repos := NewRepositoryFactory(db)

    // Create services by injecting repo factory
    userService := NewUserService(repos)
    fooService := NewFooService(repos)
    barService := NewBarService(repos)
    bazService := NewBazService(repos)
}

Does this approach still confirm to SOLID principles? It makes development much quicker and still uses DI, so I don't see why it couldn't still be tested because I could just mock the repository factory class in the same way I'd mock the individual repository classes...

Would you recommend this approach, why/why not? Thanks.


texts:
I implemented Aho-Corasick string matching in Haskell. It is a purely functional implementation compared to many other implementations.

The input to build an automata is [([a],b)]. which is a list of (pattern,output) pairs.
b has to form a monoid, so we know what to do when more than one match occurs at the same place.

I borrowed many idea from the KMP implementation by Twan van Laarhoven(which I suspect is a implementation of the MP instead of KMP algorithm).

import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function
import Control.Arrow
data Automaton a b = Node {delta  :: a -> Automaton a b,
                           output :: b
                         }
-- assume the input function eq is a equivalence relation, then this
-- produce all the equivalent classes.
equivalentClasses :: (a->a->Bool)->[a]->[[a]]
equivalentClasses eq = foldl parts []
  where parts [] a = [[a]]
        parts (x:xs) a
         | eq (head x) a = (a:x):xs
         | otherwise     = x:parts xs a

buildAutomaton :: (Monoid b,Eq a) => [([a],b)] -> Automaton a b
buildAutomaton xs = automaton
  where automaton = build (const automaton) xs mempty

-- this builds one node of the automaton. Tying the knot happens everywhere
build :: (Monoid b,Eq a)=> (a -> Automaton a b) -> [([a],b)] -> b -> Automaton a b
build trans' xs out = node
  where node  = Node trans out
        trans a
          | isNothing next = trans' a
          | otherwise      = fromJust next
          where next = lookup a table
        table =  map transPair $ equivalentClasses (on (==) (head . fst)) xs
        transPair xs = (a, build (delta (trans' a)) ys out)
         where a  = head $ fst $ head xs
               (ys,zs) = partition (not . null . fst) $ map (first tail) xs
               out = mappend (mconcat $ map snd zs) (output $ trans' a)

-- this function simulates the automaton.
match :: Eq a => Automaton a b -> [a] -> [b]
match a xs = map output $ scanl delta a xs

-- an example to check if a list is a sublist of another list
isInfixOf' :: Eq a => [a] -> [a] -> Bool
isInfixOf' xs ys = getAll $ mconcat $ match (buildAutomaton [(xs, All True)]) ys


texts:
I have a function that adds to a std::wstring some filler characters. The user gives a single filler character. They can also optionally given an initial filler sequence (std::wstring) and an optional final filler sequence (std::wstring) that start and end the padding. These will only be added however if they fit inside the padded length specified by the user.

static std::wstring fillWString(
    const std::wstring &stringToFill,
    size_t fillLength,
    const wchar_t fillChar = L' ',
    const std::wstring &initialFill = L"",
    const std::wstring &endFill = L"") {

  const size_t originalStringLength = stringToFill.size();
  if (fillLength <= originalStringLength) {
    return stringToFill;
  }

  std::wstring result(stringToFill);
  result.resize(fillLength, fillChar);

  if (originalStringLength + initialFill.size() <= fillLength) {
    result.replace(originalStringLength, initialFill.size(), initialFill, 0u);
    if (originalStringLength + initialFill.size() + endFill.size() <= fillLength) {
      result.replace(fillLength - endFill.size(), endFill.size(), endFill, 0u);
    }
  }
  return result;
}

Here is some output:

Analyzed folder: .... \Path\To\Some\Folder\
Time step: .......... 0.007045000
Out Flow: ........... 1.2460679423999952
In Flow: ............ -1.2461052960000008

where each line was generated using

fillWString(L"string", 22, '.', L" ", L" ") << value;

Specifically, I was wondering what sort of tips you guys might give to improve this. Also, I was just wondering if copy-elision is guaranteed to occur here if the string is indeed padded?


texts: Counting the total value of Card instances given

texts:
I am trying to write a function called countHand() that takes in an array of Card instances and counts the total value of the cards given.

The requirements are as follows:

The function returns the value of the cards in the hand as an Int.  It does not use loops or nested functions.
The card values are as follows:

Any Ace preceded by 5 of Diamonds is worth 100 points.
Any odd numeric card (3, 5, 7, 9) of any suit's worth the double of its rank value in points when immediately preceded in the hand by any card of the Hearts.

Examples:

The hand 3♥, 7♣ has total value of 14.
The hand 3♣, 7♥ has total value of 0.

Brevity/using one statement functions/closures/case statements are prefered.

Here is the current solution:

enum Suit {
    case Clubs, Diamonds, Hearts, Spades
}

enum Rank {
    case Jack, Queen, King, Ace
    case Num(Int)
}

struct Card {
    let suit: Suit
    let rank: Rank
}

/*
- Generate an array of tuples of 2 card subsequences by zipping the hand array with itself (minus the first element)
- Map over the array examining each pair for value-contributing combinations in a switch statement
- Sum all resulting values
*/
func countHand(hand: [Card]) -> Int {
    return Array(Zip2(hand, dropFirst(hand))).map{(card1: Card, card2: Card)->Int in
        switch (card1.suit, card1.rank, card2.rank) {
        case (.Hearts, _, .Num(let numRank)) where numRank % 2 == 1:
            return 2 * numRank
        case (.Diamonds, .Num(5), .Ace):
            return 100
        default:
            return 0
        }}.reduce(0, +)
}

countHand([
    Card(suit:.Hearts, rank:.Num(10)),
    Card(suit:.Hearts, rank:.Num(6)),
    Card(suit:.Diamonds, rank:.Num(5)),
    Card(suit:.Clubs, rank:.Ace),
    Card(suit:.Diamonds, rank:.Jack)
    ])// --> prints 110

I am wondering if there is room for improvement of this code, whether it would be brevity/execution speed/memory usage/CPU (extreme cases could be considered i.e a hand with a big number of cards).


texts: Concurrent byte array access in Java with different locking

texts:
I have one writer thread and 10 reader threads of a byte array. It is important to synchronize writes and reads over a "row" (16 bytes).

There are a lot less locks than rows, e.g. in the current configuration 1024 (chunkRows) rows have one lock which makes the overall operation faster, but also consumes less memory.

Here is the read method for ReadWrite locking:

public void read(int pointer, byte[] tmpBytes, int length) {
    Lock lock = locks[pointer / rowSize / chunkRows].readLock();
    lock.lock();
    try {
        System.arraycopy(bytes, pointer, tmpBytes, 0, length);
    } finally {
        lock.unlock();
    }
}

and here for simple "Object"-synchronized:

public void read(int pointer, byte[] tmpBytes, int length) {
    Object lock = locks[pointer / rowSize / chunkRows];
    synchronized (lock) {
        System.arraycopy(bytes, pointer, tmpBytes, 0, length);
    }
}

Here is the full repository which you can easily run via maven. It uses JMH to avoid nasty performance pitfalls. Of course, also write is synchronized similarly.

Now why is my ReadWrite implementation a lot slower than synchronized? (RW is roughly 40% slower)

I like Object-locking more because it uses less RAM but did I made a mistake with ReadWrite-locking or does this make sense?

I tried it on my dual core laptop as well as on more beefy quad core commodity server with simmilar results (Object-locking faster than RW). I get something like 13.0 ops/s for ReadWrite locking and 21.6 ops/s for Object locking.

Update

Several things were wrong in the benchmark which I fixed (maybe there are still glitches)

Very important bug fix was to include service.awaitTermination
make sure write and read happen at the same time and both are long enough (previously write was too short and nearly no r+w concurrency happened)
I've learned about StampedLock, could be slightly faster and also optimistic locking could be even the winner here.
minor thing: catch errors in runnable otherwise they won't appear

See all in this commit


texts: HttpWebRequest Extension with cancelation and timeout support

texts:
I want to make a extension that extends HttpWebRequest in order to retrieve the response asynchronously. This is achieved by using the Task.Factory.FromAsync. Now this extension needs to be able to handle cancellations as well as timeouts.

The way I implemented the cancellation is via registering the request.abort() to the cancellation token. The timeout is handled by running the asynchronous operation inside an other task. It waits on that task with the the given timeout as shown below.

I have tested this method and it works, but I want to know if my implementation is valid (safe practice) with the guidelines. I also want to know if there is a better way to achieve what I need. I am pretty sure that I am adding extra overhead because of the task inside a task situation.

internal static Task<WebResponse> GetResponseAsync(this HttpWebRequest request, TimeSpan timeout,
            CancellationToken token)
        {
            return Task.Run(() =>
            {
                if (token.IsCancellationRequested)
                    return null;
                Task<WebResponse> task;

                try
                {
                    token.Register(request.Abort);
                    task = Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);

                    if (!task.Wait(timeout))
                        throw new WebException("No response was received during the time-out period specified.",
                            WebExceptionStatus.Timeout);
                }
                catch (Exception ex)
                {
                    var exception = ex as WebException;
                    if (exception != null)
                        throw exception;

                    throw new WebException(ex.Message, WebExceptionStatus.ConnectionClosed);
                }

                return task.Result;
            }, token);
        }

Edit: I have modified my extension method; the new code looks better but it still has the issue of overhead because of two tasks. What do you guys think?

internal static async Task<WebResponse> GetResponseAsync(this HttpWebRequest request, int timeout,
        CancellationToken token)
    {
        var requestTask = Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
        var timeOutTask = Task.Delay(timeout, token);

        var result = await Task.WhenAny(requestTask, timeOutTask).ConfigureAwait(false);

        if (result != timeOutTask) return requestTask.Result;

        request.Abort();

        if (token.IsCancellationRequested)
            throw new WebException("Request was canceled.", WebExceptionStatus.RequestCanceled);

        throw new WebException("Request timed out.", WebExceptionStatus.Timeout);
    }


texts: Authorization using Entity Framework in ASP.NET MVC

texts:
1. Backstory

I recently starting programming and I found out that Entity Framework works perfect for my small-sized applications due its simplicity.

I've made my custom authorize attribute for MVC controllers and controller methods to check if the current user has a certain role (which is an enum type in my case).

The following code represents my authorize attribute:

public class HasRoleAttribute : ActionFilterAttribute
{
    private Role _role;

    public HasRoleAttribute(Role role)
    {
        this._role = role;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var context = new FactoryManagementContext();

        var userName = filterContext.HttpContext.User.Identity.Name;
        var user = context.Users.FirstOrDefault(item => item.UserName == userName);

        var hasRole = user.Role == _role;

        if (user == null || !hasRole)
        {
            // If this user does not have the
            // required permission then redirect to login page
            var url = new UrlHelper(filterContext.RequestContext);
            var loginUrl = url.Content("/Account/Login");
            filterContext.HttpContext.Response.Redirect(loginUrl, true);
        }
    }
}

public enum Role
{
    Engineer,
    Manager,
    Admin
}

2. Question

It works as a charm, but I have only one question: is it necessary to initialize the database context every single time when authorizing a user?


texts:
I got asked this following interview for the following problem.
Wondering if you have any thought and feedback for 3 solutions below:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Link to the problem:
https://leetcode.com/problems/merge-k-sorted-lists/description/

# Time:  O(nlogk)
# Space: O(1)

# Merge k sorted linked lists and return it as one sorted list.
# Analyze and describe its complexity.

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, self.next)

# Merge two by two solution.
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        def mergeTwoLists(l1, l2):
            curr = dummy = ListNode(0)
            while l1 and l2:
                if l1.val < l2.val:
                    curr.next = l1
                    l1 = l1.next
                else:
                    curr.next = l2
                    l2 = l2.next
                curr = curr.next
            curr.next = l1 or l2
            return dummy.next

        if not lists:
            return None
        left, right = 0, len(lists) - 1;
        while right > 0:
            if left >= right:
                left = 0
            else:
                lists[left] = mergeTwoLists(lists[left], lists[right])
                left += 1
                right -= 1
        return lists[0]

# Time:  O(nlogk)
# Space: O(logk)
# Divide and Conquer solution.
class Solution2:
    # @param a list of ListNode
    # @return a ListNode
    def mergeKLists(self, lists):
        def mergeTwoLists(l1, l2):
            curr = dummy = ListNode(0)
            while l1 and l2:
                if l1.val < l2.val:
                    curr.next = l1
                    l1 = l1.next
                else:
                    curr.next = l2
                    l2 = l2.next
                curr = curr.next
            curr.next = l1 or l2
            return dummy.next

        def mergeKListsHelper(lists, begin, end):
            if begin > end:
                return None
            if begin == end:
                return lists[begin]
            return mergeTwoLists(mergeKListsHelper(lists, begin, (begin + end) / 2), \
                                 mergeKListsHelper(lists, (begin + end) / 2 + 1, end))

        return mergeKListsHelper(lists, 0, len(lists) - 1)

# Time:  O(nlogk)
# Space: O(k)
# Heap solution.
import heapq
class Solution3:
    # @param a list of ListNode
    # @return a ListNode
    def mergeKLists(self, lists):
        dummy = ListNode(0)
        current = dummy

        heap = []
        for sorted_list in lists:
            if sorted_list:
                heapq.heappush(heap, (sorted_list.val, sorted_list))

        while heap:
            smallest = heapq.heappop(heap)[1]
            current.next = smallest
            current = current.next
            if smallest.next:
                heapq.heappush(heap, (smallest.next.val, smallest.next))

        return dummy.next

if __name__ == "__main__":
    list1 = ListNode(1)
    list1.next = ListNode(3)
    list2 = ListNode(2)
    list2.next = ListNode(4)

    print Solution().mergeKLists([list1, list2])


texts:
The normal boostrap affix doesn't take the items natural offset top position into account, you have to manually pass it in as an attribute. This takes care of that, and accounts for the offset top changing on window resize.

var $attribute = $('[data-smart-affix]');
$attribute.each(function(){
  $(this).affix({
    offset: {
      top: $(this).offset().top,
    }
  })
})
$(window).on("resize", function(){
  $attribute.each(function(){
    $(this).data('bs.affix').options.offset = $(this).offset().top
  })
})


texts:
As an exercise I have written a basic binary tree implementation in Go.

Tree struct:

type Tree struct {
    Key   *int
    Value interface{}
    Left  *Tree
    Right *Tree
}

func New() *Tree {
    return &Tree{}
}

It a annoys me a bit, that Key is a pointer, but this is needed at the moment, because I use nil as an indicator for an empty node, e.g. in Insert:

func (t *Tree) Insert(key int, value interface{}) {
    if t.Key == nil {
        t.Key = &key
        t.Value = value
        t.Left = New()
        t.Right = New()
    } else {
        if key == *t.Key {
            return
        }
        if key < *t.Key {
            t.Left.Insert(key, value)
        } else {
            t.Right.Insert(key, value)
        }
    }
}

The Search method does not look too bad, but the nil check still looks wrong:

func (t *Tree) Search(key int) *Tree {
    if t.Key == nil {
        return nil
    }
    if *t.Key == key {
        return t
    }
    if key < *t.Key {
        return t.Left.Search(key)
    } else {
        return t.Right.Search(key)
    }
}

Would this be idiomatic Go? Wouldn't it be better to forego nil checks, since

  Hoare [...] described their invention [Nullable references] as a "billion dollar mistake".

From: http://en.wikipedia.org/wiki/Nullable_type

Full implementation: https://github.com/miku/arboretum/blob/2f3646d8483b5db249917921feedb9732754a7bf/bst/bst.go

Example usage: https://github.com/miku/arboretum/blob/2f3646d8483b5db249917921feedb9732754a7bf/examples/bst.go


texts:
I have solved the Ransom Note
 challenge on HackerRank using JavaScript / ECMAScript 6. The challenge goes like this:

A kidnapper wrote a ransom note but is worried it will be traced back to him. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use whole words available in the magazine, meaning he cannot use substrings or concatenation to create the words he needs.
Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No.
Input Format
The first line contains two space-separated integers describing the respective values of (the number of words in the magazine) and (the number of words in the ransom note).
The second line contains space-separated strings denoting the words present in the magazine.
The third line contains space-separated strings denoting the words present in the ransom note.

My solution uses JavaScript Map objects (as suggested by the name of the challenge) and passes all tests with no timeouts. However, the solution itself is very literal, as in, it removes out each word in the ransom note from the magazine, unless the needed word is not available.
Note that the portion of code above ignore above this line is included with all challenges on the site, I left it in for the sake of completeness, so that anyone can copy-paste the whole block into the challenge page, if they wish.
process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

const addValueOrIncrementCount = (value, map) => {
    let count = map.get(value)
    if (count) {
        map.set(value, ++count)
    } else {
        map.set(value, 1)
    }
    return count
}

const decrementCountIfPossible = (value, map) => {
    let count = map.get(value)
    if (!count) {
        return null
    } else {
        map.set(value, --count)
        return count
    }
}

const mapWordCounts = inputString => {
    const output = new Map()
    let occurrences
    for (let word of inputString.split(" ")) {
        addValueOrIncrementCount(word, output)
    }
    return output
}

const isRansomComposedFromMagazine = (ransom, magazine) => {
    const ransomMap = mapWordCounts(ransom)
    const magazineMap = mapWordCounts(magazine)
    let ransomWordFromMagazine
    for (let [word, count] of ransomMap.entries()) {
        while (count > 0) {
            ransomWordFromMagazine = decrementCountIfPossible(word, magazineMap)
            if (ransomWordFromMagazine === null) {
                return false
            }
            count--
        }
    }
    return true
}

const getProgramInput = () => {
    const firstLine = readLine().split(' ')
    const magazineWordCount = parseInt(firstLine[0])
    const ransomWordCount = parseInt(firstLine[1])
    const magazine = readLine()
    const ransom = readLine()
    return {
        magazineWordCount: magazineWordCount,
        ransomWordCount: ransomWordCount,
        magazine: magazine,
        ransom: ransom
    }
}

const main = () => {
    const input = getProgramInput()
    console.log(isRansomComposedFromMagazine(input.ransom, input.magazine) ? "Yes" : "No")
}


texts: Looking at the hill of indents seems like this can be improved

texts:
I've spent some time on this as an answer elsewhere, and did my best to optimize it. But looking at the hill of indents seems like this can be improved. I've tried to implement an any() statement to replace the for break part, without any luck. Does anyone have any suggestions?
Groups = [[['NM1', 'OP', '1', 'SMITH', 'JOHN', 'PAUL', 'MR', 'JR'],
           ['ABC', '1L', '690553677'],
           ['DIR', '348', 'D8', '20200601'],
           ['DIR', '349', 'D8', '20200630']],
          [['NM1', 'OP', '1', 'IMA', 'MEAN', 'TURD', 'MR', 'SR'],
           ['ABC', '1L', '690545645'],
           ['ABC', '0F', '001938383',''],
           ['DIR', '348', 'D8', '20200601']]]

def ids(a, b):
    l = []
    for group in Groups:
        for lst in group:
            if lst[0] == a and lst[1] == b:
                if lst[2] == 'D8':
                    l.append(lst[3])
                else:
                    l.append(lst[2])
                break
        else:
            l.append(None)
    return l

current_id = ids('ABC', '1L')
prior_id = ids('ABC', '0F')
start_date = ids('DIR', '348')
end_date = ids('DIR', '349')

print(current_id)
print(prior_id)
print(start_date)
print(end_date)

Output:
['690553677', '690545645']
[None, '001938383']
['20200601', '20200601']
['20200630', None]

So basically, I have this Groups list, in that list are 2 nested lists. Assuming the output lists are [x, y], the first nested list in Groups is x, and the second is y.
You see my function has two parameters, a and b. x and y are determined when their corresponding nested list has a list that has a as the first index, and b as the second index.
If the nested list doesn't have a list that meets that requirement, the x or y will be None.

UPDATE: Is there any way to flatten the series of indents? At least a few?


texts:
I have the following tables structures:

CREATE TABLE IF NOT EXISTS `options` (
  `option_id` tinyint(4) unsigned NOT NULL,
  `poll_id` mediumint(8) unsigned NOT NULL,
  `option` tinytext NOT NULL,
  UNIQUE KEY `option_id_poll_id` (`option_id`,`poll_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Storing poll options/choices';

CREATE TABLE IF NOT EXISTS `questions` (
  `poll_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `deleted` bit(1) NOT NULL DEFAULT b'0',
  `question` tinytext NOT NULL,
  `nick` varchar(32) NOT NULL,
  `dated` datetime NOT NULL,
  PRIMARY KEY (`poll_id`),
  KEY `deleted` (`deleted`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Table to store poll questions/titles';

CREATE TABLE IF NOT EXISTS `votes` (
  `poll_id` mediumint(8) unsigned NOT NULL,
  `option_id` tinyint(4) unsigned NOT NULL,
  `nick` varchar(32) NOT NULL,
  `dated` datetime NOT NULL,
  UNIQUE KEY `poll_id_nick` (`poll_id`,`nick`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

I am displaying details for a particular poll_id using the following query:

SELECT
    o.option_id AS option_id,
    o.`option` AS `option`,
    COUNT(v.nick) AS total,
    FLOOR(
        ( COUNT(v.nick) / (SELECT COUNT(1) FROM votes WHERE poll_id = %d) ) * 100
    ) AS percentage
FROM options o
LEFT JOIN votes v
    ON o.poll_id = v.poll_id
    AND v.option_id = o.option_id
WHERE o.poll_id = %d
GROUP BY o.option_id
ORDER BY total DESC, o.option_id ASC;

I am not satisfied with the way that I am calculating the percentage votes on each of the available options! %d is place-holder for string.format function.

I'd like a review on the query/table structures above.


texts:
I am slowly learning to master JavaScript and particularly the art of self-executing/invoking functions. I have developed a simple JavaScript plugin and I think I have followed the correct standards.

It is pretty basic in what it does, it is to store information on a oData BATCH request, which provides functions to add to the batch request, get the string representation (which can then be used in a HTTP request), and I am expanding on it as we speak.

However, the code is as follows. It was using jQuery but not any more due to resource constraint.

I am generally after comments on what could have been done better. I am doing this in an attempt to reduce the window namespace. Therefore BatchInfo and BatchCacheRequest (which are a bit more specific to my code) are not clogging up the name space, nor do I have to keep an array anywhere do hold the BatchInfo objects.

(function () {
    var info = [],
        b = {
            clear: function () {
                info = [];
            },

            get: function () {
                return info;
            },

            add: function (command, url, data) {
                info.push(new BatchInfo(command, url, data));
                return info;
            },

            toString: function () {
                var batchString = ['--batchfull'];

                batchString.push('Content-Type: multipart/mixed; boundary=batchitems');

                for (var i = 0; i < info.length; i++) {
                    batchString.push('');
                    batchString.push('--batchitems');
                    batchString.push('Content-Type: application/http');
                    batchString.push('Content-Transfer-Encoding: binary');
                    batchString.push('');
                    batchString.push(info[i].Command + ' ' + info[i].URL + ' HTTP/1.1');

                    if (info[i].Command !== 'DELETE') {
                        batchString.push('Content-Type: application/json;type=entry');
                    }

                    batchString.push('');
                    batchString.push(info[i].Data);
                }

                return batchString.join('\r\n') || '';
            }
        };

    function BatchInfo(command, url, data) {
        this.URL = url || '';
        this.Command = command || '';
        this.Data = data || '';
    }

    function BatchCacheRequest(info, description) {
        this.Info = info || '';
        this.Description = description || '';
        this.SubmitDateTime = new Date().toString('yyyy-MM-dd HH:mm');
    }

    window.batch = b;

})();

Usage is:

batch.add('POST', 'http://www.mywebsite.com', '[some data to post]');

Then toString() will return me a string which is formatted like a BATCH request (which I will use later on in the code).

Is there anything I'm doing stupidly bad here?


texts: Iterative Fibonacci sequence using standard library functions

texts:
We're all aware of Fibonacci sequence calculators but they look like C-style code. I want to avoid that and take advantage of the standard library. This code is very short, so I'm focusing on readability and correctness.

Barring comments, will people be able to understand the code just by looking at it?
As you're probably aware, this doesn't scale well due to stack limits. Using a dynamic memory approach, i.e. auto arr = std::make_unique<type[]>(size);, this allocates A LOT of memory. Comparatively, an iterative approach doesn't need any memory allocation at all, as it doesn't store the previous results, only the last one. As a result, my approach is automatically slower. For example, this answer ran in under a second, while mine ran in 7 seconds for a size of 1000000 (and allocated 8,000,000 bytes).

What's a way to make this faster AND to cut down on the memory usage?
I've compared the output to the oeis list and it seems correct. Would this break for bigger numbers? What should I replace std::uint64_t with? While I need std::uint64_t to store the bigger numbers, it obviously doubles the amount of memory allocated.

#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <cstdint>

int main()
{
    std::array<std::uint64_t, 10000> arr;
    arr.fill(0);
    arr[1] = 1;
    arr[2] = 1;

    std::transform(arr.begin(), arr.end() - 2,
        arr.begin() + 1, arr.begin() + 2,
        std::plus<>());
    std::copy(arr.begin(), arr.end(),
        std::ostream_iterator<std::uint64_t>(std::cout, " "));
    return 0;
}


texts: Inherited code checking Struts method name

texts:
I am working in an inherited code (as in "everybody related to it left before I arrived at the job and left no documentation") and I have noticed an strange pattern.

Almost(*) each Struts (Struts 1.3.8) method that is invoked begins with a code such as

public ActionForward myMethod(ActionMapping mapping, ActionForm form,
  HttpServletRequest request, HttpServletResponse response)
    throws IOException, SerletException {

  String method = request.getParameter("method");
  if (method != null && "myMethod".equals(method)) {
    // Perform the actual work
    ...

I mean, I would be pretty confident that Struts would redirect each request to its associated method and I should not need to double-check it in the logic (also, if Struts fails to properly redirect, then the application would fail because the desired operation would not be executed).

I have asked Google for reasons for this code (existing or old bugs, etc.) but found none; anyone with experience in Struts can provide a reason that justifies the existence of such a code and so much (apparently) wasted effort? I want to know if I am free to delete such code to simplify the methods (which are messy enough without these "improvements").

(*) There are a few instances in which the code does not appear, but it smells just of the programmer forgetting it.


texts:
I've started reading C++ Primer a few weeks ago and there's an exercise that asks you to compare two arrays for equality. The code I made works, but is it good? What should I fix?

If the number of elements don't match, they're not equal.  If the elements are different, they are not equal.

#include <iostream>

using namespace std;

bool arrayComparer(int *a, size_t asize, int *b, size_t bsize){
    if(asize != bsize){return false;}
    for(size_t ite = 0; ite < asize; ++ite){
       if(*(a+ite) != *(b+ite)){return false;}
    }
    return true;
}

int main()
{
    int ar1[]{0,1,2,3,4,5,6,7,8,9},
        *ptr1 = ar1,
        ar2[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18},
        *ptr2 = ar2;

        size_t intSize = sizeof(int),
               asize = sizeof(ar1) / intSize,
               bsize = sizeof(ar2) / intSize;

    cout << arrayComparer(ptr1,asize,ptr2,bsize) << endl;
    return 0;
}

Since the number of elements may be different, I'm using pointers. I did not find a way to get the number of elements from the pointers, so I'm also passing the size to the function.

Comments are appreciated.


texts:
I'm trying to create a way to clock in and clock out at work using python and tkinter. There are several features to be implemented.

Change the Employee Name
Clock In button
Clock Out button
Export file with the information

I have all the components and they work when I run the different features individually. When I try to combine to one script, the program fails.

import tkinter as tk
import time

class StopWatch(Frame):
    """ Implements a stop watch frame widget. """
    def __init__(self, parent=None, **kw):
       Frame.__init__(self, parent, kw)
    self._start = 0.0
    self._elapsedtime = 0.0
    self._running = 0
    self.timestr = StringVar()
    self.makeWidgets()

    def makeWidgets(self):
        """ Make the time label. """
        l = Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=2, padx=2)

    def _update(self):
        """ Update the label with elapsed time. """
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def _setTime(self, elap):
        """ Set the time string to Minutes:Seconds:Hundreths """
        minutes = int(elap/60)
        seconds = int(elap - minutes*60.0)
        hseconds = int((elap - minutes*60.0 - seconds)*100)
        self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))

    def Start(self):
        """ Start the stopwatch, ignore if running. """
        if not self._running:
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1

    def Stop(self):
        """ Stop the stopwatch, ignore if stopped. """
        if self._running:
            self.after_cancel(self._timer)
            self._elapsedtime = time.time() - self._start
            self._setTime(self._elapsedtime)
            self._running = 0

    def Reset(self):
        """ Reset the stopwatch. """
        self._start = time.time()
        self._elapsedtime = 0.0
        self._setTime(self._elapsedtime)

    def clock_in(self):
        global e1
        data = e1.get()
        ClockIn_time = datetime.datetime.now()
        ClockIn_date = datetime.datetime.now().strftime('%Y-%m-%d')
        totalinput = [ data, ClockIn_time, ClockIn_date]
        with open(r"C:\Users\Desktop\ClockIn.csv", "a") as savedb:
            w = csv.writer(savedb)
            w.writerow(totalinput)

    def clock_out(self):
        global e1
        data = e1.get()
        ClockOut_time = datetime.datetime.now()
        ClockOut_date = datetime.datetime.now().strftime('%Y-%m-%d')
        totalinput = [ data, ClockOut_time , ClockOut_date ]
        with open(r"C:\Users\Desktop\ClockIn.csv", "a") as savedb:
            w = csv.writer(savedb)
            w.writerow(totalinput)

def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)
    root.geometry("400x400")

    ####
    label = tk.Label(root, text="Employee Name: ")
    label.pack(side="top")

    new = StringVar()
    e1 = Entry(root, textvariable=new)
    e1.pack()
    #######

    Button(root, text='Clock In', command=lambda :[sw.Start(), sw.clock_in()]).pack(side=LEFT)
    Button(root, text='Clock Out', command=lambda :[sw.Start(), sw.clock_out()]).pack(side=LEFT)
    Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
    Button(root, text='Quit', command=root.quit).pack(side=LEFT)

    root.mainloop()

if __name__ == '__main__':
    main()

I'm having trouble get() the employees name and saving to a file. I've created a stand alone tkinter app, I'm able to do this, when I implement multiple features I cannot get them all to marinate.


texts:
I'm trying to implement fftshift from matlab for OpenCV. Can you please review the correctness of my algorithm? Have I missed something? Also, is there a better and faster way to do it?

cv::Mat ff;
cv::dft(distanceF, ff, cv::DFT_COMPLEX_OUTPUT);

//Make place for both the complex and the real values
cv::Mat planes[] = {cv::Mat::zeros(distanceF.size(),1, CV_32F), cv::Mat::zeros(distanceF.size(),1, CV_32F)};
cv::split(ff, planes);    // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))

cv::vector<float> im(planes[1].cols);
cv::vector<float> re(planes[0].cols);
int m = planes[0].cols;
int p = ceil(m/2);

for (int i = 0; i < p; i++)
{
    im[i] = planes[1].at<float>(p + i +1);
    im[p +i +1] = planes[1].at<float>(i +1);

    re[i] = planes[0].at<float>(p + i +1);
    re[p +i +1] = planes[0].at<float>(i +1);
}
im[p] = planes[1].at<float>(0);
re[p] = planes[0].at<float>(0);
cv::Mat input[] = {cv::Mat(im),cv::Mat(re)};
cv::merge(input,2,ff);


texts:
I am going through some of my companies EDI reports to see if I can make them faster.  The query below runs in less than one second in our AWS RDS environment, but it takes ~55 seconds on a blade in the office, so there is room for improvement.  I do not see any common performance culprits based upon Google searches, but I am not an expert.

When I say, "EDI", I am expressing that the purpose of this query is to transfer data from one computer system to another. For instance, that is why I am converting all of the dates to strings, because that is what the target system wants (in "mm/dd/yyyy" format).

Some background info:

There are about 11,000 rows in each of the two tables
Two of tables are de-normalized "Snapshot" tables
The query returns 3500 records
The two Snapshot tables have non-unique, non-clustered indexes
The third table (CaseOpenEnrollmentPeriod) has a unique clustered index, although it is only four records long.

DECLARE @MostRecentSnapshotTime datetime
SET @MostRecentSnapshotTime = (SELECT MAX(SnapshotLoadStartTime) AS Expr1
                       FROM   Snapshot.SnapshotLog)

SELECT
   SPE.SSN
  ,SPE.SSN
  ,CONVERT(NVARCHAR(10), SPE.BirthDate, 101)
  ,SPE.LastName
  ,SPE.FirstName
  ,LEFT(SPE.MiddleName, 1)
  ,SPE.Address1
  ,SPE.Address2
  ,SPE.City
  ,SPE.StateCode
  ,LEFT(SPE.ZipCode, 5)
  ,'SampleText'
  ,'SampleText'
  ,CASE WHEN SPE.MaritalStatusCode = 'SampleText' THEN 'SampleText' END
  ,SPE.Gender
  ,SPE.[Status]
  ,CASE
    WHEN SEE.PlanCode = 'MED' THEN 'MED 16'
    WHEN SEE.PlanCode = 'MEDP' THEN 'MEDPlus 16'
    WHEN SEE.PlanCode = 'MEDH' THEN 'MEDHeavy 16'
    WHEN SEE.PlanCode = 'MEDHP' THEN 'MEDHeavyPlus 16'
    WHEN SEE.PlanCode = 'MVP' THEN 'MVP 16'
    ELSE NULL
   END
  ,'4'
  ,CASE
    WHEN SEE.TierCode =  'EO' THEN 'E'
    WHEN SEE.TierCode =  'ESP' THEN 'ES'
    WHEN SEE.TierCode =  'ECH' THEN 'EC'
    WHEN SEE.TierCode =  'EFam' THEN 'F'
    ELSE NULL
   END
  ,'4'
  ,SPE.DepartmentCode
  ,CONVERT(NVARCHAR(10), SPE.HireDate,                  101)
  ,CONVERT(NVARCHAR(10), COEP.BenefitsEffectiveDate,    101)
  ,CONVERT(NVARCHAR(10), SEE.EffectiveDate,             101)
  ,CONVERT(NVARCHAR(10), SEE.StopDate,                  101)
  ,CASE WHEN NULLIF(LTRIM(SPE.TerminationDate), '') IS NOT NULL AND SEE.LifeEventActionID IS NOT NULL THEN CONVERT(VARCHAR(4), SEE.LifeEventActionID)
        WHEN NULLIF(LTRIM(SPE.TerminationDate), '') IS NOT NULL AND SEE.LifeEventActionID IS NULL THEN 'AI'
        ELSE ''
   END

  ,SEE.EnrollerID
  ,'1'
  ,(SEE.IssCost * 12 / SPE.PayCycle)
  ,CASE WHEN SPE.PayCycle = 52 THEN 'Weekly'
        WHEN SPE.PayCycle = 12 THEN 'Monthly'
        WHEN SPE.PayCycle = 24 THEN 'Semi-Monthly'
        ELSE 'Other'
   END
  ,SPE.WorkPhone
  ,SPE.HomePhone
  ,SPE.Email
  ,ISNULL(SPE.HeightInInches, '')
  ,ISNULL(SPE.WeightInPounds, '')

FROM Snapshot.EmployeeElection SEE
  JOIN Snapshot.PersonEmployee SPE
    ON  SEE.EmployeeID = SPE.AssignedID AND
        SEE.ConfirmationID = SPE.ConfirmationID AND
        SEE.CaseOpenEnrollmentPeriodID = SPE.CaseOpenEnrollmentPeriodID AND
        SEE.LoadDateTime = SPE.LoadDateTime
  JOIN CaseOpenEnrollmentPeriod COEP
    ON COEP.CaseOpenEnrollmentPeriod_ID = SEE.CaseOpenEnrollmentPeriodID
WHERE SEE.LoadDateTime = @MostRecentSnapshotTime
  AND PlanID <> 8
  AND SPE.ConfirmationID > 0;

Here is the XML execution plan. I am new to execution plans, so I am not sure if this is the info you need or not.


texts: Calculating sum of multiple columns in pandas

texts:
I have data from one data provider in very thin demographic units: Adults_18_21,Adults_22_24,Adults_25_27, etc.

Then in the original data frame that is built like this:

DemoDF = pd.DataFrame({'City':['NYC','Chicago','Nash'],'Adults_18_21':    [100,50,75],'Adults_22_24':[200,300,400],'Adults_25_27':[300,100,200]})

From another data provider, we get larger buckets of advertising data, Adults_18_27.

AdvertisingDF = pd.DataFrame({'City':     ['NYC','Chicago','Nash'],'Adults_18_27':[1,2,3]})

To multiply ad rates by demographic, I am currently creating a dictionary of tuples:

Compare_Buckets = {
'Adults_18_27':('Adults_18_21','Adults_22_24','Adults_25_27')
}

Then creating new columns based on the tuples:

for key in Compare_Buckets.keys():
        DemoDF[key] = 0
        for value in Compare_Buckets[key]:
            DemoDF[key] += DemoDF[value]

I can then take the new resulting column and join it with the AdvertisingDF based on city and do any further functions I need. There are 40+ keys in the dictionary so I thought the for loop would work best. Is there a better way or a more memory efficient way?


texts: Displaying all substrings of some given string

texts:
I solved exercise 8 from Core Java for Impatient, chapter 1. This exercise is to implement a displayAllCombinations method to display all substrings of the given string.

I would like to prove that following algorithm is valid in Java. I wonder if there is an easier solution?

package pl.hubot.exercises.corejava.r01.ex08;

import java.util.Scanner;

/**
 * This program contains mine solutions of exercises
 * from book Core Java for the Impatient, chapter 1.
 *
 * The content of following exercise:
 * "Write a program that reads a string and displays all contained
 * in it non-empty strings."
 *
 * @version 1.00 23-07-2016
 * @author Hubot
 */
public class Program
{
    public static void main(String[] args)
    {
        System.out.print("Enter any string: ");
        Scanner in = new Scanner(System.in);
        String text = in.nextLine();
        displayAllCombinations(text);
    }

    private static void displayAllCombinations(String text)
    {
        int offset = 0;
        int current = 0;
        int ending = text.length();
        while (offset != ending)
        {
            String result = text.substring(current, ending - offset);
            if (!result.equals(""))
                System.out.println(result);
            if (current != (ending - offset)) current++;
            else
            {
                current = 0;
                offset++;
            }
        }
    }
}

Sample run:

Enter any string: Amy
Amy
my
y
Am
m
A


texts:
import string
def charRange(mini, maxi, step=1):
  if mini in string.ascii_uppercase:
    strg = string.ascii_uppercase
  else:
    strg = string.ascii_lowercase
  return (strg[i] for i in
          range(string.ascii_lowercase.index(mini.lower()),
                string.ascii_lowercase.index(maxi.lower())+1,
                step))

Examples of usage:

for i in charRange('A', 'Z'):
    print(i)
> A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
for i in charRange('a', 'h'):
  print(i, end=' ')
> a b c d e f g h
for i in charRange('A', 'J', 2):
  print(i, end=' ')
> A C E G I


texts: How Jackson object attributes attain @NonNull annotation?

texts:
import com.fasterxml.jackson.annotation.*;
import lombok.*;

@Data @NoArgsConstructor // lombok
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DataClass {
    @JsonProperty("name")
    private String name;

}

public class Test {

 public void createDataClass(String name) {
  DataClass dataClass = new DataClass();
  dataClass.setName(name);  // This statement gives warning image below.
 }

 public void createDataClass_noWarnings(String name) {
  DataClass dataClass = new DataClass();
  if(name != null) {
    dataClass.setName(name);
  }
 }

}

This needs null-check every time a setter method is called. The attributes for the DataClass is automatically attaining @NonNull annotation. The solution seems to be explicitly mentioning @Nullable on each parameter or to make the code dirty with the if condition.
Can you help me understand how the attribute attained the @NonNull annotation? Please share if you know any other approach to avoid the null check for setter methods.


texts: Implementing a c++ Kafka producer based on librdkafka

texts:
To practice my c++ I decided to implement a simple Kafka producer to wrap the producer in c in librdkafka library. I just want to get your opinion on the way I have implemented teh default, copy and move constructors and make sure what I'm doing is safe.

Default constructor:

kafka_publisher::kafka_publisher(const std::string &brokers,
                                 const std::string &topic)
{
    m_errstr = new char[512];
    m_config = rd_kafka_conf_new();

    if (rd_kafka_conf_set(m_config,
                          "bootstrap.servers",
                          brokers.c_str(),
                          m_errstr,
                          sizeof(m_errstr)) != RD_KAFKA_CONF_OK) {
        std::string msg = "Failed to initialize Kafka configuration. Caused by ";
        throw std::invalid_argument(msg.append(m_errstr));
    }

    m_publisher = rd_kafka_new(RD_KAFKA_PRODUCER,
                               m_config,
                               m_errstr,
                               sizeof(m_errstr));

    if (!m_publisher) {
        std::string msg = "Failed to initialize Kafka publisher. Caused by ";
        throw std::runtime_error(msg.append(m_errstr));
    }

    m_topic = rd_kafka_topic_new(m_publisher, topic.c_str(), nullptr);

    if (!m_topic) {
        std::string msg = "Failed to initialize Kafka topic. Caused by ";
        throw std::runtime_error(msg.append(rd_kafka_err2str(rd_kafka_last_error())));
    }
}

Copy constructor:

kafka_publisher::kafka_publisher(const kafka_publisher &p)
: m_run(p.m_run),
  m_config(p.m_config),
  m_publisher(p.m_publisher),
  m_topic(p.m_topic)
{
    strcpy(m_errstr, p.m_errstr);
}

Move constructor:

kafka_publisher::kafka_publisher(kafka_publisher &&m)
: m_run(m.m_run),
  m_errstr(m.m_errstr),
  m_config(m.m_config),
  m_publisher(m.m_publisher),
  m_topic(m.m_topic)
{
    m.m_run = 0;
    m.m_errstr = nullptr;
    m.m_config = nullptr;
    m.m_publisher = nullptr;
    m.m_topic = nullptr;
}

In case if it's helpful, the declaration for this class is:

class kafka_publisher {
public:
    kafka_publisher(const std::string &brokers,
                    const std::string &topic);
    kafka_publisher(const kafka_publisher &p);
    kafka_publisher(kafka_publisher &&m);

    kafka_publisher &operator=(const kafka_publisher &p);
    kafka_publisher &operator=(kafka_publisher &&m);

    ~kafka_publisher();

    void publish(std::string &message);
    void stop() { m_run = 0; };

private:
    int m_run = 1;
    char *m_errstr;

    rd_kafka_conf_t *m_config;
    rd_kafka_t *m_publisher;
    rd_kafka_topic_t *m_topic;
};

Really appreciate your time and effort and helping me improve my c++. Thank you.