texts:
This is a very basic timer that can support multithreading with std::thread and std::chrono.

The timer has the classic functions: start() and stop().

The start() method creates an independent thread (if multithread support is enabled), then sleep the thread for a given Interval, then execute Timeout function. This method sets the running flag to true.

If singleShot flag is not enabled the sleepThenTimeout process is called while a running flag is true.

If multithread support is not enabled, the current thread is sleep.

The stop() method just sets the running flag to false and join the thread.

My doubt is about threat-safety.  I've just started to learn how multithreading works, so I'm not sure if I must use mutexes or something like that.

Any other type of feedback are welcome!

Timer.h

#ifndef TIMER_H
#define TIMER_H

#include <thread>
#include <chrono>

class Timer
{
public:
    typedef std::chrono::milliseconds Interval;
    typedef std::function<void(void)> Timeout;

    Timer(const Timeout &timeout);
    Timer(const Timeout &timeout,
          const Interval &interval,
          bool singleShot = true);

    void start(bool multiThread = false);
    void stop();

    bool running() const;

    void setSingleShot(bool singleShot);
    bool isSingleShot() const;

    void setInterval(const Interval &interval);
    const Interval &interval() const;

    void setTimeout(const Timeout &timeout);
    const Timeout &timeout() const;

private:
    std::thread _thread;

    bool _running = false;
    bool _isSingleShot = true;

    Interval _interval = Interval(0);
    Timeout _timeout = nullptr;

    void _temporize();
    void _sleepThenTimeout();
};

#endif // TIMER_H

Timer.cpp

#include "Timer.h"

Timer::Timer(const Timeout &timeout)
    : _timeout(timeout)
{
}

Timer::Timer(const Timer::Timeout &timeout,
             const Timer::Interval &interval,
             bool singleShot)
    : _isSingleShot(singleShot),
      _interval(interval),
      _timeout(timeout)
{
}

void Timer::start(bool multiThread)
{
    if (this->running() == true)
        return;

    _running = true;

    if (multiThread == true) {
        _thread = std::thread(
                    &Timer::_temporize, this);
    }
    else{
        this->_temporize();
    }
}

void Timer::stop()
{
    _running = false;
    _thread.join();
}

bool Timer::running() const
{
    return _running;
}

void Timer::setSingleShot(bool singleShot)
{
    if (this->running() == true)
       return;

    _isSingleShot = singleShot;
}

bool Timer::isSingleShot() const
{
    return _isSingleShot;
}

void Timer::setInterval(const Timer::Interval &interval)
{
    if (this->running() == true)
       return;

    _interval = interval;
}

const Timer::Interval &Timer::interval() const
{
    return _interval;
}

void Timer::setTimeout(const Timeout &timeout)
{
    if (this->running() == true)
       return;

    _timeout = timeout;
}

const Timer::Timeout &Timer::timeout() const
{
    return _timeout;
}

void Timer::_temporize()
{
    if (_isSingleShot == true) {
        this->_sleepThenTimeout();
    }
    else {
        while (this->running() == true) {
            this->_sleepThenTimeout();
        }
    }
}

void Timer::_sleepThenTimeout()
{
    std::this_thread::sleep_for(_interval);

    if (this->running() == true)
        this->timeout()();
}

main.cpp

#include <iostream>

#include "Timer.h"

using namespace std;

int main(void)
{
    Timer tHello([]()
    {
        cout << "Hello!" << endl;
    });

    tHello.setSingleShot(false);
    tHello.setInterval(Timer::Interval(1000));
    tHello.start(true);

    Timer tStop([&]()
    {
        tHello.stop();
    });

    tStop.setSingleShot(true);
    tStop.setInterval(Timer::Interval(3000));
    tStop.start();

    return 0;
}


texts:
I've written an asynchronous retry method as an answer for this question. I'd like to get your opinion of the implementation and whether there are better ways to implement this. You could also implement this with async-await but I thought this would be a more efficient implementation.

public static Task RetryAsync(Func<bool> retryFunc, CancellationToken cancellationToken, int retryInterval)
{
    var tcs = new TaskCompletionSource<object>();

    var timer = new Timer((state) =>
    {
        var taskCompletionSource = (TaskCompletionSource<object>)state;

        if (!taskCompletionSource.Task.IsCompleted)
        {
            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    taskCompletionSource.SetException(new TaskCanceledException("RetryAsync cancelled"));
                }
                else if (retryFunc())
                {
                    taskCompletionSource.SetResult(null);
                }
            }
            catch (Exception ex)
            {
                taskCompletionSource.SetException(ex);
            }
        }

    }, tcs, 0, retryInterval);

    //// Once the task is complete, dispose of the timer so it doesn't keep firing.
    tcs.Task.ContinueWith(t => timer.Dispose(),
                          CancellationToken.None,
                          TaskContinuationOptions.ExecuteSynchronously,
                          TaskScheduler.Default);

    return tcs.Task;
}


texts: Git tag release build files and reset to commit without

texts:
This is part of a library that wants to release builded files (eg dist/*) when published to npm and bower. However, I don't want to commit those builded files for obvious reasons. Bower uses tags, and so I need tag to hold a version that contains builded files.

I didn't think twice, and that's what I came up with:

#!/bin/bash
[[ '' == $1 ]] && echo "Please provide patch, minor, major argument" && exit 1

# build dist files
gulp
# use npm to get the next semver (ie npm version patch increments patch number)
# --no-git-tag-version is to avoid any git interactions
newver=$(npm --no-git-tag-version version $1)

# dist files are ignored, adding them with the updated package.json
git add -f dist package.json

# commit and tag the new version with dist files
git commit -m $newver
git tag $newver

# publish on npm
npm publish

# reset the latest commit
git reset --hard HEAD~1

# issue the npm command again so that package.json gets updated
newver=$(npm --no-git-tag-version version $1)

# only add the package.json, dist files are gone
git add package.json

# commit and push tags
git commit -m $newver
git push --tags
git push

I'm wondering if this would be considered as a bad-practice, if there is something I could improve, or if someone has a better idea on how to do this. It's working great, but is having a tag that refers to an overridden commit a good idea?


texts:
I'm consuming some messages from a rabbit queue. Within the consumer/processor I need to invalidate a varnish cache and requeue the message if the purge failed.
I'm using a local purge proxy.
The consumer is a Dropwizard microservice but I'm using a BasicHttpClient because JerseyClient doesn't allow me (AFAIK) to set PURGE as http verb.

I'm trying to improve my error handling.. Is throwing an IllegalStateException fine or should I improve it?
Thanks

public void invalidateVarnishCache( String level, String idUrl ) throws IOException {
    try{
        String xPurgeRegex = level+"/"+idUrl+"$";
        Header header = new BasicHeader( "X-Purge-Regex", xPurgeRegex );
        BasicHttpRequest purgeRequest = new BasicHttpRequest("PURGE", "/" );
        purgeRequest.setHeader(header);

        LOGGER.log( LogEntries.VarnPurge, level, idUrl, host, xPurgeRegex );

        response = httpClient.execute(host, purgeRequest);

        entity = response.getEntity();

        int statusCode = response.getStatusLine().getStatusCode();

        if( !is2XXResponse( statusCode ) ){

            int respLength = entity.getContent().available();
            byte[] errorResp = new byte[ respLength ];
            entity.getContent().read(errorResp, 0, respLength);

            LOGGER.log( LogEntries.VarnPurgeErrResp, statusCode, new String(errorResp) );

            throw new IllegalStateException("Varnish local proxy returned response with status code "+statusCode+" from Varnish backend. Consumed message will be requeued.");
                      /////////////////////
        }else{
            LOGGER.log( LogEntries.VarnPurgeSuccessResp, statusCode );
        }

        EntityUtils.consume(entity);

    }catch( IOException ex ){
        LOGGER.log( LogEntries.VarnPurgeException, ex );
        throw ex;
    }
}

This is the consumer..

public MessageResult apply(UpdateMessage t) {

    if( !agentValidator.validMessage( t ) ){
        return MessageResult.ACK; // discard message
    }

    String urlRequest = t.getLink();

    String[] splitted = urlRequest.split( "/", -1 );
    String level = splitted[2];
    String idUrl = splitted[3];

    try{
        // Varnish cache purge. It will requeue if purge fails for any reason.
        try{
            pcsConnector.purgeVarnishBeforePcsRequest( level, idUrl );
        }catch(Exception e){

            LOGGER.log( LogEntries.PurgeError, host, urlRequest, e );
            return MessageResult.NACK_REQUEUE;
        }

        // retrieve resource from ohter microservice
        try{
            response = connector.getLatestStateOfResource( urlRequest );
        }catch(Exception e){

            LOGGER.log( LogEntries.DBServiceError, pcsHost, urlRequest, e );
            return MessageResult.NACK_REQUEUE;
        }

        // .....
        // more logic
        // ....

    }catch(Exception e){

        LOGGER.log( LogEntries.MsgProcessingError, t.toString(), e );
        return MessageResult.NACK_REQUEUE;
    }

    LOGGER.log( LogEntries.MsgConsumedSuccess, t.toString() );

    return MessageResult.ACK; // SUCCESS. Remove message from queue.

}


texts: Is this a good way to receive a message from a server?

texts:
I am developing some software that uses a pretty ancient low-level TCP/IP protocol from (I think) the eighties. I can send messages to the server very reliably, but I am a little unsure about receiving them. I cannot predict when the server will send me a message, so I have this method in an infinite loop. GetNextMessage() blocks the thread until it receives a message, whereupon the message is acted upon, and the loop repeats.

Messages are sent at a rate of about maybe 5 or 6 a minute, and I can process them in less than a quarter of a second, so I'm not currently spinning off a new thread when I receive them.

This code fragment contains all the relevant symbols and the logic that I am unsure of:

    /// this is filled earlier in the program
    private Socket _socket;

    private const int BufferSize = 4096;

    /// <summary>
    /// This byte (hex 02) indicates the start of the message.
    /// </summary>
    private const byte RecordStart = 2;

    /// <summary>
    /// This byte (hex 03) indicates the end of the message.
    /// </summary>
    private const byte RecordEnd = 3;

    private string GetNextMessage()
    {
        byte[] bytesReceived = new byte[BufferSize];

        // ReSharper disable PossibleNullReferenceException
        _socket.Receive(bytesReceived);
        // ReSharper restore PossibleNullReferenceException

        if (_socket.Poll(1, SelectMode.SelectRead))
        {
            throw new SocketException((int)SocketError.ConnectionReset);
        }

        IEnumerable<byte> bytes = bytesReceived
            .Where(character => character != RecordStart)
            .TakeWhile(character => character != RecordEnd);

        return Encoding.ASCII.GetString(bytes.ToArray());
    }

My concerns:

I am not sure if _socket.Poll() is the correct way to determine if the socket has gone away. It most certainly works and is very necessary, but I'm sure I should be doing something else.
I once performed an operation that sent three messages immediately after each other, but I only appeared to receive two of them. It is possible that there is a bug in the product I am developing for (seems likely), but I am worried that the method I have chosen is somehow causing messages to be discarded.


texts: Find numbers that are both Triangle numbers and Square numbers

texts:
I've written a simple JavaScript function to find numbers that contain both the attributes of a Triangle (\$ n(n+1)/2 = x \$) and a Square (\$ n^2 = x \$) number.
The challenge was given in Matt Parker's Things to Make and Do in the Fourth Dimension.

function main() {
  for (var i = 1; i < 1000000; i++) {
    var triangled = ( i * ( i + 1 ) ) / 2;
        if(Math.sqrt(triangled) % 1 === 0) {
         // print
      }
  }
}

Here's the JSFiddle of the same.

The algorithm n = 1000000 takes about ~35ms but gets considerably slower with higher values

~300ms for n = 10000000

~3000ms for n = 100000000

The only priority is performance. Any tips?


texts: Type Name or Alias via Reflection for TT Code Generation

texts:
I was working on some TT code generation to get rid of mundane C# codings in VS2013 Express Edition, and after researching online, created the following helper methods to facilitate Type declarations.

I am able to use it successfully in my code generation but wonder if they can be improved further or if there's any scenario which they do not cater for.

public static String GetActualTypeName(Type type, bool bAlias = true, bool bFullQualified = false)
{
    Type nullable = Nullable.GetUnderlyingType(type);
    String name = null;

    if (nullable != null) // handles Nullable types
    {
        name = (bAlias) ? GetAliasName(nullable, bFullQualified)
            : (bFullQualified) ? nullable.FullName : nullable.Name;

        return String.Format("{0}?", name);
    }

    if (!type.GenericTypeArguments.Any()) // handles non generic types
    {
        name = (bAlias) ? GetAliasName(type, bFullQualified)
            : (bFullQualified) ? type.FullName : type.Name;

        return name;
    }

    name = (bFullQualified) ? type.FullName : type.Name;

    // recrusive looping into generic type tree for the required type names
    String[] names = type.GenericTypeArguments
        .Select(t => GetActualTypeName(t, bAlias, bFullQualified))
        .ToArray();

    return String.Format("{0}<{1}>", name.Substring(0, name.IndexOf('`')), String.Join(",", names));
}

public static String GetAliasName(Type type, bool bFullQualified = false)
{
    String alias = null;

    using (var provider = new Microsoft.CSharp.CSharpCodeProvider())
    {
        var typeRef = new System.CodeDom.CodeTypeReference(type);

        alias = provider.GetTypeOutput(typeRef);
    }

    int index = alias.LastIndexOf(".");

    if (bFullQualified || index == -1)
        return alias;

    return alias.Substring(index + 1);
}


texts:
I'm working on a parser library for substituting strings in dictionaries, with things like globals etc. Wanting to get opinions on the direction I'm taking and where I can improve the script. This currently works

class DictParser(object):
    def __init__(self, dictionary):
        self.working_dict = dictionary

    def __traverse(self, obj, callback=None):
        if isinstance(obj, dict):
            return {k: self.__traverse(v, callback) for k, v in obj.items()}
        elif isinstance(obj, list):
            return [self.__traverse(elem, callback) for elem in obj]
        else:
            if not callback:
                return obj
            else:
                return callback(obj)

    def replace_with_global_var(self, pattern):
        pattern_variable = re.compile(pattern)

        def substitute(x):
            if x.group(1) in globals():
                return globals()[x.group(1)]
            else:
                raise IndexError('Missing Global: %s' % x.group(1))

        def transformer(item):
            if isinstance(item, str):
                return pattern_variable.sub(substitute, item)
            else:
                return item

        self.working_dict = self.__traverse(self.working_dict, callback=transformer)

    def retrieve(self):
        return self.working_dict

Usage:

a = 'blah'

my_dict = {
    'test': '((a))',
    'another': 'my ((a)) test',
    'nested': {
        'child': 'here is ((a)) ((a))'
    },
    'boo': 1,
    'test': False
}

d = DictParser(my_dict)
d.replace_with_global_var(r'\(\((.+?)\)\)')
print(d.retrieve())

This was a reasonably quick hack together, tried using repl so I could print the d variable directly but didn't quite work out.


texts: Quick Sum TopCoder (Brute Force solution)

texts:
Given a string of digits, find the minimum number of additions
  required for the string to equal some target number. Each addition is
  the equivalent of inserting a plus sign somewhere into the string of
  digits. After all plus signs are inserted, evaluate the sum as usual.
  For example, consider the string "12" (quotes for clarity). With zero
  additions, we can achieve the number 12. If we insert one plus sign
  into the string, we get "1+2", which evaluates to 3. So, in that case,
  given "12", a minimum of 1 addition is required to get the number 3.
  As another example, consider "303" and a target sum of 6. The best
  strategy is not "3+0+3", but "3+03". You can do this because leading
  zeros do not change the result.

  Write a class QuickSums that contains the method minSums, which takes
  a String numbers and an int sum. The method should calculate and
  return the minimum number of additions required to create an
  expression from numbers that evaluates to sum. If this is impossible,
  return -1.

  TopCoder link

So I came up with a brute force solution of checking all possible solutions to find the min. Is there a better way to do this?

public class QuickSums {

  public static void main(String args[]) {
    String input = "99999";
    int total = 45;
    int res = minSums(input, total);
    System.out.println(res);
  }

  // With at most 10 digits(constraint given), there are at most 2^9 ways to insert plus signs into the string.
  // Therefore, there are at most 2^9 possibilities to consider. We can use recursion to go through
  // all possibilities and keep track of the minimum number of additions required
  public static int minSums(String numbers, int sum) {
    int N = numbers.length();

    // base cases
    if (N <= 3 && sum == Integer.parseInt(numbers)) {
      return 0;
    }

    else if (N == 2 && Integer.parseInt(numbers.substring(0, N - 1))
        + Integer.parseInt(numbers.substring(N - 1)) == sum) {
      return 1;
    } else if (N == 2 && Integer.parseInt(numbers.substring(0, N - 1))
        + Integer.parseInt(numbers.substring(N - 1)) != sum) {
      return -1;
    }
    else if (N == 1 && Integer.parseInt(numbers) != sum) {
      return -1;
    }

    // solution
    else {

      int lenOFStr = N-1;
      int possibleCombination = (int) Math.pow(2, lenOFStr);

      // numbers will contain between 1 and 10 characters, inclusive.
      int min = Integer.MAX_VALUE;
      StringBuilder tempString;
      for (int i = 0; i < possibleCombination; i++) {
        String plus = Integer.toBinaryString(i);
        while (plus.length() < lenOFStr) {
          plus = "0" + plus;
        }
        // System.out.println(plus);

        // Add plus sign to the string
        tempString = new StringBuilder(numbers);
        int len = N;
        for (int k = 0; k < lenOFStr ; k++) {
          if (plus.charAt(k) == '1') {
            len = len + 1;
            int offset = len-N+k;
           // System.out.println(offset);
            tempString.insert(offset, " ");
          }
        }
        // System.out.println(tempString);

        // compute the sum
        String[] arr = tempString.toString().split(" ");
        long tempSum = 0;
        for (String s : arr) {
          tempSum +=Long.parseLong(s);
        }

        // check if the sum is same
        if (tempSum == sum) {
          min = Math.min(arr.length-1, min);
        }

      }
      return (min == Integer.MAX_VALUE) ? -1 : min;

    }
  }

}

This program works fine for all inputs but I'm wondering, there must be a dynamic programming solution to this? Or something better?


texts: Performing several hundred raster multiplications

texts:
I have several hundred "A" rasters, numbered from 001_A.tif to 100_A.tif.

I also have several hundred "B" rasters, numbered from 001_B.tif to 100_B.tif.

I want to multiply them like this:

001_A * 001_B = 001_result
002_A * 002_B = 002_result
003_A * 003_B = 003_result
.
.
.

I have a loop in R which works fine, but it is relatively slow:

library(raster)

A_Files <- list.files(pattern="A.tif") # files A
All_A <- unique(A_Files)

B_Files <- list.files(pattern="B") # files B
All_B <- unique(B_Files)

for (i in 1:100) {
  A.i <- All_A[i]
  B.i <- All_B[i]

  Raster_A.i <- raster(A.i) # create rasters from files A
  Raster_B.i <- raster(B.i) # create rasters from files B

  Result.i <- (Raster_A.i * Raster_B.i) # multiplying A by B

  writeRaster(Result.i, paste(A.i, "_result.tif", sep = ""), datatype='FLT4S',
 overwrite=TRUE) # write results in .tif format with the name "001_A_result.tif"
    }

Is there a way to speed it up?


texts: Find all words beginning with a given prefix

texts:
Today I present some code for finding all words that
begin with a given prefix and some simple test cases for review.

from itertools import chain

sentinel = object()

def insert(tree, word):
    for letter in chain(word, [sentinel]):
        tree = tree.setdefault(letter, {})

def words_beginning_with(start, tree):
    for letter in start:
        try:
            tree = tree[letter]
        except KeyError:
            return
    for word in _all_words(tree):
        yield start + word

def _all_words(tree, start=''):
    for letter, tree in tree.items():
        if letter is sentinel:
            yield start
        else:
            for word in _all_words(tree, start+letter):
                yield word

def test_tree():
    # Simple tests
    tree = {}

    assert [] == list(words_beginning_with('foo', tree))

    insert(tree, 'foo')
    assert {'f': {'o': {'o': {sentinel: {}}}}} == tree

    assert ['foo'] == list(words_beginning_with('foo', tree))

    insert(tree, 'food')
    assert {'f': {'o': {'o': {sentinel: {},
                              'd': {sentinel: {}}}}}} == tree

    assert sorted(['foo', 'food']) == sorted(words_beginning_with('fo', tree))

    insert(tree, 'foody')
    assert sorted(['foo', 'food', 'foody']) == sorted(
        words_beginning_with('fo', tree))

    insert(tree, 'fold')
    assert sorted(['foo', 'fold', 'food', 'foody']) == sorted(
        words_beginning_with('fo', tree))

if __name__ == "__main__":
    test_tree()

I appreciate brutal and honest feedback the most, thanks.


texts: Scale an image to fit some maximum dimension using vanilla JavaScript code

texts:
Fill in the ? with a Javascript expression to set the scale ratio for
  an image having a given height and width so that it fit inside a
  maxdim-by-maxdim square area (touching at least two edges).

function scaleImage(width, height, maxdim) {
  var scale = ?;
  return [scale * width, scale * height];
}

Here is my solution:

function scaleImage(width, height, maxdim) {
  var scale = (width > height ? maxdim/width : maxdim/height);
  return [scale * width, scale * height];
}

Is there a cleaner way of doing this?


texts:
Looking for feedback on how to better improve the code below to simplify the code below.

var animateTop = $('body');
if ($('html').hasClass('lt-ie9')) {
    animateTop = $('html');
}
$('.var').on('click', function() {
    animateTop.animate({
        scrollTop: $('footer').offset().top
    }, {
    queue: false,
    duration: 1500,
    complete: function() {
        if(!$('.foo').hasClass('active')) {
            $('.foo').toggleClass('active');
            $('.bar').slideToggle();
        }
    }
});
return false;
});


texts:
Several times we need to be able to revert the data the user is inserting to a previous state (cancel data update). In order to keep DRY and for the sake of separation of concerns I thought about a way of just allowing that.

public class RevertableObject<T> : ViewModelBase //implements INotifyPropertyChanged
    where T:class, ICloneable
{
    public RevertableObject(T initialValue)
    {
        Value = initialValue;
        Value = initialValue.Clone() as T;
    }

    private T _oldValue;
    private T _currentValue;
    public T Value
    {
        get { return _currentValue; }
        private set
        {
            _oldValue = _currentValue;
            _currentValue = value;
            OnPropertyChanged();
        }
    }

    public void Revert()
    {
        Value = _oldValue;
    }
}

Some drawbacks of this solution are, but are not limited to:

Dependency on the interface ICloneable which does not have a way of knowing the cloning algorithm being used (member clone vs deep clone)
It only allows one object to be reverted once.

Any insights of better alternatives? Is this code acceptable?


texts:
Currently, I am in the process of optimizing a MIPS assembly program that takes a n x n matrix and multiplies it with its transpose. I am trying to optimize my matrix calculation algorithm so that it completes in as few clock cycles as possible. I have been given the A matrix, with its values stored in RAM. I must then calculate B=A*transpose(A).

There are a few caveats:

The matrix multiplication must be the dot product of the ith row of A and the jth column of B. It is not meant to be the element-wise multiplication. See the Wikipedia article.
I am not to make my algorithm more mathematically efficient then the un-modified example I will show below. I.e. I cannot exploit the symmetric nature resulting when you multiply a matrix with its transpose.

Here is the pseudo code example I have been given:

// Given array A which is unsigned int A[n*n] (ie word or 32 bit form)
// Reset array B which is unsigned int B[n*n] (ie word or 32 bit form)
for(int i = 0; i < (n * n); i++)
{
    B[i] = 0;
}

// Matrix Multiplicaiton B = A*A'
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        for (int k = 0; k < n; k++)
        {
            B[i + n * j] = B[i + n * j] + A[i + n * k] * A[j + n * k];
        }
    }
}

Here is my attempt at optimizing the above example:

// Given array A which is unsigned int A[n*n] (ie word or 32-bit form)

// Matrix Multiplicaiton B = A*A'
for(int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        temp = 0;
        n_times_i = n * i;

        for (int k = 0; k < (n*n); k+=n)
        {
            temp += A[j + k] * A[i + k];
        }

        B[j + n_times_i] = temp;
    }
}

As you can see, I have swapped things around to avoid unnecessary calculations where possible.

However, I was wondering whether anyone can see any other way of speeding things up? I.e. Cleverly swapping the order of the loops, etc.

Any help would be greatly appreciated!


texts:
The aim of this code, written in Python3.6, was to write a function that will non-recursively walk over a N-branching tree structure.

It works by using a list of indices that keep track of visited nodes and by retracing prior steps when a tree branch ends. The function non_recurs visits nodes top down left to right (as far as I can tell).

non-recurs allows the caller to provide a function to the func argument which will be applied to to each node. The end_only argument will determine if the supplied function will be applied to all nodes (end_only=False) or only nodes at the end of branches (end_only=True).

1st I would like to know if this attempt is actually capable of walking over N-branching trees and 2nd I would like to know what you think about my implementation.

NOTE: There are two sections to my code below. The first is to generate N-branching trees and is not the focus of this code review. But is required to generate my demonstrated output

EDIT

I added IndexError to the except of the try block

tree generation code

from itertools import product

# CODE to create test tree's for walking
def assign(tree, idx, value):
    new_idx = idx[:]
    assignment_idx = new_idx.pop()
    ref = tree
    for i in new_idx:
        ref = ref[i]
    ref[assignment_idx] = value
    return tree

def n_branch_tree(height, branches):
    idx = ([i] for i in range(branches))
    tree = list(range(branches))
    count = 0
    node = 0
    while count < height:
        for i in idx:
            # mutates tree
            assign(tree, list(i), list(range(node, node+branches)))
            node += branches
        count += 1
        idx = product(range(branches), repeat=count)
    return tree

tree walk code

# Code to walk over tree

def walk(tree, idx):
    """Return tree node at provided index

    args:
        tree: tree to index
        idx: index of desired node

    returns: node
    """
    for i in idx:
        tree = tree[i]
    return tree

def non_recurs(tree, func=print, branches=2, end_only=True, ):
    """Non-recursively walk n-branching tree

    args:
        tree: n-branching tree
        func: function that takes tree node as first argument
        branches: The number of branches each node has
        end_only: Default is True. When  True will only apply func to
                end nodes. When False will apply func to all Nodes

    """
    branches = branches - 1  # Because index's start at 0
    idx = [0]
    node = None
    while True:
        # print(idx)
        try:
            node = walk(tree, idx)
        except (TypeError, IndexError):
            # Could not find node at index
            try:
                # Walk back up tree until a node has not
                # been fully explored
                while idx[-1] == branches:
                    idx.pop()
            except IndexError:
                # Means all nodes in index have been fully explored
                break

            # Increase index if current index is under node branch limit
            if idx[-1] < branches:
                idx[-1] += 1

            # Apply func to end node
            if end_only and node:
                func(node)
                node = None
        else:
            idx.append(0)

            # Apply func to all nodes
            if not end_only:
                func(node)

if __name__ == '__main__':

        tree = n_branch_tree(height=3, branches=3)

        print(tree)

        value_store = []

        non_recurs(tree, func=value_store.append, branches=3, end_only=True)

        print(value_store)

Outputs

[[[18, 19, 20], [21, 22, 23], [24, 25, 26]], [[27, 28, 29], [30, 31, 32], [33, 34, 35]], [[36, 37, 38], [39, 40, 41], [42, 43, 44]]]
[18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]


texts: angular service for centralizing common grid functions

texts:
I have an angular 7 app that is data focused and as a result has dozens of grids.  These grids are from the Kendo UI for ANgular component library made by Telerik.  These grid components expose hooks for the sort, filter, group functions of the grid.  90% of the grids I have are a very simple CRUD grid with next to no validation or business logic involved.

As a result, I have to write the following code (Typescript) over and over for each grid:

 public initData(): void {
    this.gridData = process(this.data, this.gridState);
  }

  public onStateChange(state: DataStateChangeEvent): void {
    state.group.map(group => (group.aggregates = this.aggregates));
    this.gridState = state;
    this.gridData = process(this.data, this.gridState);
  }

  public groupChange(grp: GroupDescriptor[]): void {
    this.groups = grp;
    this.gridData = process(this.data, this.gridState);
  }

  public sortChange(srt: SortDescriptor[]): void {
    this.sort = srt;
    this.gridData = process(this.data, this.gridState);
  }

  public filterChange(fltr: CompositeFilterDescriptor): void {
    this.filter = fltr;
    this.gridData = process(filterBy(this.data, this.filter), {
      group: this.groups,
      sort: this.sort
    });
  }

this is obviously in the component class behind each grid.

What I am wondering is, Can I move the functions to a service so that I don't have to rewrite them for each component?  Additionally, should I create them as static so that there is only one or should I instantiate a new "service" for each component?

Just wondering what others think about this

Thanks


texts: Retrieving font preference setting in Eclipse JDT plugin

texts:
I have an Eclipse plugin which creates a JavaSourceViewer to visualize specific source code in a separate view.
I would like to configure the font of the viewer to match the settings of the Java Editor Text Font preference:

JavaSourceViewer textViewer = new JavaSourceViewer(...);
...

// get the SWT component which displays the text
StyledText textControl = textViewer.getTextWidget();

// retrieve the font preference from the theme manager
IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
ITheme currentTheme = themeManager.getCurrentTheme();
FontRegistry fontRegistry = currentTheme.getFontRegistry();
Font font = fontRegistry.get(PreferenceConstants.EDITOR_TEXT_FONT);

// set the font on the SWT component
textControl.setFont(font);

My question is especially about the code block which retrieves the font from the theme manager:

Is this the correct approach to get the font?
Is there anything else which needs to be considered?


texts:
I am parsing the following line of code via a specific format.
Line is:

S|111111|87654321|Bar UK|BCreace UK|GBP|24/08/2010|

The Format is:

Index    Field Length
S0 -     1
S1 -     6
S2 -     34
....
...
S6 -     10

I am validating using many if statements. Could anyone suggest a better approach?

private static StatementLineResult Validate(string delimitedRecord)
{
    if (delimitedRecord == null)
        throw new ArgumentNullException("delimitedRecord");

    var items = delimitedRecord.Split('|');
    if(items.Length != 19)
        throw new Exception("Improper line format");

    var errorMessage = new Dictionary<string, string>();

    var bankIdentifierCodes = new List<string> {"ABCDGB2L", "EFGHGB2L"};

    if (items[0].Length != 1 || items[0] != "S")
        errorMessage.Add("Record Identifier","Invalid Record Identifier");

    var sortCode = 0;
    if (!int.TryParse(items[1], out sortCode) || items[1].Length > 6)
        errorMessage.Add("Sort Code", "Invalid sort code");

    if (string.IsNullOrEmpty(items[2]) || items[1].Length > 34)
        errorMessage.Add("Account Number", "Invalid account number");

    if (string.IsNullOrEmpty(items[3]) || items[1].Length > 35)
        errorMessage.Add("Account Alias", "Invalid account alias");

    if (string.IsNullOrEmpty(items[4]) || items[1].Length > 35)
        errorMessage.Add("Account Name", "Invalid account name");

    if(string.IsNullOrEmpty(items[5]) || items[5].Length != 3)
        errorMessage.Add("Account Currency", "Invalid account currency");

    if (!string.IsNullOrEmpty(items[6]) && items[6].Length > 20)
        errorMessage.Add("Account Type", "Invalid account type");

    if(string.IsNullOrEmpty(items[7]) || items[7].Length != 8 || !bankIdentifierCodes.Contains(items[7],StringComparer.OrdinalIgnoreCase))
        errorMessage.Add("Bank Identifier Code", "Invalid bank identifier code");

    if (!string.IsNullOrEmpty(items[8]) && items[8].Length > 35)
        errorMessage.Add("Bank Name", "Invalid bank name");

    if (!string.IsNullOrEmpty(items[9]) && items[9].Length > 27)
        errorMessage.Add("Bank Branch Name", "Invalid bank branch name");

    DateTime transactionDate;
    if (!DateTime.TryParse(items[10], out transactionDate))
        errorMessage.Add("Transaction Date", "Invalid date");

    if (!string.IsNullOrEmpty(items[11]) && items[11].Length > 25)
        errorMessage.Add("Narrative Line 1", "Invalid narrative line 1");
    if (!string.IsNullOrEmpty(items[12]) && items[12].Length > 25)
        errorMessage.Add("Narrative Line 2", "Invalid narrative line 2");
    if (!string.IsNullOrEmpty(items[13]) && items[13].Length > 25)
        errorMessage.Add("Narrative Line 13", "Invalid narrative line 13");
    if (!string.IsNullOrEmpty(items[14]) && items[14].Length > 25)
        errorMessage.Add("Narrative Line 14", "Invalid narrative line 14");
    if (!string.IsNullOrEmpty(items[15]) && items[15].Length > 25)
        errorMessage.Add("Narrative Line 15", "Invalid narrative line 15");

    if(_transactionTypes.First(item=>item.TransactionType==items[16]) == null)
        errorMessage.Add("Transaction Type", "Invalid transaction type");

    decimal debitValue;
    if(items[17] != "" && !Decimal.TryParse(items[17], out debitValue))
        errorMessage.Add("Debit Value", "Invalid debit amount");

    decimal creditValue;
    if (items[18] != "" && !Decimal.TryParse(items[18], out creditValue))
        errorMessage.Add("Credit Value", "Invalid credit amount");

    return new StatementLineResult()
    {
        ErrorMessages = errorMessage,
        Data = BankLineData(delimitedRecord),
        IsValid = errorMessage.Count==0
    };
}


texts: Common function to check if an element exists

texts:
I think there is more that is needed here. Can someone please comment on it?

What I need is to add some common functions to check if an element exists.

// Common functions
$(document).ready(function() {

    /*
    Function for creating different styling checkbox, radio input, and select
    */

    // Create pretty checkboxes and inputs

    if ($('.iCheck').length){
        $('.iCheck').iCheck({
        checkboxClass: 'icheckbox_minimal-blue',
        radioClass: 'iradio_minimal-blue',
        increaseArea: '20%' // optional
    });
    }

    // Create pretty selects and multiselect
        if(!$("html").hasClass("ie8")){
            if ($('select').length){
                $('select').attr('data-width', '100%').selectpicker();
            }

        };

     /*
      Preloader
     */
    var targetPreloader = $('[data-overlay-text]');
    targetPreloader.click(function() {
        var text = $(this).attr("data-overlay-text");
        $('.preloader-text').text(text);
        $('.preloader-window').show().fadeIn();
    });

    /*
      Fix for showing SVG
     */
    svgeezy.init('nothing', 'png');

        /*
    Form validation using Jquery validate
    */
        $('form').validate({
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorElement: 'span',
        errorClass: 'help-block',
        errorPlacement: function(error, element) {
            if(element.parent('.input-group').length) {
                error.insertAfter(element.parent());
            } else {
                error.insertAfter(element);
            }
        }
    });

});


texts: parsing a flat file and removing duplicates

texts:
Have some code that I wrote to parse a flat file of IP address and other junk unwanted information. Just wanting to see if there was any way to make shorter or better.

#!/usr/bin/perl

use strict;
use warnings;

#opening the access_log flat file that contains a list of ip addresses with unwanted information after, and contains duplicate IPs
#example, "203.151.232.51 - - DateTime Junk URL Information"
open (YYY, "/home/access_log");
#assigning flat file to an array
my @incomingarray=<YYY>;

my $value = 0;

#splitting up the array and assigning variables to the pairs
foreach my $pair(@incomingarray) {
  (my $ip, my $junk) = split(/ - - /, $pair);
  $incomingarray[$value] = $ip;

  #autoincrementing the scalar
  $value++;
}

close (YYY);

#print @incomingarray;

#creating a hashlist from the array and using the map function to remove duplicates
my %IPlist = map { $_ => 1 } @incomingarray;

#creating a new array by using the keys function to loop through the hash list
my @distinctIP = keys %IPlist;

foreach (@distinctIP) {
  print "$_\n";
}


texts: Request for Comments: Singleton pattern implemented in Java

texts:
I have several utility classes who should only ever have one instance in memory, such as LogHelper, CacheHelper, etc. One instance to rule them all.

I've never implemented Singleton in Java before, so I wanted to post my first pass and see if anybody had major issues with this, or just helpful critiques.  I want to make sure that my design will have the intended affect when I go to use these singleton classes throughout my codebase.

Singleton:

public class Singleton
{
    private static Singleton instance;

    protected Singleton()
    {
        super();
    }

    public static synchronized Singleton getInstance()
    {
        if(instance == null)
            instance = instantiate();

        return instance;
    }

    // Wanted to make this abstract and let subclasses @Override it,
    // but combining 'abstract' and 'static' is illegal; makes sense!
    protected static Singleton instantiate()
    {
        return new Singleton();
    }
}

LogHelper (a singleton since all my classes will use it to write messages to the same destinations):

public class LogHelper extends Singleton
{
    protected static LogHelper instantiate()
    {
        return new LogHelper(...blah...);
    }

    public LogHelper(...blah...)
    {
        // Initialize the singleton LogHelper
    }

    // More methods for logging, etc.
}

Here's how I'd like to use it throughout my codebase:

LogHelper logHelper = LogHelper.getInstance();
logHelper.logInfo("...");

What I'm worried about is that I may have inadvertently designed this wrong and heading down the wrong avenue. Can anybody weigh-in on my design?

Thanks!


texts: Implementing basic graph theory functions in APL with matrices

texts:
I had to solve three problems on graph theory that I solved by implementing a utility function and 3 functions, one for each of the problems.

The problem set defines the input for all my functions as a E+1 x 2 matrix (they call this an edge list) where the first row V E contains the number of vertices V in the graph and the number E of edges. The other E rows contain the endpoints of edges, so a row a b means there's an edge between vertices a and b.

Degrees is a function that retrieves the degree of a given vertex; e.g. Graphs.Degrees 8 2 ⍴ 6 7 1 2 2 3 6 3 5 6 2 5 2 4 1 4 gives 2 4 2 2 2 2;
DoubleDegrees is a function that, given a vertex v, retrieves the sum of the degrees of the neighbours of v (i.e. the vertices connected to v by an edge); e.g. Graphs.DoubleDegrees 5 2⍴ 5 4 1 2 2 3 4 3 2 4 gives 3 5 5 5 0;
ConnectedComponents is a function that counts the number of connected components in the graph; e.g. Graphs.ConnectedComponents 14 2⍴12 13 1 2 1 5 5 9 5 10 9 10 3 4 3 7 3 8 4 8 7 11 8 11 11 12 8 12 gives 3.

The functions work as expected.

I'm particularly interested in feedback on the AdjacencyMatrix and on the ConnectedComponents functions. Also, I believe the DoubleDegrees and ConnectedComponents functions are sub-optimal since they use simple algorithms but make use of matrix multiplications and search algorithms would be faster (in other languages). Is this still efficient code for APL? Or would a search-based solution be more efficient?

:Namespace Graphs
    ⍝ This particular namespace contains functions related to graphs.
    ⍝ For this namespace, an 'EdgeList' is a (v+1)×2 integer matrix, with v≥0, that encodes an undirected graph:
    ⍝   The first row (v e) is the number of vertices and edges in the graph;
    ⍝   The remaining e rows have two integers ≤v representing the end points of an edge.

    AdjacencyMatrix ← {
        ⍝ Compute the adjacency matrix of a graph.
        ⍝ Monadic function expecting an 'EdgeList'.

        vertices ← ⊃1↑⍵
        edges ← (↓⌽⍪⊢) 1↓⍵
        mat ← 0⍴⍨ 2⍴ vertices
        (1@edges) mat
    }

    Degrees ← {
        ⍝ Compute the degree of a vertex of a graph.
        ⍝ Dyadic function expecting integer on the left and 'EdgeList' on the right.
        ⍝   If the left integer is missing, return the degrees of all vertices.

        ⍺ ← ⍬
        adj ← AdjacencyMatrix ⍵
        ⍺⊃+/adj
    }

    DoubleDegrees ← {
        ⍝ Compute the double degree of a vertex of a graph.
        ⍝ Dyadic function expecting an integer on the left and 'EdgeList' on the right.
        ⍝   If the left integer is missing, return the double degrees of all vertices.

        ⍺ ← ⍬
        adj ← AdjacencyMatrix ⍵
        ⍺⊃+/ +.×⍨ adj
    }

    ConnectedComponents ← {
        ⍝ Computes the number of connected components of a graph.
        ⍝ Monadic function expecting 'EdgeList' as argument.

        adj ← AdjacencyMatrix ⍵
        v ← ⊃⍴ adj
        (1 1⍉adj) ← v⍴1     ⍝ Assign 1s to the main diagonal to accumulate all paths.
        accum ← (+.×)⍣(v-1)⍨ adj
        ≢∪ (1@(≠∘0)) accum
    }

:EndNamespace


texts: Python automatic import and install script

texts:
In the following script, I am trying to infer if the modules are managed by a conda environment or not and based on that, I am trying to auto install and import the modules. [I skipped around 5 to 6 imports to keep it short for the sake of this example].

It would be great if someone can give me some pointers if I have made any mistakes in my following code.

import importlib
import os
import subprocess
import sys

def package_install(package, is_conda):
    """ Installs missing modules. """
    install_env = "conda" if is_conda else "pip"
    conda_call = [install_env, "install", "-y", package]
    pip_call = [sys.executable, "-m", install_env, "install", package]
    install_call = conda_call if is_conda else pip_call

    try:
        subprocess.call(install_call)
    except Exception as err:
        print(f'Unable to install the module using {install_env}:\n{repr(err)}')

# Check if the packages are managed with conda environment
is_conda = os.path.exists(os.path.join(sys.prefix, 'conda-meta'))

try:
    import matplotlib as plt
except ImportError:
    package_install("matplotlib", is_conda)
    plt = importlib.import_module("matplotlib")
try:
    import descartes as des
except ImportError:
    package_install("descartes", is_conda)
    des = importlib.import_module("descartes")


texts: Convert IP address to its binary representation

texts:
For a recent lab at the university we had to match the longest prefix for an IP (v4) address by using a Trie data structure. The code works fine, but it takes about 2 minutes to load a 14 million-line routing table. I examined what was causing the slowness, and it was the (String) IP to (String) binary format conversion.

For example, the IP address 127.0.0.1 should be converted to 01111111000000000000000000000001. I my original method (slow) uses String.format, which I find much more readable and easy to follow. I then wrote a different method using a temporary char[], filled with '0' to use as padding.

The speedup of the fast method is about 6x. Below is a stripped down version for demonstration and measurement:

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        final String ip = "127.0.0.1";
        String binaryIp;
        final long start = System.currentTimeMillis();

        for (int i = 0; i < 10000000; i ++) {
            binaryIp = fast(ip);
        }

        long fast = System.currentTimeMillis();

        for (int i = 0; i < 10000000; i ++) {
            binaryIp = slow(ip);
        }

        long slow = System.currentTimeMillis();

        System.out.println("Fast time: " + (fast - start) + " ms");
        System.out.println("Slow time: " + (slow - fast) + " ms");
    }

    public static String fast(String ip) {

        StringBuilder bStringBuilder = new StringBuilder();
        String ipParts[] = ip.split("\\.");

        for (String ipPart : ipParts) {

            String binString = Integer.toBinaryString(Integer.parseInt(ipPart));
            int length = 8 - binString.length();
            char[] padArray = new char[length];
            Arrays.fill(padArray, '0');
            bStringBuilder.append(padArray).append(binString);
        }
        System.out.println(bStringBuilder.toString());
        return bStringBuilder.toString();
    }

    public static String slow(String ip) {

        StringBuilder bStringBuilder = new StringBuilder();
        String ipParts[] = ip.split("\\.");

        for (String ipPart : ipParts) {

            String binString = Integer.toBinaryString(Integer.parseInt(ipPart));
            String binaryPart = String.format("%8s", binString).replace(' ', '0');
            bStringBuilder.append(binaryPart);
        }
        return bStringBuilder.toString();
    }
}

For which the output is:

Fast time: 3936 ms
Slow time: 23527 ms

I can't think of a more efficient way to pad a binary string appropriately... I don't think that there's any need to improve the slow method as it's now obsolete compared to fast. However, is there any way that I can improve fast?

PS - magic number 8 would be a magic number that never changes, so I don't think I need a static final int ipv4SectionLength = 8 or anything like that!


texts:
I was writing a program in C++11 to find top k words from a file. I think priority queues will give the optimal solution so I implemented using that. The code works and compiles. Could anyone please review this and suggest some more C++11/14-ish things to do?

I also have some specific questions:

Is there way in C++11 or C++14 to avoid using an iterator to find whether an element exists or not in a map?

I am talking about the condition:

if(it != word_map.end()) {
  word_map[word] = ++word_map[word];
}

How can I avoid using an iterator? Is there a "defaultdict" in C++ like we have in Python? I suppose here I can just remove it since default initialization will be 0, but what is the general way?
I saw a weird behavior for this:

while(input_file>>word) {
  //....
}

This loop gives the correct count. But if I do:

while(input_file.good()) {
   //..
}

this gives the count with an additional 1 added if the word is present on two different lines.

For example:

this is a test.
this.

while giving a count of this as 3.
I think I need to write a custom comparator for the priority queue to compare only the second part of the "pair". In that case, on what basis is the priority queue operating as of now?

/** top k words in a file
  */
#include <iostream>
#include <fstream>
#include <map>
#include <queue>
using namespace std;

void getTopKWords(const map<string, int>& word_map, const unsigned int k) {
  priority_queue<pair<string, int> > pq;
  for(auto item : word_map) {
    pq.push(make_pair(item.first, item.second));
  }

  for(unsigned int i=0;i<k;i++) {
    auto item = pq.top();
    pq.pop();
    cout << item.first << " " <<item.second << endl;
  }
}

void getWordFrequency(const string& filename, const unsigned int& k) {
  ifstream input_file;
  input_file.open(filename);
  if(!input_file.is_open()) {
    std::cout<< "Error opening file " << std::endl;
    return;
  }

  map<std::string, int> word_map;
  std::string word = "";
  while(input_file >> word) {
    auto it = word_map.find(word);
    if(it != word_map.end()) {
      word_map[word] = ++word_map[word];
    }
    else {
      word_map[word] = 1;
    }
  }
  input_file.close();
  getTopKWords(word_map, k);
}

int main() {
  getWordFrequency("test_file.txt", 5);
}


texts:
I have the following multi thread scenario and the codes. It looks kind of messy and want to know if I can make it better or if there is any flaw to fix.
When a request arrives, one thread downloads it and the remaining operations are dependent on download so it needs to wait for download to finish. But there can be many request coming and download tasks must run at the same time but each process operation need to wait for its own download task. So I did the following.
ProcessCompletedListener
public interface ProcessCompletedListener {
    void onComplete(Object object);
}

RequestListener
public interface RequestListener {
    void onRequest(Object request);
}

Receiver class where I send request for testing purpose.
public class Receiver {
private RequestListener requestListener;

public void setRequestListener(RequestListener requestListener) {
    this.requestListener = requestListener;
}

public void requestBomb() {
    String[] names = new String[]{"a", "b", "c"};

    int i = 0;
    while (i < 3) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        requestListener.onRequest(names[i]);
        i++;
    }
}
}

Custom blocking queue
public class CustomBlockingQueue {
private BlockingQueue<Object> blockingQueue = new LinkedBlockingDeque<>();
private ProcessCompletedListener processCompletedListener;

public boolean offerAndProcess(Object object) {
    if (blockingQueue.offer(object)) {
        process(object);
        return true;
    }
    return false;
}

public void setProcessCompletedListener(ProcessCompletedListener processCompletedListener) {
    this.processCompletedListener = processCompletedListener;
}

private void process(Object object) {
    new Thread(() -> {
        System.err.println(object + ": Request process started.");

        try {
            Thread.sleep(6000); // mock for real operation
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.err.println(object + ": Request process completed.");

        if (processCompletedListener != null) {
            processCompletedListener.onComplete(object);
        }
    }).start();
}
}

Demo class
public class Demo {
public CustomBlockingQueue customBlockingQueue;

public void setCustomBlockingQueue(CustomBlockingQueue customBlockingQueue) {
    this.customBlockingQueue = customBlockingQueue;
}

public CustomBlockingQueue getCustomBlockingQueue() {
    return customBlockingQueue;
}

public static void main(String[] args) {
    Demo demo = new Demo();
    demo.setCustomBlockingQueue(new CustomBlockingQueue());

    Receiver receiver = new Receiver();
    Thread t = new Thread(() -> {
        receiver.setRequestListener((request) -> {
            new Thread(() ->
                    demo.getCustomBlockingQueue().setProcessCompletedListener((Object object) -> {
                        System.err.println(object + ": post process started");
                        try {
                            Thread.sleep(1500); // mock for real operation
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.err.println(object + ": post process completed");
                    })).start();
            demo.getCustomBlockingQueue().offerAndProcess(request);
        });
    });
    t.start();
    receiver.requestBomb();
}
}


texts:
In this code:

tmr represents timer array
n represents number of frames in memory
m represents number of pages
rs represents the reference string

There are many functions in this program, but the important one is the timer_confg. This is the function that tests the particular page refereed is least refereed or just refereed. It is used to calculate the timing of the pages. I have designed the function for 3 frames, but if the frames are increased then the cases in the switch statement can be increased. Here 0 means just refereed page and max means maximum from the timer array tmr[] is the least refereed page.

There are other functions for read and display. The max function is used for finding the maximum from the timer which will be used to determine the least refereed page.

This code implements the algorithm using the timer which is maintained by the array tmr[]. The pg[] array denotes the frames in the memory and rs[] denotes the reference string. The rest of the code is about the conditions that will be encountered like:

when frames are empty
when the page is already in the memory
which page needs to be replaced

#include<iostream>
using namespace std;

int max(int r[],int n)
{
    int pos,i,l,max=0;
    for(i=0;i<n;i++)
    {
        if(r[i]>max)
        {
            l=r[i];
            max=r[i];
            pos=i;
        }
    }
    return pos;
}

void read(int a[],int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
}

void display(int b[],int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        cout<<b[i]<<" ";
    }
}

void timer_confg(int tmr[],int pos)
{
    int j=pos;
    switch(pos)
    {
        case 0:
            tmr[j]=0;
            tmr[j+1]=tmr[j+1]++;
            tmr[j+2]=tmr[j+2]++;
            break;
        case 1:
            tmr[j]=0;
            tmr[j-1]=tmr[j-1]++;
            tmr[j+1]=tmr[j+1]++;
            break;
        case 2:
            tmr[j]=0;
            tmr[j-1]=tmr[j-1]++;
            tmr[j-2]=tmr[j-2]++;
            break;
    }
}
int main()
{
    int pg[20],tmr[20],i,j,n,pf=0,rs[20],m,avail=0;
    cout<<"Enter number of frames: ";
    cin>>n;
    for(i=0;i<20;i++)
    {
        pg[i]=-1;
    }
    cout<<"Enter the number of pages:";
    cin>>m;
    cout<<"Enter the reference string: ";
    read(rs,m);
    int pos;
    tmr[0]=2;
    tmr[1]=1;
    tmr[2]=0;
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            if(pg[j]==-1)
            {
                pg[j]=rs[i];
                avail=1;
                pf++;
                cout<<"This page "<<rs[i]<<" is PLACED in the frame "<<j<<endl;
                break;
            }
            else
            {
                if(pg[j]==rs[i])
                {
                    pos=j;
                    timer_confg(tmr,pos);
                    avail=1;
                    cout<<"This page "<<rs[i]<<" is already in the frame "<<j<<endl;
                    break;
                }

                else
                {
                    if(avail==0 || j==(n-1))
                    {
                        pos=max(tmr,n);
                        pg[pos]=rs[i];
                        pf++;
                        timer_confg(tmr,pos);
                        cout<<"The page "<<rs[i]<<" is replaced with frame "<<pos<<endl;
                        break;
                    }
                }
            }
        }
    }
    cout<<"The total number of page fault is:"<<pf;
    return 0;
}


texts:
I have been tasked with creating financial reports. I am looking for any suggestions on improving performance, readability/formatting  or best practices.

/*setting dummy parameters */
SET DATEFORMAT dmy
DECLARE @startProduct NVARCHAR = ''
DECLARE @endProduct NVARCHAR = 'zzzzzzzzzzzzzzzzzzzzzz'
DECLARE @startGroup NVARCHAR = ''
DECLARE @endGroup NVARCHAR = 'zzzzzzzzzzzzzzzzzz'
DECLARE @startDepartment NVARCHAR = ''
DECLARE @endDepartment NVARCHAR = 'zzzzzzzzzzzzzzzzzzzzzzz'
DECLARE @startDate DATE = '01/05/2000'
DECLARE @endDate DATE = CAST('31/05/2012' AS DATE)
DECLARE @StartTime TIME  = '08:00:00'
DECLARE @endTime TIME = '17:00:00'
DECLARE @grouping INT = 0
DECLARE @site  INT = 21
/*
ProductCode = 0
ProductGroup = 1
Department = 2
Pump = 3
Date = 4
*/

SELECT
     CASE @grouping
        WHEN 0 THEN P.Code
        WHEN 1 THEN P.[Group]
        WHEN 2 THEN P.Department
        WHEN 3 THEN P.[Description]
        WHEN 4 THEN CONVERT(VARCHAR,RPS.SalesDateTime,103)
    END AS GroupCode,
    CASE @grouping
        WHEN 0 THEN P.[Description]
        WHEN 1 THEN PG.[Description]
        WHEN 2 THEN PD.[Description]
        WHEN 3 THEN 'PUMP: ' + CONVERT(VARCHAR,RPS.PumpId) +' HOSE: ' + CONVERT(VARCHAR,RPS.HoseId)
        WHEN 4 THEN CONVERT(VARCHAR(MAX),CAST(FLOOR(CAST(RPS.SalesDateTime AS FLOAT)) AS DATETIME))
    END AS [GroupDescription],
    SUM(RPS.Quantity) AS Quantity,
    SUM( CASE
            WHEN P.GSTable = 1 THEN  RPS.TotalAmount / 1.1
            ELSE RPS.TotalAmount
         END) AS AmountX,
    SUM(CASE
            WHEN P.GSTable = 1 THEN (rps.TotalAmount * .10)
            ELSE 0 END
        ) AS GST,
    SUM(RPS.UnitLastCost * RPS.Quantity) AS CostXgst,
    SUM(RPS.TotalAmount) AS AmountInc,
    FLOOR(ROUND(((1 -
        (
        SUM(RPS.UnitLastCost * RPS.Quantity)
            /
            NULLIF(SUM
            (
                CASE
                    WHEN P.GSTable = 1 THEN  RPS.TotalAmount / 1.1
                    ELSE RPS.TotalAmount
                END
            ),0))) * 100 ),0))

          AS Margin
FROM
    RetailPosSales RPS
        JOIN Products P ON RPS.ProductCode = P.Code
        LEFT OUTER JOIN ProductGroups PG ON P.[Group] = PG.Code /*need this if the grouping is 1*/
        LEFT OUTER JOIN ProductDepartments PD ON P.Department = PD.Code  /*need this if the grouping is 2 */
WHERE
    ((@grouping <> 3) OR (@grouping = 3 AND RPS.IsFuelSale = 1)) /*When grouping by pump, only allow fuel products */
    AND P.Code BETWEEN @startProduct AND @endProduct
    AND P.[Group] BETWEEN @startGroup AND @endGroup
    AND P.Department BETWEEN @startDepartment AND @endDepartment
    AND CAST(RPS.SalesDateTime AS DATE) BETWEEN @startDate AND @endDate
    AND CAST(RPS.SalesDateTime AS TIME) BETWEEN @StartTime AND @endTime
    AND RPS.SiteId = @site
GROUP BY
    CASE @grouping
        WHEN 0 THEN P.Code
        WHEN 1 THEN P.[Group]
        WHEN 2 THEN P.Department
        WHEN 3 THEN P.[Description]
        WHEN 4 THEN CONVERT(VARCHAR,RPS.SalesDateTime,103)
    END,
    CASE @grouping
        WHEN 0 THEN P.[Description]
        WHEN 1 THEN PG.[Description]
        WHEN 2 THEN PD.[Description]
        WHEN 3 THEN 'PUMP: ' + CONVERT(VARCHAR,RPS.PumpId) +' HOSE: ' + CONVERT(VARCHAR,RPS.HoseId)
        WHEN 4 THEN CONVERT(VARCHAR(MAX),CAST(FLOOR(CAST(RPS.SalesDateTime AS FLOAT)) AS DATETIME))
    END
ORDER BY
    GroupCode,
    GroupDescription


texts:
Is it possible to automate the array inside the while loop and automatically assign the key name based on the row so I don't have to spell out each one?

$stmt = $conn->prepare("SELECT * FROM tickets_info WHERE ticket = ?");
$stmt->execute(array($_POST['ticket']));

if ($stmt->rowCount()) {

    while ($row = $stmt->fetch()) {

        $ticket = [
            'name'      => $row['name'],
            'company'   => $row['company'],
            'email'     => $row['email'],
            'phone'     => $row['phone'],
            'address'   => $row['address'],
        ];

    }

}


texts:
I made a palindrome checker that's supposed to be designed to be simple and easy to read. Please let me know what you think. I believe the time complexity is \$\mathcal{O}(n)\$ but I'm not too sure about that:

Challenge: You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes.

function reverseString(str)
{
  str = str.replace(/[^\w\s]|_/g, "").toLowerCase().split(" ").join("");
  var array = [];
  for(var i = str.length ; i >=0; i--)
  {
    array.push(str[i])
  }
  return(array.join(""));
}

reverseString("My age is 0, 0 si ega ym.");

function palindrome(str) {
  str = str.replace(/[^\w\s]|_/g, "").toLowerCase().split(" ").join("");
  if(str === reverseString(str))
  {
   return true;
  }
  else
  {
    return false;
  }
}


texts: Cleanup code to add div structure to element

texts:
I was cleaning up my code when I came across this situation :

var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var count = 1;
var html = '';
for (var i = 0; i < a.length; i++) {
    var rowStart = '
';
    var cell = '
';
    cell += '
' + a[i] + '
';
    cell += '
';
    var rowEnd = '
';

    if (count == 1) {
        html += rowStart + cell;
        count++;
    } else if (count == 3) {
        html += cell + rowEnd;
        count = 1;
    } else {
        html += cell;
        count++
    }
}
$('#container').append(html);

jsFiddle

I retrieve data from a database which I want to display in a div structure as shown above. This code however looks ugly and I think it can be way shorter, I just don't know how.

I was hoping someone could give me some advice/methods/anything on how to clean up this code.


texts: Creating Original Database Algorithm--Login System

texts:
For fun, I have been making a very basic login system in Python. I was going to look up an algorithm or something for user info storage and transfer, but then decided it would be more fun to come up with and implement it myself. What I would like to know is:

Is there anyway to make it secure (i.e.-encrypting the password without revealing the algorithm in the file)?
Can the algorithm I used be made any more efficient?
Is it cleanly written? I tried to take into account the comments on my last question regarding simplifying code and any comments about its readability would be appreciated--by secondary goal is beautiful code.

#This program will do a couple of things.
#The first time it is run, it will request that you add a password. Once you do, it will change the check_e$
#Every subsequent time, it will check the password in the other file and then match user input.
#If user input is correct it will display a joke.
#If user input is incorrect it will exit the program.

#Function to help the user pick a password
def pick_password():
        file = '/home/vhx/Documents/code/pydata_test/password_dbs/pswd.txt'
        print 'Please pick a password.'
        password = raw_input()
        target = open(file, 'w')
        target.write(password)
        file = '/home/vhx/Documents/code/pydata_test/password_dbs/existence_check.txt'
        target = open(file, 'w')
        target.write('YES')
#       file.close()

#Function to check the password with the password located in pswd.txt
def password_check():
        file = '/home/vhx/Documents/code/pydata_test/password_dbs/pswd.txt'
        pwd_check = open(file).read()
        userpass = raw_input('Please input a password.\n')
        if userpass == pwd_check:
                print 'Password accepted!'
                print 'Ready for the joke?'
                raw_input()
                print 'Why did the fly fly? Because the spider spied her!'
        elif userpass != pwd_check:
                print 'Sorry, wrong password.\n'
                exit()
        else:
                print 'Invalid syntax.'
                exit()

#location of password existence check file
EC = '/home/vhx/Documents/code/pydata_test/password_dbs/existence_check.txt'
PWD = '/home/vhx/Documents/code/pydata_test/password_dbs/pswd.txt' #Location of password file

pswd_exist = open(EC).read() #Checking to see if the password exists
if pswd_exist == 'YES':
        pass
else:
        pick_password() #If it doesn't, user will pick a password

#Checking for password
password_check()

Note: If you want to run it, it requires two files --pswd.txt and existence_check.txt--which you then must link (and replace all necessary file locations).

If you input the correct password, the program tells a joke, though whether its funny is debatable.


texts: Checking for neighbours more elegantly in Conway's Game of Life

texts:
My method for counting neighbors in my soon-to-be Game of Life implementation is very repetitive and I was wondering if this could be done more elegantly:

static int countNeighbours(Board b, int x, int y) {
    int count = 0;
    if (b.getTile(x - 1, y - 1)) {
        ++count;
    }
    if (b.getTile(x, y - 1)) {
        ++count;
    }
    if (b.getTile(x + 1, y - 1)) {
        ++count;
    }
    if (b.getTile(x + 1, y)) {
        ++count;
    }
    if (b.getTile(x + 1, y + 1)) {
        ++count;
    }
    if (b.getTile(x, y + 1)) {
        ++count;
    }
    if (b.getTile(x - 1, y + 1)) {
        ++count;
    }
    if (b.getTile(x - 1, y)) {
        ++count;
    }
    return count;
}

Because officially the board should be infinite, I don't need out-of-bounds checks in this code - I assume the board is infinite here -, but my Board implementation secretly looks like this:

// TODO: make the board 'infinite'
public boolean getTile(int x, int y) {
    if (x < 0 || y < 0 || x > getWidth() - 1 || y > getHeight() -1) return false;
    return tiles[y][x];
}

public void setTile(int x, int y, boolean val) {
    if (x < 0 || y < 0 || x > getWidth() - 1 || y > getHeight() -1) return;
    tiles[y][x] = val;
}

(Just to save you the time it costs to type 'your code will cause an IndexOutOfBoundsException for the tile on (0,0)'. This question is on the implementation of static int countNeighbours(Board, int, int).)

I'm stuck with Java 6 by the way.


texts: Dependency Injection With Unity in MVC 5 without repository and unit of work

texts:
I want to use dependency injection with Unity in my application. I am not following repository pattern and unit-of-work (and don't want to). I also have ViewModel in my controller action method. Please review my code and add your comments.

public class ProductCatagoryController : Controller
{
    private dataBaseContext _context;

    public ProductCatagoryController(IdataBaseContext context)
    {
        this._context = context as dataBaseContext;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult addNewCategory([Bind(Include = "catName,desc")]RegisterNewCatagoryViewModel RegisterNewCatagoryViewModel)
    {
        if (ModelState.IsValid)
        {
            try
            {
                Mapper.CreateMap<RegisterNewCatagoryViewModel, Category>();
                Category category = Mapper.Map<Category>(RegisterNewCatagoryViewModel);
                category.catID = Guid.NewGuid().ToString();
                category.date_from = DateTime.Now;
                category.active = true;
                _context.Categories.Add(category);
                _context.SaveChanges();
            }
            catch (Exception e)
            {
                loggerElmah.logElmah(e, "Adding New Category Failed");
            }
        }
        return View();
    }

    [HttpGet]
    public ActionResult addNewCategory()
    {
        return View();
    }

    // GET: ProductCatagory
    public ActionResult Index()
    {
        return View();
    }
}

In addNewCategory I am passing an object of a concrete class object, but I want to pass an interface of the viewmodel and bind it with actual implementation in the run-time through unity. How can I do this?

Also, can someone guide me on writing unit-tests for the above code?


texts: Registering or logging in when creating a new comment object

texts:
This service object allows users without a session to create a comment, and register OR login at the same time.

If a user is signed out he must enter an email and a password along with the comment.

The service checks if a user exists using the email, then attempts to authenticate the user. Otherwise, it creates a new user.

Three code smells:

User errors are added to the comment. There is no user object in the view, just a params hash with that name.
If user validation fails, comment validation does not trigger, meaning if the comment was also blank they need another round trip to find out. Probably not significant though.
User data is not repopulated on validation failure.

Question: I'm proud of writing a nifty object like that, but it stills feels a little 'wrong-ish' if there is such a word. Is there a better way to handle this type of scenario?

class CommentService
  def self.by(params, user)
    if user
      new params, user
    else
      new params, find_or_new(params)
    end
  end

  def self.find_or_new(params)
    User.find_by(email: params[:user][:email]) || User.new
  end

  attr_reader :params, :comment, :user

  def initialize(params, user)
    @params, @user = params, user
    @comment = Comment.new(comment_params)
  end

  def save
    if user.new_record?
      self.user.attributes = user_params
      user.save ? persist : add_user_errors
    else
      if params[:user].present?
        user.authenticate(params[:user][:password]) ? persist : add_auth_error
      else
        persist
      end
    end
  end

  def post
    @post ||= Post.find(params[:post_id])
  end

  private

  def add_user_errors
    user.errors.each do |k,v|
      comment.errors.add(k, v)
    end
    false
  end

  def add_auth_error
    comment.errors[:base] << "Invalid email or password."
    false
  end

  def user_params
    params.require(:user).permit(:name, :email, :password)
  end

  def comment_params
    params.require(:comment).permit(:text)
  end

  def persist
    comment.author = user
    comment.post = post
    comment.save
  end
end

Controller code:

  def create
    service  = CommentService.by(params, current_user)
    @post = service.post
    if service.save
      redirect_to @post
    else
      @comment = service.comment
      render 'new'
    end
  end

View code:

= form_for [@post, @comment] do |f|
  = f.text_area :comment
  / No user object here. Just tossing a user hash into the params.
  - unless signed_in?
    = fields_for :user do |uf|
      = uf.text_field :email
      = uf.password_field :password

  = f.submit


texts:
I've been working at speeding up my web scraping with the asyncio library. I have a working solution, but am unsure as to how pythonic it is or if I am properly using the library. Any input would be appreciated.

import aiohttp
import asyncio
import requests
from lxml import etree

@asyncio.coroutine
def get(*args, **kwargs):
    """
    A wrapper method for aiohttp's get method. Taken from Georges Dubus' article at
    http://compiletoi.net/fast-scraping-in-python-with-asyncio.html
    """
    response = yield from aiohttp.request('GET', *args, **kwargs)
    return (yield from response.read_and_close())

@asyncio.coroutine
def extract_text(url):
    """
    Given the url for a chapter, extract the relevant text from it
    :param url: the url for the chapter to scrape
    :return: a string containing the chapter's text
    """
    sem = asyncio.Semaphore(5)
    with (yield from sem):
        page = yield from get(url)

    tree = etree.HTML(page)
    paragraphs = tree.findall('.//*/div[@class="entry-content"]/p')[1: -1]
    return b'\n'.join(etree.tostring(paragraph) for paragraph in paragraphs)

def generate_links():
    """
    Generate the links to each of the chapters
    :return: A list of strings containing every url to visit
    """
    start_url = 'https://twigserial.wordpress.com/'
    base_url = 'https://twigserial.wordpress.com/category/story/'
    tree = etree.HTML(requests.get(start_url).text)
    xpath = './/*/option[@class="level-2"]/text()'
    return [base_url + suffix.strip() for suffix in tree.xpath(xpath)]

@asyncio.coroutine
def run():
    links = generate_links()
    chapters = []

    for f in asyncio.as_completed([extract_text(link) for link in links]):
        result = yield from f
        chapters.append(result)

    return chapters

def main():
    loop = asyncio.get_event_loop()
    chapters = loop.run_until_complete(run())
    print(len(chapters))

if __name__ == '__main__':
    main()


texts:
I have code for googly eyes that is too long. Basically I have variables for each element pupils (one for right -other for left), eyesockets (left, right). I wish I could compress my code so I can call a function animateEye (eye).

  function animateEye(eye) {
          console.log(eye);
          var pupille = eye.find("div");

For now this is what I have and I have no idea how to continue.

This is the actual code:

var pupilleLinks = $('#pupilleLinks');
var pupilleRechts = $('#pupilleRechts');

//   var abstandH =  pupille.offset().left- e.pageX + pupille.height()/2;

$(document).on('mousemove', function(e){
    var abstandV1 = pupilleLinks.offset().top- e.pageY +pupilleLinks.height()/2;

    var pupilleL1 = pupilleLinks.position().top - abstandV1 ; // 10 = Breite Pupille / 2
    var augeLinks = $("#augeLinks")
    var distanceX=augeLinks.width()-pupilleLinks.width();
    var distanceY=augeLinks.height()-pupilleLinks.height();
    if(pupilleL1 > distanceY) {
      (pupilleL1 = distanceY);
               }
    if(pupilleL1 < 0) {
      (pupilleL1 = 0);
               }
    var abstandH1 = pupilleLinks.offset().left- e.pageX + pupilleLinks.width()/2;
    var pupilleL2 = pupilleLinks.position().left - abstandH1 ;
    if (pupilleL2 < 0) {
       (pupilleL2 = 0);
               }
    if(pupilleL2 > distanceX) {
      (pupilleL2 =distanceX);
               }
    pupilleLinks.css({
        left: pupilleL2+"px",
        top: pupilleL1+"px"
               });

    var abstandH2 = pupilleRechts.offset().left- e.pageX + pupilleRechts.width()/2;
    var pupilleR1 = pupilleRechts.position().left - abstandH2;
    var augeRechts = $("#augeRechts")
    var distanceX2=augeRechts.width()-pupilleRechts.width();
    var distanceY2=augeRechts.height()-pupilleRechts.height();
    if(pupilleR1 < 0) {
      (pupilleR1 = 0);
               }
    if(pupilleR1 > distanceX2) {
      (pupilleR1 = distanceX2);
               }
    var abstandV2 = pupilleRechts.offset().top- e.pageY + pupilleRechts.width()/2;
    var pupilleR2 = pupilleRechts.position().top - abstandV2;
    if(pupilleR2 < 0) {
      (pupilleR2 = 0);
               }
    if(pupilleR2 > distanceY2) {
      (pupilleR2 =distanceY2);
               }
    pupilleRechts.css({
            left: pupilleR1+"px",
            top: pupilleR2+"px"
               });

    });
.auge {
  position: relative;
  display: inline-block;
  width: 150px;
  height: 150px;
  border: 10px solid black;
}
.pupille {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 30px;
  height: 30px;
  background-color: blue;
  border-radius: 15px;
}


texts:
the One of Unix core commands is yes which simply prints infinity number of letter y.

I read a blog post (https://matthias-endler.de/2017/yes/) about how people optimize it to output y with a speed of 10 GB/s. I get 7.5 GB/s on my machine using this command.

I tried to achieve similar results with Java but it stopped at 70 MB/s.

My code is:

public class yes {

    static byte[] bb = new byte[]{'y','\n'};

    public static void main(String[] args) throws IOException {

        BufferedOutputStream writer = new BufferedOutputStream(System.out);
        for (;;) {
            writer.write(bb);
        }

    }
}

Do you have any idea how to optimize it to get results similar to UNIX version?


texts:
I have written a very basic paint program in java using AWT and Swing. I have separated the program into two different class files; one of them holds the JFrame and adds a custom panel (this custom panel being the second class file, extending JPanel).

In my first try, I tried using Timer and an ActionListener with repaint() but that seemed very very laggy (I could not draw straight lines/curves, they would always be laggy when I dragged my mouse fast.)

Then I switched to using a different approach (stored previous x and y locations and drew a line between the current position and the previous location). Here are the two class files:

The custom JPanel class:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Panel extends JPanel
{
  // PROPERTIES
  private final int DEFAULT_WIDTH  = 800;
  private final int DEFAULT_HEIGHT = 800;
  private final Color BACK_COLOR   = Color.WHITE;

  private int x1, y1, x2, y2;

  private MyMouseHandler handler;
  private Graphics g;

  // CONSTRUCTOR
  public Panel()
  {
    setBackground( BACK_COLOR );
    setPreferredSize( new Dimension( DEFAULT_WIDTH, DEFAULT_HEIGHT ) );

    handler  = new MyMouseHandler();

    this.addMouseListener( handler );
    this.addMouseMotionListener( handler );
  }

  // METHOD
  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
  }

  private void setUpDrawingGraphics()
  {
    g = getGraphics();
  }

  // INNER CLASS
  private class MyMouseHandler extends MouseAdapter
  {
    public void mousePressed( MouseEvent e )
    {
      x1 = e.getX();
      y1 = e.getY();

      System.out.println("Mouse is being pressed at X: " + x1 + " Y: " + y1);

      setUpDrawingGraphics();

      x2=x1;
      y2=y1;
    }

    public void mouseDragged( MouseEvent e )
    {
      x1 = e.getX();
      y1 = e.getY();

      System.out.println("Mouse is being dragged at X: " + x1 + " Y: " + y1);

      g.drawLine(x1,y1,x2,y2);

      x2=x1;
      y2=y1;
    }
  }
}

and the JFrame class with the main method:

import java.awt.*;
import javax.swing.*;

public class RunPanel
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame( "Run Panel" );
    frame.setDefaultCloseOperation(3);

    Panel  panel = new Panel();
    frame.add( panel );

    frame.pack();
    frame.setVisible( true );
  }
}

The program works fine, I can draw normal curves at low mouse speed. But again, as I increase the mouse speed the lines/curves start the get jaggy and ugly.

Maybe this is because I am drawing lines in between the positions, but drawing individual pixels look MUCH worse.

NOTE: I have gathered the two classes into one class file and the program stopped the lag. What is causing this? You can see the code here.


texts:
This is the first piece of code I wrote on my own.  I tried to use everything I know, like functions, loops and variables.  Is it good or could it be simpler?

Please be hard as you can be with me because I feel my programming knowledge is quite poor and I end up using Google for solving my problems.

    // RPS.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int nPlayerScore=0;
int nComputerScore=0;
int nPlayerMove=0;
int nComputerMove=0;

void DisplayScore()
{
    cout << "Player: " << nPlayerScore << endl;
    cout << "Computer: " << nComputerScore << endl << endl;
}

int GetMove()
{
    cout << "Please choose a move: \n1.Rock\n2.Paper\n3.Scissors\n";
    int x;
    cin >> x;
    cout << endl;
    return x;
}

void CalculateResults()
{
    if (nPlayerMove==1) //player is Rock
    {
        if (nComputerMove==1) {cout << "player Rock vs computer Rock: IT'S A TIE!";}
        if (nComputerMove==2) {cout << "player Rock vs computer Paper: COMPUTER WON!"; nComputerScore=nComputerScore+1;}
        if (nComputerMove==3) {cout << "player Rock vs computer Scissors: PLAYER WON!"; nPlayerScore=nPlayerScore+1;}
    }
    if (nPlayerMove==2) //player is Paper
    {
        if (nComputerMove==1) {cout << "player Paper vs computer Rock: PLAYER WON!"; nPlayerScore=nPlayerScore+1;}
        if (nComputerMove==2) {cout << "player Paper vs computer Paper: IT'S A TIE!";}
        if (nComputerMove==3) {cout << "player Paper vs computer Scissors: COMPUTER WON!"; nComputerScore=nComputerScore+1;}
    }
    if (nPlayerMove==3) //player is Scissors
    {
        if (nComputerMove==1) {cout << "player Scissors vs computer Rock: COMPUTER WON!"; nComputerScore=nComputerScore+1;}
        if (nComputerMove==2) {cout << "player Scissors vs computer Paper: PLAYER WON!"; nPlayerScore=nPlayerScore+1;}
        if (nComputerMove==3) {cout << "player Scissors vs computer Scissors: IT'S A TIE!";}
    }

cout << endl << endl;
}

int main()
{
    do
    {
    cout << "Welcome to RPS 1.0a \tby GeTAFIX \n\n";
    DisplayScore();
    nPlayerMove=GetMove();
    srand((unsigned)time(0));
    nComputerMove=rand()%(3)+1;
    CalculateResults();
    //cout << "Press any key to continue...";
    system("pause");
    system("cls");
    } while (1==1);
}


texts:
A new question about a revised version of the code in this question, based on the advice in the accepted answer can be found here.

I need to signal my program to do something every X seconds. So I decided to make a separate thread that sends such a signal using ZeroMQ. All other behaviour is also triggered by ZeroMQ messages, so this seems like a safe way to do it, with respect to multithreading.

I have never used threads in C++ before though, so I'd like some feedback on my code. Note that in the code below I have replaced the actual task with a simple cout statement.

EDIT: I just realized the thread could very well terminate between setting run = false and calling join, which causes a std::system_error to be thrown. Putting the join statement in an if-block with isjoinable still suffers from the same problem. How should I handle this? try-catch? Using a locking mechanism instead of an atomic bool?

Ticker.hpp

#include <thread>
#include <chrono>
#include <atomic>

class Ticker {
private:
    const unsigned int interval;
    std::atomic_bool run;
    std::thread tickthread;
public:
    Ticker(unsigned int interval);
    Ticker(const Ticker& orig) = delete;
    virtual ~Ticker();
    void stop();
private:
    void tickfunction();
};

Ticker.cpp

#include "Ticker.hpp"
#include <iostream>

using namespace std;

Ticker::Ticker(unsigned int interval)
: interval(interval), run(true), tickthread(&Ticker::tickfunction, this) {
}

Ticker::~Ticker() {
    if (tickthread.joinable()) {
        stop();
    }
}

void Ticker::stop() {
    cout << "stopping..." << endl;
    run = false;
    // interrupt sleep?
    tickthread.join();
    cout << "joined" << endl;
}

void Ticker::tickfunction() {
    while (true) {
        this_thread::sleep_for(chrono::seconds(interval));
        if (run) {
            cout << "tick" << endl;
        } else {
            break;
        }
    }
}

There are also two specific things I'd like recommendations on:

How can I change this class to accept any std::chrono::duration object as input for the interval, instead of just an integer? I tried this, but couldn't figure out how to do it with the templates.
Is there a way to interrupt the sleep_for when I call stop()? Especially when interval is large, it'd be nice to not have to wait for the sleeping thread when stopping it.


texts: Handling potentially missing props of an object

texts:
I'm building a wrapper for the Stackoverflow Careers RSS feeds for a NodeJS application and I've hit an interesting point.

The following code works fine and produces a valid result but I feel like I can handle it better.

Here's my Utils.js file:

let utils = {
    UrlPrefix: 'https://stackoverflow.com/jobs/feed?q=',
    Location: "&l=",
    Unit: "&u=",
    TechLiked: "&tl=",
    TechDisliked: "&td="
}

module.exports = utils;

And the function that I'm getting cold sweats from:

function UrlBuilder(props) {

    let builtUrl = utils.UrlPrefix;

    if(props.query) {
        builtUrl += props.query
    }

    if(props.location) {
        builtUrl += utils.Location + props.location
    }

    if(props.td) {
        builtUrl += utils.TechDisliked + props.td
    }

    if(props.tl) {
        builtUrl += utils.TechLiked + props.tl
    }

    if(props.unit) {
        builtUrl += utils.Unit + props.unit
    }

    return builtUrl;
}

Is there no way around this or can I handle this better? All of the properties are optional so any one of them could be absent.


texts: Add and enable/disable Windows Firewall rules with Python

texts:
I have this following module using for adding and enabling/disabling Windows Firewall rules using Python.

I currently use subprocess.call to execute the netsh command inside Python. I'm wondering if there is any better method to do this? Executing the cmd command inside Python seems to be impractical to me.

import subprocess, ctypes, os, sys
from subprocess import Popen, DEVNULL

def chkAdmin():
    """ Force to start application with admin rights """
    try:
        isAdmin = ctypes.windll.shell32.IsUserAnAdmin()
    except AttributeError:
        isAdmin = False
    if not isAdmin:
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)

def addRule(rule_name, file_path):
    """ Add rule to Windows Firewall """
    subprocess.call("netsh advfirewall firewall add rule name="+ rule_name +" dir=out action=block enable=no program=" + file_path, shell=True, stdout=DEVNULL, stderr=DEVNULL)
    print("Rule", rule_name, "for", file_path, "added")

def modifyRule(rule_name, state):
    """ Enable/Disable specific rule, 0 = Disable / 1 = Enable """
    if state:
        subprocess.call("netsh advfirewall firewall set rule name="+ rule_name +" new enable=yes", shell=True, stdout=DEVNULL, stderr=DEVNULL)
        print("Rule", rule_name, "Enabled")
    else:
        subprocess.call("netsh advfirewall firewall set rule name="+ rule_name +" new enable=no", shell=True, stdout=DEVNULL, stderr=DEVNULL)
        print("Rule", rule_name, "Disabled")

chkAdmin()
addRule("RULE_NAME", "PATH_TO_FILE")
modifyRule("RULE_NAME", 1)


texts: Counting vowels and consonants in a string

texts:
The output should display as follows...

PROGRAM: Vowel count

Please, enter a text string: fred
4 characters
a e i o u
0 1 0 0 0
b c d f g h j k l m n p q r s t v w x y z
0 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0

It works; but, I  believe is way over long...; maybe, I should have used arrays/or, ASCII count/-etc.?

vowels="aeiou"
aCount=eCount=iCount=oCount=uCount=0

consonants="bcdfghjklmnpqrstvwxyz"
bCount=cCount=dCount=fCount=gCount=hCount=jCount=kCount=lCount=mCount=nCount=oCount=pCount=qCount=rCount=sCount=tCount=uCount=vCount=wCount=xCount=yCount=zCount=0

print("PROGRAM: Vowel count\n")

aString=input("Please, enter a text string: ")

for eachChar in aString:

    if eachChar in vowels:
        if eachChar == "a": aCount+=1
        if eachChar == "e": eCount+=1
        if eachChar == "i": iCount+=1
        if eachChar == "o": oCount+=1
        if eachChar == "u": uCount+=1

    if eachChar in consonants:
        if eachChar == "b": bCount+=1
        if eachChar == "c": cCount+=1
        if eachChar == "d": dCount+=1
        if eachChar == "f": fCount+=1
        if eachChar == "g": gCount+=1
        if eachChar == "h": hCount+=1
        if eachChar == "j": jCount+=1
        if eachChar == "k": kCount+=1
        if eachChar == "l": lCount+=1
        if eachChar == "m": mCount+=1
        if eachChar == "n": nCount+=1
        if eachChar == "p": pCount+=1
        if eachChar == "q": qCount+=1
        if eachChar == "r": rCount+=1
        if eachChar == "s": sCount+=1
        if eachChar == "t": tCount+=1
        if eachChar == "v": vCount+=1
        if eachChar == "w": wCount+=1
        if eachChar == "x": xCount+=1
        if eachChar == "y": yCount+=1
        if eachChar == "z": zCount+=1

print(len(aString),"characters")

print("a","e","i","o","u")
print(aCount,eCount,iCount,oCount,uCount)

print("b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z")
print(bCount,cCount,dCount,fCount,gCount,hCount,jCount,kCount,lCount,mCount,nCount,pCount,qCount,rCount,sCount,tCount,vCount,wCount,xCount,yCount,zCount)


texts:
Can my code be reviewed by common C++ formatting standards, and can it be optimized? My code determines if the number (x) you input is greater then the other number (y) you input, the code then prints out the results.

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

using namespace std;

int oper();

int main() {
    oper(); //function for the operation.
}
int oper() {
    int x = 0;
    int y = 0;
    int c;

    std::cin >> x;
    std::cin >> y;

    if (x > y)
        cout << "\nx = " << x <<
        ", y must be < " << x << "\n";

}


texts:
I have been studying C#, and I have made a simple math quiz program.

Is my program reasonable or is there anything I need to improve?

class Program
{

    static void Main(string[] args)
    {
        Console.WriteLine("============== Math Game ===================");

        double num1, num2;
        double userInput;
        int randomIndex;
        double sum = 0;
        string operation;

        // [2]
        //int lives = 0;

        // Console.Write("How many lives do you want?\t");
        // lives = Convert.ToInt32(Console.ReadLine());
        // Console.WriteLine("You have  {0} Lives", lives);

        bool isPlaying = true;
        do
        {
            // 1 generate randon#
            Random rnd = new Random();
            randomIndex = rnd.Next(1, 4);
            num1 = rnd.Next(1, 11);
            num2 = rnd.Next(1, 11);

            // 2 cal sum && operation && Display
            sum = Cal(num1, num2, randomIndex);
            operation = Operation(randomIndex);

           // DisplayProblem(num1, num2, operation);

            // 3 request input
            userInput = RequestInput(num1,num2,operation);

            // 4 check answer
            CheckAnswer(userInput, sum);

        } while (isPlaying);

    }
    private static double Cal(double num1, double num2, int randomIndex)
    {
        double sum = 0;
        switch (randomIndex)
        {
            case 1:
                sum = num1 + num2;
                break;
            case 2:
                sum = num1 - num2;
                break;
            case 3:
                sum = num1 * num2;
                break;
            case 4:
                sum = num1 / num2;
                break;
            default:
                Console.WriteLine("Error");
                break;
        }
        return sum;
    }
    private static string Operation(int randomIndex)
    {
        string operation = "";

        switch (randomIndex)
        {
            case 1:
                operation = "+";
                break;
            case 2:
                operation = "-";
                break;
            case 3:
                operation = "*";
                break;
            case 4:
                operation = "/";
                break;
            default:
                Console.WriteLine("error");
                break;
        }
        return operation;
    }
    private static void DisplayProblem(double num1, double num2, string operation)
    {
        Console.Write($"{num1} {operation} {num2}  = ");
    }
    private static double RequestInput(double num1, double num2, string operation)
    {
        DisplayProblem(num1, num2, operation);

        double userInput;
        while (!Double.TryParse(Console.ReadLine(),out userInput))
        {
            Console.WriteLine("Invalid input. Please type a whole num");
            DisplayProblem(num1, num2, operation);
        }
        return userInput;
    }
    private static void CheckAnswer(double userInput, double sum)
    {
        if (userInput == sum)
        {
            Console.WriteLine("Correct Answer.");
        }
        else if(userInput != sum)
        {
            Console.WriteLine("Wrong Answer.");
        }
    }
}


texts:
I would like to refactor that code.

def experiences
  work_experience_array = @coach.delete(:work_experience)
  education_array = @coach.delete(:education)

  array = []
  array << work_experience_array.map do |experience|
    Db::Experiences::Work.new(experience.for_indexing)
  end
  array << education_array.map do |experience|
    Db::Experiences::Education.new(experience.for_indexing)
  end
  array.flatten
end


texts: String constructible from short list of words? AtCoder ABC049C - Daydream

texts:
I am practicing python, and in order to brush up my skill, I am trying the programming contest site AtCoder's past problems.

Daydream

Basically, you are given an input string and have to output YES if the string is constructed with choices of 4 different words ('dream', 'dreamer', 'erase', 'eraser'), otherwise NO.

I implemented as following.

I am aware that there are much better solutions out there, but mine also should work. However, even though first 3 cases were accepted as answers, but other 15 cases fails, and I cannot figure out why my code could fail.

ddee = ('dream', 'dreamer', 'erase', 'eraser')

def match_and_move(s, t, i):
    """checks if string s starts with any of the 4 choices starting from index i"""
    if s == t:
        return True
    for word in ddee:
        if s.startswith(word, i):
            if match_and_move(s, t+word, i+len(word)):
                return True
    return False

S = input()
T = ''
print('YES' if match_and_move(S, T, 0) else 'NO')

What am I doing wrong here?

Any assistance would be appreciated.

Thank you in advanced.

EDIT :

Because this is programming contest site, I was not provided with the input file for the all 18 tests.
I just know that first 3 tests were marked 'AC - Accepted' and other 15 tests were marked 'RE - Runtime Error' without actual error being displayed.
I performed test on my own based on the requirements (as well as the example provided by them on the question page).
At least I know that this code is working as they intended even if it is partially.

EDIT 2 / Answer :

Since this question is closed, I cannot place a separate answer.

Further testing my code, I was looking further in to the constraints.

1≦|S|≦10^5
s consists of lowercase English letters.

I prepared a string that is 7000 characters long 'dreamerdreamer...dreamer' which should return 'YES' as this is just a repeat of 'dreamer' which is one of the 4 phrases.

And I received following error.

RecursionError: maximum recursion depth exceeded in comparison

Which is self explanatory. (and is also something @VincentRG has suggested)

import sys
sys.setrecursionlimit(10**6)

By adding above, on my PC this program is working with this large input. 5 more problems are solved on the website, and 10 of the website's test were returning Memory Limit Exception, which also make sense.