texts:
Kruptos is a simple tool that encrypts and decrypts the ~/.kruptos directory with the password that is stored in ~/.kruptos/.phrazein. There are 3 commands:

e - Encrypt
d - Decrypt
i - Initialize

Goal
I have a couple main goals:

Design: How could I make this more resilient to change?
Readability: How could I make this more readable?
Best Practices: Are there aspects of a bash command that I am missing?

# Minimalist password manager
function kruptos
{
    # Decipher the flag
    if [[ $# -eq 1 ]]; then
        DOWHAT="$1"
    else
        DOWHAT="d"
    fi

    # Perform an action
    if [[ $DOWHAT == "d" ]]; then
        #Decrypt
        pushd . &>/dev/null
        cd ~/
        openssl aes-256-cbc -d  -in .kruptos.tar.gz.aes | tar -xz -f - --strip-components=2 && rm ~/.kruptos.tar.gz.aes
        popd &>/dev/null
    elif [[ $DOWHAT == "e" ]]; then
        #Encrypt
        tar -zcf - ~/.kruptos | openssl aes-256-cbc -out ~/.kruptos.tar.gz.aes -kfile ~/.kruptos/.phrazein && rm -r ~/.kruptos
    elif [[ $DOWHAT == "i" ]]; then
        #Initialize
        mkdir ~/.kruptos
        echo pswd > ~/.kruptos/.phrazein
    else
        echo "$DOWHAT is not an acceptable flag"
    fi
}


texts: Average interval between dates with random blanks

texts:
I have a spreadsheet with order date data:

I need to find the average interval in days between each order date.  I have to both find a way to get past the blank cells in the row, and also take into account that some clients have 5-10 orders and some clients have 2 orders when calculating my average frequency (interval) between orders.

Sub DateInt()
    Dim CurrentSheet As Worksheet
    Dim LastRow As Integer
    Dim LastCol As Integer
    Dim CurrentRow As Integer
    Dim CurrentCol As Integer
    Dim GrandT As String
    Dim DateA As Date
    Dim DateB As Date
    Dim DateTtl As Integer
    Dim DateCount As Integer

    Set CurrentSheet = ActiveWorkbook.ActiveSheet
    LastRow = CurrentSheet.Range("A" & Rows.Count).End(xlUp).Row - 1
    LastCol = CurrentSheet.Cells(4, Columns.Count).End(xlToLeft).Column

    Cells(4, LastCol + 1).Value = "Avg Interval"
    Cells(4, LastCol + 2).Value = "Days Since Last Order"
    Cells(4, LastCol + 3).Value = "Last Order Date"
    Cells(4, LastCol + 4).Value = "Last Order v Avg Order"

    For CurrentRow = 5 To LastRow
        Cells(CurrentRow, LastCol).Value = Date
        Cells(CurrentRow, LastCol).NumberFormat = "mm/dd/yy"
        DateCount = 0
        DateTtl = 0
        DateC = DateAdd("d", 20, Date)

        For CurrentCol = 2 To LastCol
            If Cells(CurrentRow, CurrentCol).Value = "" Then
            Else
                If DateCount < 1 Then
                    DateA = Cells(CurrentRow, CurrentCol).Value
                Else
                    DateB = Cells(CurrentRow, CurrentCol).Value
                    DateTtl = DateDiff("d", DateA, DateB) + DateTtl

                    If DateValue(DateB) = DateValue(Date) Then
                    Else
                        DateA = DateB
                    End If
                End If

                DateCount = DateCount + 1
            End If
        Next CurrentCol

        Cells(CurrentRow, LastCol + 1).Value = DateTtl / DateCount
        Cells(CurrentRow, LastCol + 1).NumberFormat = "General"
        Cells(CurrentRow, LastCol + 2).Value = DateDiff("d", DateA, Date)
        Cells(CurrentRow, LastCol + 2).NumberFormat = "General"
        Cells(CurrentRow, LastCol + 3).Value = DateA
        Cells(CurrentRow, LastCol + 3).NumberFormat = "mm/dd/yy"
        Cells(CurrentRow, LastCol + 4).Value = Cells(CurrentRow, LastCol + 1).Value - Cells(CurrentRow, LastCol + 2).Value
        Cells(CurrentRow, LastCol + 4).NumberFormat = "#,##0_);[Red](#,##0)"
        Next CurrentRow

End Sub

Here is what my code ended up doing:


texts:
I wanted to create a basic interaction which does 1 outcome but with 2 possible actions: get a number from an other document, by either clicking on a button or waiting a fixed amount of time.

I wrote this, which works:

//Initialize the ajax function
(function($) {
    $.fn.getNumber = function() {
        $(this).load('number.html .giver');
    };
})(jQuery);

//Launch ajax function 3s after DOM is loaded
$(function() {
    $('.receiver').delay(3000).queue(function(nxt) {
        $(this).getNumber();
    });
});

//Launch ajax function if a button is clicked
$('button').click(function() {
    $('.receiver').getNumber();
});

Now even if it works I'm pretty sure my code is badly written, for instance my getNumber function seem redundant. I just fear I might get bad habits, any insights of how I could write this in a more elegant way?


texts:
How can I write my code more efficient (not repeating same code)?

And is there a solution that simplifies the way of having to create a lot of dependency objects over and over again whenever I instantiate a new class (as seen in the load method)?

Any suggestions are welcome.

class Router
{
    private $request;
    private $cleanUri;
    # control attributes
    private $controller;
    private $action;
    private $params = [];

    public function __construct(Request $request)
    {
        $this->request  = $request;
        $this->cleanUri = preg_replace(['#/+#', '(\.\./)'], '/', trim($request->getUri(), '/'));

        $this->parseUri();
        $this->load();
    }

    private function parseUri()
    {
        $parts            = explode('/', $this->cleanUri);
        $this->controller = ($this->cleanUri !== '' ? ucfirst(array_shift($parts))  : 'Index') . 'Controller';
        $this->action     = array_shift($parts);
        $this->params     = !empty($parts) ? $parts : null;
    }

    private function load()
    {
        if (class_exists($this->controller)) {
            if (empty($this->action)) {
                $this->action = 'index';
            } elseif ($this->action !== 'index' && method_exists($this->controller, $this->action)) {
                //$action value stays the same
            } else {
                if (class_exists('_404Controller')) {
                    $controller = new _404Controller();

                    $controller->index();
                } else {
                    throw new Exception('404 controller not found. Page doesn\'t exist for: ' . $this->request->getUri());
                }
            }

            $controller = $this->controller;

            //create dependencies
            $db   = new Database();
            $user = new User($db, $this->request);
            $menu = new MenuHelper($this->request, $user);

            $controller = new $controller($this->request, $user, $menu);
            $action     = $this->action;

            $controller->$action();
        } else {
            if (class_exists('_404Controller')) {
                $controller = new _404Controller();

                $controller->index();
            } else {
                throw new Exception('404 controller not found. Page doesn\'t exist for: ' . $this->request->getUri());
            }
        }
    }
}


texts: Implementing two stacks using single array in java

texts:
Please review the code

package com.gmail.practice;

import java.util.Arrays;

public class StacksForTwo {

    int size;
    int[] stack;
    int top1;
    int top2;

    public StacksForTwo(int arraysize)
    {
        size = arraysize;
        stack = new int[size];
        top1 = -1;
        top2 = size;
    }

    public void push1(int x)
    {
        if(top1 < top2-1)
        {
        top1++;
        stack[top1] = x;
        }else{
            System.out.println("stackoverflow");
        }
    }

    public void push2(int y)
    {
        if(top1 < top2-1)
        {
            top2--;
            stack[top2] = y;
        }else{
            System.out.println("stack overflow");
        }
    }

    public void pop1()
    {
        if(top1 >= 0)
        {
            top1--;
            System.out.println("The popped out number is"+" "+stack[top1+1]);
        }else{
            System.out.println("stack underflow");
        }
    }

    public void pop2()
    {
        if(top2 < size)
        {
            top2++;
            System.out.println("The popped out number is"+" "+stack[top2+1]);
        }else{
            System.out.println("stack underflow");
        }
    }

    public void display()
    {
        System.out.println(Arrays.toString(stack));
    }

    public static void main(String[] args)
    {
        StacksForTwo sft = new StacksForTwo(10);
        sft.push1(4);
        sft.push1(5);
        sft.push1(3);
        sft.push1(2);
        sft.push2(6);
        sft.push2(4);
        sft.display();
        sft.push2(8);
        sft.push1(2);
        sft.push2(6);
        sft.push2(4);
        sft.push2(8);
        sft.display();
    }
}


texts:
I have a class which is responsible for checking whether a website is up or down. I've made it to run asynchronously, but I would like critique if this is a good/bad way or if there is another better way to do it.

class UrlChecker {
    private readonly IValidationCondition _condition;
    private readonly Dictionary<string, UrlStatus> _status = new Dictionary<string, UrlStatus>();
    private readonly object _lock = new object();

    public UrlChecker(IValidationCondition condition) {
        _condition = condition;
    }

    public void CheckRange(IEnumerable<string> urls, Action<Dictionary<string, UrlStatus>> callback) {
        var options = new ParallelOptions {MaxDegreeOfParallelism = 5};
        Parallel.ForEach(urls, options, Check);

        callback(_status);
    }

    private void Check(string url) {
        Console.WriteLine("Checking " + url);

        var req = (HttpWebRequest) WebRequest.Create(url);
        req.Timeout = 10 * 10000; // 10 seconds

        HttpWebResponse resp;

        try {
            resp = (HttpWebResponse)req.GetResponse();
        }
        catch(WebException ex) {
            // We got an exception, consider it as down
            lock (_lock)
                _status.Add(url, UrlStatus.Down);
            return;
        }

        if(resp.StatusCode != HttpStatusCode.OK) {
            lock (_lock)
                _status.Add(url, UrlStatus.Down);
            return;
        }

        using(var reader = new StreamReader(resp.GetResponseStream())) {
            // Check for empty response
            var html = reader.ReadToEnd();
            if(string.IsNullOrEmpty(html)) {
                lock(_lock) {
                    _status.Add(url, UrlStatus.Down);
                }
            }

            // Validate against condition
            if(!_condition.IsValid(html)) {
                lock(_lock) {
                    _status.Add(url, UrlStatus.Down);
                }
                return;
            }
        }

        // We reached the end without problems, it's a valid url
        lock(_lock) {
            _status.Add(url, UrlStatus.OK);
        }
    }
}

It's called like so:

checker.CheckRange(urls, status => {
    if(status.Any(x => x.Value == UrlStatus.Down))
        EmailFailing(message);
});

The second parameter is obviously a callback that's invoked when all checks are done.

Am I locking correctly?

Is this an acceptable way of doing it? Checking with Fiddler proves that it's working correctly, but is there a better way?


texts: Eliminating columns from a matrix where the entries in two rows are equal

texts:
Is there a way to reduce the computation time in this program that eliminates the columns of a matrix A if for a given column the element of line 4 is equal to the element in row 5:

k=1;
for i=1:4000
   if A(4,i) ~= A(5,i)
      B(:,k)=A(:,i);
      k=k+1;
   end
end


texts: Printing the status of a database insertion as JSON

texts:
The controller is currently inserting a record into the database and returning a JSON response as shown below in the try-catch block. I can see the Inserted Successfully within the try-catch block!. Although,
I haven't seen this message Error in Inserting Record! so far since my webservice haven't errored out till now.

Please let me know if the approach I have followed to display just two lines of JSON is an efficient / conventional way of doing similar things ? If it can be improved, please suggest.

@RequestMapping(value = "/insertRecord", method = RequestMethod.POST)
 public Map<String, String> insertRecord
  (
   @RequestParam(value = "type_id", defaultValue = "0") Integer type_id,
   @RequestParam(value = "tempID", defaultValue = "0") Integer tempID,
   @RequestParam(value = "status", defaultValue = "") String successORFailure,
   @RequestParam(value = "notes", defaultValue = "") String message
  ) {

   Map<String, String> response =  new HashMap<String,String>();

   try {

    insertRecordDao insertDao = (insertRecordDao) context.getBean("insertRecordDao");
    insertDao.insertAuditInfo(type_id, tempID, successORFailure, message);
    response.put("message", "Inserted Successfully within the try-catch block!");
    response.put("status", "SUCCESS");

   } catch (Throwable th) {
    th.printStackTrace();
    response.put("message", "Error in Inserting Record!");
    response.put("status", "ERROR");

   }

    return response;

  }

Here's a JSON response from my POSTMAN client:


texts: Given a function that returns a random number 0 or 1, write a function that returns a number between 0 and 199

texts:
We are given a function f2(), that can return either 0 or 1 with equal probability. Now using this function f2() only, write a function f200() which returns a number from 0 to 199 with equal probability distribution.

In Ruby:

def f2
  return Random.rand(2)
end

def f200
  # this function makes use of the property that, if you throw away
  # evenly distributed numbers, the rest of the numbers are still
  # evenly distributed

  while true do
    max = 0
    result = 0

    while max < 199 do
      result <<= 1
      max <<= 1
      result += f2()    # f2() gives a random bit
      max += 1
    end

    return result if result >= 0 && result <= 199
  end

end

# this part is only for testing: ==========================================

def print_report(tally)
  number_of_keys = tally.keys().length
  total = tally.values().inject(:+)
  expected_count = total.to_f / number_of_keys

  tally.keys().sort().each {|k| puts "%-8i %-8i off by %6.3f %" % [k, tally[k], ((tally[k] - expected_count) / expected_count * 100).abs()] }
end

n = 1_000_000
puts "checking f200() for #{n} times:"
tallyForF200 = Hash.new(0)
n.times { r = f200(); tallyForF200[r] += 1 }
print_report(tallyForF200)

If you want to see a better result (of more even distributed numbers), increase the n, which is set to 1_000_000 near the end to 10_000_000.


texts: MS VS solution structure w.r.t. dependency injection unit tests?

texts:
Is the following MS VS solution structure and classes OK w.r.t. easy unit tests with dependency injection? Would your unit tests look similar?

If you call the calculations below over a WPF module, would you skip a test over the WPF since complicated, or would you still conisder testing it over the WPF module ?

Solution

ProjectWork

Classes

IDev.cs

public interface IDev
{
  IToMeasure Measure();
}
public interface IToMeasure
{
  double Value{ get; set; }
}

CalculatingUnit.cs

public class CalculatingUnit
{
   int count = 0,
       maxMeasuredValues = 20;

   public double doMeasures(IDev myDevice)
   {
      // simulating measuring each Xms
      while (count < maxMeasuredValues )
      {
         return myDevice.Measure();
         count++;
      }
   }
}

MyDevice.cs

// non-deterministic (random) values
public class MyDevice: IDev
{
   private readonly MyRandom myRandomVar = new Random(0);

   public IToMeasure Measure()
   {
      var meas = new Measure { Value = myRandomVar.NextRandom(2, 0.5) };
      return meas;
   }
}

TestDevice.cs

// deterministic values
public class TestDevice : IDevice
{
   int nrValues = 6;
   int gIdx = 0,
   gCount = 0;
   int[] testMeasures = { 1, 2, 3, 4, 5, 6 };

   public IToMeasure Measure()
   {
      gIdx = gCount % nrValues;
      var meas = new Measure { Value = testMeasures[gIdx] };
      gCount++;

      return meas;
   }
}

myDeviceWPF.cs // it seems complicated testing over WPF, so I dont test with it, would you also skip it ?

class myDeviceViewModel : INotifyPropertyChanged
{
  ...
}

ProjectTest

myDevice_Test.cs

[TestClass]
public class myDevice_Test
{
    [TestMethod]
    public void Test_doMeasures()
    {
        double actual = 1;
        double expected = 21.068;

        TestDevice myDevice;
        CalculatingUnit myCalculatingUnit;

        myDevice = new TestDevice();
        myCalculatingUnit = new CalculatingUnit();

        actual = myCalculatingUnit.doMeasures(myDevice );
        Assert.AreEqual(expected, actual , 0.001, "Wrong calculations");
    }
}


texts: Working with Locales in Swing (with change at runtime)?

texts:
I thought about the best way to implement localisation with runtime  in Swing.

I currently solve the problem like that:

JMenu menuData = new JMenu("Data");
    menuData.setName("mainframe.menu.data"); // property key
    localeChangedListener.add(menuData);

The LocaleChangedListener:

public class SwingLocaleChangedListener implements LocaleChangedListener {

    private ArrayList<AbstractButton>   abstractButtons;

    @Override
    public void localeChanged(ResourceBundle rb) {
        logger.info("Locale changed to '" + rb.getLocale() + "'");
        for (AbstractButton b : abstractButtons) {
            b.setText(rb.getString(b.getName()));
            b.setComponentOrientation(ComponentOrientation.getOrientation(rb.getLocale())); //EDIT: Line added
        }

    }

    public boolean add(AbstractButton b) {
        initAbstractButtons();
        return abstractButtons.add(b);
    }

    private void initAbstractButtons() {
        if (abstractButtons == null) {
            this.abstractButtons = new ArrayList<AbstractButton>();
        }
    }
}

And the registration of the Listener:

public class GuiBundleManager {

    private String                  filePrefix  = "language.lang";
    private ResourceBundle          rb         = null;
    private LocaleChangedListener   listener    = null;

    private static GuiBundleManager instance    = null;

    private GuiBundleManager() {
        setLocale(Locale.getDefault());
    }

    public String getString(String key) {
        return rb.getString(key);
    }

    public String[] getStringArray(String key) {
        return rb.getStringArray(key);
    }

    public Locale getLocale() {
        return rb.getLocale();
    }

    public void setLocale(Locale l) {
        rb = ResourceBundle.getBundle(filePrefix, l);
        if (listener != null) {
            listener.localeChanged(rb);
        }
    }

    public LocaleChangedListener getLocaleChangedListener() {
        return listener;
    }

    public void setLocaleChangedListener(LocaleChangedListener listener) {
        this.listener = listener;
        if (listener != null) {
            listener.localeChanged(rb);
        }
    }

    public static GuiBundleManager get() {
        if (instance == null) {
            instance = new GuiBundleManager();
        }
        return instance;
    }
}

Another way I'm thinking of is using Component.setLocale() combined with an PropertyChangedListener:

public abstract class GUIComponentFactory {

    public JLabel createLocalisedJLabel(final String key) {
        final JLabel label = new JLabel(GuiBundleManager.get().getString(key));
        label.addPropertyChangeListener("locale", new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent e) {
                label.setText(GuiBundleManager.get().getString(key));
                label.setComponentOrientation(ComponentOrientation.getOrientation(e.getNewValue())); //Edit: Line added
                for(Component c : getComponents()){
                    c.setLocale(e.getNewValue());
                }
            }
        });
                return label;
    }
    .
    .
    .
}


texts: More efficient columnar transposition decryption

texts:
Below, I have created a rudimentary script to decipher a columnar transposition. I am wondering if there is a more efficient way to determine the number of the rows in a column? Also, is there a way to build the resulting string without creating a matrix in the interim?

Overview

Quick refresher for columnar transpositions.

Method 1

Given a key of 3,

the text 'Attack at dawn' is transposed into three columns...

1   2   3
A   t   t
a   c   k
a   t   D
a   w   n

...joining each column; left->right, top->bottom; will result in the following text:

Aaaa tctw tkDn

Method 2

Given a key 'table',

the text 'Attack at dawn' is transposed into five columns (length of the key)...

t   a   b   l   e
A   t   t   a   c
k   a   t   D   a
w   n

...joining the columns, as described above, result in the following text:

tAkw atan btt laD eca

Code

Is there a better way to determine how many rows will be present for each column?

function decrypt(ciphertext, key) {
    var chars   = normalizeText(ciphertext);
    var len     = chars.length;
    var isStr   = typeof key === 'string';
    var cols    = isStr ? key.length : key;
    var rows    = Math.ceil(len / cols);
    var mod     = divMod(len, cols)[1];
    var matrix  = Matrix(rows, cols, '');
    var counter = 0;
    for (var col = 0; col < cols; col++) {
        var remainder = mod !== 0 && col >= mod ? 1 : 0;
        for (var row = 0; row < rows - remainder; row++) {
            matrix[row][col] = chars[counter++];
        }
    }
    return (function(plaintext, startIndex) {
        return plaintext.substr(startIndex);
    }(matrix.reduce(function(result, row) {
        return result + row.join('');
    }, ''), isStr ? cols : 0));
}

Demo

[ [ 'Aaaa tctw tkDn'       , 3       ],
  [ 'tAkw atan btt laD eca', 'table' ]
].forEach(function(cipher) {
    println(decrypt(cipher[0], cipher[1]));
});

function decrypt(ciphertext, key) {
    var chars   = normalizeText(ciphertext);
    var len     = chars.length;
    var isStr   = typeof key === 'string';
    var cols    = isStr ? key.length : key;
    var rows    = Math.ceil(len / cols);
    var mod     = divMod(len, cols)[1];
    var matrix  = Matrix(rows, cols, '');
    var counter = 0;
    for (var col = 0; col < cols; col++) {
        var remainder = mod !== 0 && col >= mod ? 1 : 0;
        for (var row = 0; row < rows - remainder; row++) {
            matrix[row][col] = chars[counter++];
        }
    }
    return (function(plaintext, startIndex) {
        return plaintext.substr(startIndex);
    }(matrix.reduce(function(result, row) {
        return result + row.join('');
    }, ''), isStr ? cols : 0));
}
function divMod(y, x) {
    return [~~(y / x), y % x];
}
function normalizeText(ciphertext) {
    return ciphertext.replace(/ +/g, "").split('');
}
function Matrix(rows, cols, defaultVal) {
    defaultVal = defaultVal !== undefined ? defaultVal : 0;
    var arr = [];
    for (var i = 0; i < rows; i++) {
        arr.push([]);
        arr[i].push(new Array(cols));
        for (var j = 0; j < cols; j++) {
            arr[i][j] = defaultVal;
        }
    }
    return arr;
}
function print(str, targetEl) {
    return (function (el) {
        return el.html(el.html() + (str || ''));
    }(targetEl || $('#out')));
}
function println(str, targetEl) {
    print((str || '') + '
', targetEl)
}


texts:
Considering I'm not implementing distributed lock mechanism, is this code correct and clear?

class RedisLock
  class NotAcquired < StandardError; end

  def initialize(redis)
    @redis = redis
  end

  def lock(key, expiration_ms)
    val = SecureRandom.random_number(100000000000000000).to_s

    if @redis.set(key, val, nx: true, px: expiration_ms)
      yield
      unlock(key, val)
      true
    else
      false
    end
  end

  def lock!(*args, &block)
    unless lock(*args, &block)
      raise NotAcquired.new("Could not acquire lock with #{args}")
    end
  end

  def unlock(key, val)
    check_and_delete = <<-LUA
      if redis.call('get', KEYS[1]) == KEYS[2] then
        redis.call('del', KEYS[1])
      end
    LUA

    @redis.eval(check_and_delete, [key, val])
  end
end

RedisLock.new(Redis.current).lock!('key', 10000) { do_something }


texts:
The challenge (PDF) is to convert a time from 12-hour format (hh:mm:ssAM or hh:mm:ssPM) to 24-hour format.

This is my solution, which worked for all test cases.

string timeConversion(string s) {
    int size = s.length();
    if(s[size-2]=='A'){
        string hh = s.substr(0,2);
        int h = stoi(hh);
        if(h==12){
            string newh = "00";
            string newTime = newh.append(s.substr(2,6));
            return newTime;
        }else{
            return s.substr(0,size-2);
        }
    }
    else{
        string hh = s.substr(0,2);
        int h = stoi(hh);
        if(h==12){
            return s.substr(0,size-2);
        }
        int inPM = h+12;
        string newh = to_string(inPM);
        string newTime = newh.append(s.substr(2,6));
        return newTime;
    }
}

Anything which I could have done in a different way in your opinion?


texts: Project Euler - #5 smallest multiple (Ruby using a hash table)

texts:
Why will this code work for a smaller multiple like 10 but time out for anything over 13? Can this code be revised to work for larger numbers?

(I have an alternate solution but wanted to see if this code could be fixed to work for more multiples.)

#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

multiple = 10
y = multiple
hash = Hash.new(0)

loop do
    if hash.has_value?(multiple) || y == 0
        break
    end
    for x in 1..multiple do
        if y % x == 0
            hash[y] += 1
        end
    end
    y += multiple
end

puts "Smallest number = #{y - multiple}"
hash.has_value?(multiple)


texts:
I'm making a card game and I found useful to include a 60 second countdown timer. Here is my approach:

import java.util.Timer;
import java.util.TimerTask;

public class SecondTimer {

    private Timer timer;
    private int countDown;
    private int secondsLeft;

    public SecondTimer() {
        timer = new Timer();
    }

    public void reset() {
        secondsLeft = countDown;
        // Decrease seconds left every 1 second.
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                secondsLeft--;
                if (secondsLeft == 0) {
                    timer.cancel();
                }
            }
        }, 0, 1000);
    }

    public void setCountDown(int seconds) {
        this.countDown = seconds;
    }

    public int getSecondsLeft() {
        return secondsLeft;
    }
}

Is this considered clean? How can I test such classes?


texts: Using case and switch macros for strings

texts:
I'd like this reviewed.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SWITCH(S) char *_S = S; if (0)
#define CASE(S) } else if (strcmp(_S, S) == 0) {switch(1) { case 1
#define BREAK }
#define DEFAULT } else {switch(1) { case 1

int main()
{
    char buf[256];

    printf("\nString - Enter your string: ");
    scanf ("%s", buf);

    SWITCH (buf) {
        CASE ("abcdef"):
            printf ("B1!\n");
            BREAK;
        CASE ("ghijkl"):
            printf ("C1!\n");
            BREAK;
        DEFAULT:
            printf ("D1!\n");
            BREAK;
    }
}


texts: Flask app to return close prices & average

texts:
I've been working on a little challenge in order to learn more.. I've written the following code, which works. I'm just concerned that there are several areas where my lack of in depth Python knowledge has forced me to 'go the long way around'. I'm really keep to learn more and learn in the correct way, so looking for areas I can improve the code & also shorten it where possible.
The idea is, we use a free API to obtain some JSON data containing a list of dates and stock price information. The JSON gives a 'refreshed date' which is the latest date the data has been obtained, I'm then calculating a list of N dates PRIOR to this date, and returning the stock close price for each of those past days, and then returning the average of those prices.
The code works, and I'm quite happy of that.. but I don't want to stop here. I want to make sure I'm learning the right way.
Since the stock market is closed on Sat/Sun, we need to avoid weekends when calculating the list of dates, so N=3 on a Monday, would be 3 'stock market' days prior to Monday, thus - Mon, Fri, Thu.
For anyone who is interested in looking at the format of data being read in there's a demo API key: https://www.alphavantage.co/query?apikey=demo&function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT
CODE:
from datetime import date, timedelta, datetime
import json
from requests import Request, Session
from flask import Flask, make_response

app = Flask(__name__)

# To be passed in with ENV-Vars
SYMBOL='MSFT'
NDAYS = 3

api_key = 'apikey="XXXXXXXX"&'
function = 'function=TIME_SERIES_DAILY_ADJUSTED&'
symbol = f'symbol={SYMBOL}'
url = f'https://www.alphavantage.co/query?{api_key}{function}{symbol}'

session = Session()
output = session.get(url)
data = json.loads(output.text)

refreshed = datetime.strptime(str(data['Meta Data']['3. Last Refreshed']), '%Y-%m-%d').date()
dates = []
output = {}
def prev_days(rdate):
    rdate -= timedelta(days=NDAYS)
    while rdate.weekday() > 4:
        rdate -= timedelta(days=1)
    return rdate

past_date = prev_days(refreshed)

delta = refreshed - past_date
for i in range(delta.days + 1):
    dates.append(refreshed - timedelta(days=i))

for date in dates:
    close = data['Time Series (Daily)'][str(date)]['4. close']
    output.update({str(date): float(close)})

avg = sum(list(output.values())) / len(list(output.values()))

def resp():
    return f'{SYMBOL} data={list(output.values())}, average={avg}'

@app.route('/')
def main():
    response = make_response(resp(), 200)
    response.mimetype = "text/plain"
    return response

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)


texts:
I have a project which we need to migrate from an on-prem solution to the AWS cloud. Currently, the software is running on a single instance. It's working fine but the business want the software to be Highly Available (HA). As part of the HA, the program will be installed on a shared file system (AWS EFS) and mount the filesystem on the multiple EC2 instances so that the same configuration accessed by all the instances.
The challenge for me is
PHP_ETC_BASE=/etc/php/7.0
PHP_INI=${PHP_ETC_BASE}/apache2/php.ini

I can install PHP on all the AWS EC2 instances (PHP_ETC_BASE) but the PHP_INI need to be on a shared file system so that the configuration can be accessed by other instances. What I read is that I cant move /etc/php/7.0 to a shared filesystem then PHP wont work
  installDepsPhp70 () {
  debug "Installing PHP 7.0 dependencies"
  PHP_ETC_BASE=/etc/php/7.0
  PHP_INI=${PHP_ETC_BASE}/apache2/php.ini
  checkAptLock
  sudo apt install -qy \
  libapache2-mod-php \
  php php-cli \
  php-dev \
  php-json php-xml php-mysql php-opcache php-readline php-mbstring php-zip \
  php-redis php-gnupg \
  php-gd

  for key in upload_max_filesize post_max_size max_execution_time max_input_time memory_limit
  do
      sudo sed -i "s/^\($key\).*/\1 = $(eval echo \${$key})/" $PHP_INI
  done
  sudo sed -i "s/^\(session.sid_length\).*/\1 = $(eval echo \${session0sid_length})/" $PHP_INI
  sudo sed -i "s/^\(session.use_strict_mode\).*/\1 = $(eval echo \${session0use_strict_mode})/" $PHP_INI
}

Similar issue for the /var/lib/mysql
prepareDB () {
  if sudo test ! -e "/var/lib/mysql/mysql/"; then
    #Make sure initial tables are created in MySQL
    debug "Install mysql tables"
    sudo mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
    sudo service mysql start
  fi

  if sudo test ! -e "/var/lib/mysql/misp/"; then
    debug "Start mysql"
    sudo service mysql start


texts:
I have a drop down menu that will run a function onchange. The function takes times from an array , adds a specific amount of time , then changes the innerHTML of the table.

The code works , but is there a simpler version? I plan on adding more options to the drop down menu.

HTML

<select id="sel1" onchange="myFunction()">

   <option value="VIC">VIC</option>
   <option value="NSW">NSW</option>

</select>

        A
        2016-08-24 16:00
        C

        A
        2016-08-24 16:00
        C

Javascript

function myFunction(){

var cellData = ["2016-08-24 15:45", "2016-08-24 16:00"];
var myTable = document.getElementById("myTable");

if (document.getElementById("sel1").value == "VIC") {

var vicTime = [];

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

date = moment(cellData[i]).add(1, 'h').format('MM/DD/YYYY hh:mm a');

vicTime.push(date);

myTable.rows[i].cells[1].innerHTML = vicTime[i];

}}

if (document.getElementById("sel1").value == "NSW") {

var nswTime = [];
var j;

for (j=0; j<cellData.length; j++) {

date = moment(cellData[j]).add(5, 'h').format('MM/DD/YYYY hh:mm a');

nswTime.push(date);

myTable.rows[j].cells[1].innerHTML = nswTime[j];

}}};


texts:
This is a simple list of items in a list, which allows the user to dynamically generate that list of events. Then a controller action does the work of serializing that into the database.

The issue is that there's the PHP-generated HTML segment, and there's a separate JavaScript segment to do the additions (for when someone presses the "add new page" button). This is not only duplicated; when it's done inline in the JavaScript it's extremely ugly to look at (look at the length of that line!).

Is there a better way of doing this?

<?php
/** @var $this Zend_View */

$this->headLink()->appendStylesheet($this->baseUrl('css/redmond/jquery-ui-1.8.5.custom.css'));

$this->headScript()->appendFile($this->baseUrl('js/jquery.js'));
$this->headScript()->appendFile($this->baseUrl('js/jquery-ui-1.8.5.custom.min.js'));

$this->headScript()->captureStart(); ?>
//
<?php $this->headScript()->captureEnd(); ?>

    <form action="<?= $this->url(array('controller' => 'admin', 'action' => 'applyEvents')) ?>" method="post">

                Add a new Event

            <? foreach ($this->events as $event) { ?>

                    <input name="dates[]" class="datebox" style="width: 120px;" type="text" value="<?= $event->GetDate()->format('Y-m-d') ?>" />

                        <input name="contents[]" type="text" value="<?= $event->GetMessage() ?>" style="width: 100%;" />

            <? } ?>

        <input type="submit" name="submit" value="Apply" />
        <input type="submit" name="submit" value="Cancel" />
    </form>


texts: Computational verification of Collatz conjecture using OpenCL

texts:
This code review request follows my previous request Computational verification of Collatz conjecture.
Unlike the previous program (which was designed for the CPU), this code should run on modern GPUs.
For this purpose, I chose OpenCL as a programming language.

Prerequisites

Since the verification program needs to deal with 128-bit arithmetic, the first thing I was forced to solve is the availability of 128-bit integer type.
So far, I rely on the __int128 compiler extension:

typedef unsigned __int128 uint128_t;

At this point my first question arises:
How efficient (in terms of performance) is this solution?
I also guess it may not be very portable, right?

For completeness, the

#define UINT128_MAX (~(uint128_t)0)

is maximum value for an object of type uint128_t.

I also needed to calculate the number of trailing zeros (ctz), which I solved as follows:

size_t ctzl(unsigned long n)
{
    return 63 - clz(n & -n);
}

size_t ctzu128(uint128_t n)
{
    size_t a = ctzl(n);

    if (a == ~0UL) {
        return 64 + ctzl(n>>64);
    }

    return a;
}

My concern here is that this could be implemented more simply.

The last building block I need is the n-th power of three:

uint128_t pow3(size_t n)
{
    uint128_t r = 1;
    uint128_t b = 3;

    while (n) {
        if (n & 1) {
            r *= b;
        }
        b *= b;
        n >>= 1;
    }

    return r;
}

All \$ 3^n \$ for \$ n < 81 \$ fit the uint128_t type.
Therefore I have the follow macro defined.

#define LUT_SIZE128 81

Code

My code verifies the convergence of the Collatz problem using this algorithm.
The range of the size 2^task_size numbers starting at task_id * 2^task_size is evenly divided among threads.
The threads do not communicate with each other.
When the calculation is complete, each thread stores their results (partial checksum, number of uint128_t overflows) into global memory.
My current solution is as follows:

__kernel void worker(
    __global unsigned long *overflow_counter,
    __global unsigned long *checksum_alpha,
    unsigned long task_id,
    unsigned long task_size,
    unsigned long task_units)
{
    unsigned long private_overflow_counter = 0;
    unsigned long private_checksum_alpha = 0;
    size_t id = get_global_id(0);

    uint128_t lut[LUT_SIZE128];

    unsigned long i;
    for (i = 0; i < LUT_SIZE128; ++i) {
        lut[i] = pow3(i);
    }

    uint128_t n_     = ((uint128_t)task_id << task_size) + ((uint128_t)(id + 0) << (task_size - task_units)) + 3;
    uint128_t n_sup_ = ((uint128_t)task_id << task_size) + ((uint128_t)(id + 1) << (task_size - task_units)) + 3;

    for (; n_ < n_sup_; n_ += 4) {
        uint128_t n = n_, n0 = n_;

        do {
            n++;
            size_t alpha = ctzu128(n);
            private_checksum_alpha += alpha;
            n >>= alpha;

            if (n > UINT128_MAX >> 2*alpha || alpha >= LUT_SIZE128) {
                private_overflow_counter++;
                break;
            }

            n *= lut[alpha];

            n--;
            n >>= ctzu128(n);

            if (n < n0) {
                break;
            }
        } while (1);
    }

    overflow_counter[id] = private_overflow_counter;
    checksum_alpha[id] = private_checksum_alpha;
}

I see an acceleration of more than two orders of magnitude compared to the CPU implementation.
My main concern (about the performance) here is that the adjacent threads do not go the same code path (the control flow is not coherent for the threads of a processor).
However, I am not sure how big this problem actually is.


texts: Determine the winner of a coin flip game

texts:
While I was writing this I had some thoughts and questions going through my head about if I was doing this in a good manner. For instance, is it good to use a StringTokenizer to loop through the words in the line I copied from the Scanner's input?

  Write a method named coinFlip that accepts as its parameter a Scanner for an input file. Assume that the input file data represents results of sets of coin flips that are either heads (H) or tails (T) in either upper or lower case, separated by at least one space. Your method should consider each line to be a separate set of coin flips and should output to the console the number of heads and the percentage of heads in that line, rounded to the nearest tenth. If this percentage is more than 50%, you should print a "You win" message.

public static void coinFlip(Scanner input) {

    int countHeads = 0;
    int countTails = 0;
    double count = 0.0;
    double ratio = 0.0;
    String line = "";

    while(input.hasNextLine()) {
        countHeads = 0;
        countTails = 0;

        line = input.nextLine();
        StringTokenizer lineTokens = new StringTokenizer(line);
        while (lineTokens.hasMoreTokens()) {
            String token = lineTokens.nextToken();
            if (token.toLowerCase().equals("h")) {
                countHeads++;
            } else {
                countTails++;
            }
        }

        count = countTails + countHeads;

        ratio = Math.abs(1 - (countTails/count)) * 100;

        System.out.printf(countHeads + " heads (%1.1f%%)\n", ratio);

        if (countHeads > countTails) {
            System.out.println("You win!\n");
        }
        else {
            System.out.println();
        }
    }
}


texts:
Please feel free to review my countdown numbers game solver. Posted here too for people working on the same problem. For clarity the print statement
"Eval..." means the program has used BODMAS on an entire mathematical statement
(e.g: 1*3+10 = 31)

"Running total" means the program recalculates the total after each move (e.g: 1*3+10 = 13 because 1*3 = 3, 3+10 = 13)

import re
def unpack(method):
    string = method
    special = ["*","+","-","/"]
    list_sum = []
    list_special = []
    numbers = (re.findall(r"[\w']+", string))
    for char in string:
        if char in special:
            list_special.append(char)

    for index in range (len(numbers)-1):
        to_eval = numbers[index] + list_special[index] + numbers[index+1]
        list_sum.append(f'{to_eval} = {eval(to_eval)}')
        numbers[index+1] = str(eval(to_eval))

    return list_sum

def evaluate (method,running_sum):
    global clear_status
    if eval(method) == target:
        if method not in list_methods:
            list_methods.append(method)
            print (f'Eval: {method}')
            clear_status = True
        return True
    if running_sum == target:
        if method not in list_methods:
            list_methods.append(method)
            print (f'Running sum: {unpack(method)}')
            clear_status = True
        return True
    clear_status = False
    return False

def new_total (total,item,operation):
    if operation == "+": return total + item
    if operation == "-": return total - item
    if operation == "*": return total * item
    if operation == "/" and item != 0: return total / item
    return ""

def solve (array,total=0,method="",list_method=[]):
    if len(array) == 0:
        return

    for (index,item) in enumerate(array):
        #Set methods and totals to "":
        add_method, sub_method, mul_method, div_method = "", "", "", ""
        add_total, sub_total, mul_total, div_total = 0, 0, 0,0

        #Assign methods and totals to a list:
        methods = [add_method, sub_method, mul_method, div_method]
        totals = [add_total, sub_total, mul_total, div_total]
        str_func = ["+", "-", "*", "/"]

        #Create new array
        remaining = array[:index] + array[index+1:]

        #Sets new totals and new "methods"
        for index_1 in range (len(methods)):
            if method =="":
                if str_func[index_1] != "/" and str_func[index_1] != "*" and str_func[index_1] != "-":
                    methods[index_1] = str(array[index])
                    totals[index_1] = new_total(total, item, str_func[index_1])
            else:
                methods[index_1] = method + str_func[index_1] + str(array[index])
                totals[index_1] = new_total(total, item, str_func[index_1])

        #Evaluates each total and method
        for index_2 in range (len(methods)):
            try:
                if evaluate(methods[index_2], totals[index_2]):
                    if clear_status == True:
                        methods[index_2]=""
                        totals[index_2]=0
                    return
            except Exception as e:
                pass

        #Recursively calculates next move
        for index_3 in range (len(methods)):
            try:
                solve(remaining, total= totals[index_3],method= methods[index_3])
            except Exception as e:
                pass

str_array = input("Please enter the starting numbers, separated by commas: ")
array = array=[int(item.strip()) for item in str_array.split(",")]
target = int(input("Please enter a target value: "))
print (f'Solutions for {array} to reach {target}')
list_methods = []
solve(array)
if list_methods == []:
    print ("Unsolvable countdown problem")
to_close = input("Press any key to exit...")


texts:
I created a monad in Haskell that lets you sample without replacement from user-defined urns, and then at the end gives you a list of all possible outcomes. It looks like it's similar to the list monad (except that one only ever samples with replacement), and to the ST monad. Here's the interface I want to present:

data Draw s a
data Urn s a
instance MonadPlus (Draw s)
newUrn :: [a] -> Draw s (Urn s a)
drawFrom :: Urn s a -> Draw s a
drawList :: [a] -> Draw s a -- so that you can still sample with replacement, like in the list monad
runDraw :: (forall s. Draw s a) -> [a]

Here's an example of how I want to use it:

runDraw $ do
  l <- newUrn [1,2,3,3]
  x <- drawFrom l
  y <- drawFrom l
  return (x, y)

-- produces [(1,2),(1,3),(1,3),(2,1),(2,3),(2,3),(3,1),(3,2),(3,3),(3,1),(3,2),(3,3)]

And here's what I came up with to implement that:

{-# LANGUAGE MagicHash, RankNTypes, RoleAnnotations #-}

module Draw (Draw, Urn, newUrn, drawFrom, drawList, runDraw) where

import Control.Applicative (Alternative(..))
import Control.Monad (MonadPlus, ap, liftM)
import Data.List (genericSplitAt)
import GHC.Exts (Any, unsafeCoerce#)
import Numeric.Natural (Natural)

newtype Draw s a = Draw { unDraw :: (Natural, [Any]) -> [(a, (Natural, [Any]))] }
type role Draw nominal representational

newtype Urn s a = Urn Natural
type role Urn nominal representational

instance Functor (Draw s) where
  fmap = liftM

instance Applicative (Draw s) where
  pure = drawList . pure
  (<*>) = ap

instance Alternative (Draw s) where
  empty = drawList empty
  Draw m1 <|> Draw m2 = Draw $ \s -> m1 s <|> m2 s

instance Monad (Draw s) where
  Draw m >>= f = Draw $ \s -> m s >>= uncurry (unDraw . f)

instance MonadPlus (Draw s)

drawList :: [a] -> Draw s a
drawList xs = Draw $ \s -> flip (,) s <$> xs

runDraw :: (forall s. Draw s a) -> [a]
runDraw (Draw f) = map fst (f (0, []))

newUrn :: [a] -> Draw s (Urn s a)
newUrn xs = Draw $ \(n, us) -> pure (Urn n, (n + 1, us ++ [toAny xs]))

drawFrom :: Urn s a -> Draw s a
drawFrom (Urn i) = Draw go where
  go :: (Natural, [Any]) -> [(a, (Natural, [Any]))]
  go (n, us) = map (\(x, remainingContents) -> (x, (n, before ++ toAny remainingContents : after))) (removeEach (fromAny urnContents)) where
    (before, urnContents:after) = genericSplitAt i us

fromAny :: Any -> [a]
fromAny = unsafeCoerce#

toAny :: [a] -> Any
toAny = unsafeCoerce#

removeEach :: [a] -> [(a, [a])]
removeEach [] = []
removeEach (x:xs) = (x, xs):map (fmap (x:)) (removeEach xs)

This seems to work, at least with the example I posted above.

Here's my concerns:

I'm doing a lot of unsafeCoerce#, which is obviously not very safe
(before, urnContents:after) = genericSplitAt i us is an incomplete pattern match, which may be able to fail at runtime
I'm building the list of urns with xs ++ [x], which is quadratically slow
I'm not confident that this satisfies all of the typeclass laws, in particular the monad law of associativity I now realize that my type is isomorphic to StateT (Natural, [Any]) [], with equivalent instances, so I'm no longer concerned about this.
I'm not sure if the way I'm handling the urns is correct, or if it's somehow possible to use an urn where it doesn't belong and thus break type safety


texts: Why is this code to paste into a DataGridView so slow?

texts:
string s = Clipboard.GetText().Replace("\r", " ");
string[] lines = s.Split('\n');
int row = dgView.CurrentCell.RowIndex;
int col = dgView.CurrentCell.ColumnIndex;
int linesCount = lines.Count();
if ((row + linesCount) - dgView.RowCount > 0) dgView.Rows.Add((row + linesCount) - dgView.RowCount);

asyncSqlResultsViewer.publicToolStripProgressBar.Maximum = linesCount;
asyncSqlResultsViewer.publicToolStripProgressBar.Step = 1;
asyncSqlResultsViewer.publicToolStripProgressBar.Visible = true;
dgView.ReadOnly = true;

foreach (string line in lines)
{
    if (line.Length > 0)
    {
        string[] cells = line.Split('\t');
        for (int i = 0; i < cells.GetLength(0); ++i)
        {
            if (col + i < dgView.ColumnCount)
            {
                dgView[col + i, row].Value = cells[i];
            }
            else
            {
                break;
            }
        }
        row++;
    }
    else
    {
        break;
    }
    asyncSqlResultsViewer.publicToolStripProgressBar.PerformStep();
}

It is ridiculously slow. Pasting 500 rows with 5 columns takes about 30 seconds. Please take into consideration that there might be already data in the DataGridView and I don't necessarily want to override it (it all depends on the starting cell). So I don't know how could I use a DataTable and assign it as DataSource in case you had that idea.


texts: A PHP MVC controller to display a form and add an item to the database

texts:
I am creating a controller that will display a form and once the form has been submitted to store the item in the database. After the item has been stored the user will be redirected back to the main page of the site. I am calling this controller with:

require_once("../app/controller/AddController.php");
new AddController();

The AddController.php file looks like this:

<?php

class AddController {

    public function __construct(){

        //Display our form
        if (empty($_POST['category']) || empty($_POST['description'])){

            require_once("../app/view/AddView.php");
            new AddView(array('title' => "Add an Item"));

        }

        //Add our new item to the database
        else {

            require_once("../app/model/AddModel.php");
            $add = new AddModel($_POST);

            if ($add->success())
                $_SESSION['message']['success'] = "The item has been added.";
            else
                $_SESSION['message']['error'] = "There was a problem adding your item.";

            header("Location: /");
            exit;

        }
    }
}

My main question is whether it is bad practice to place everything in the __construct() method like this since it is not really instantiating any variables or if I should get rid of __construct() and create a different method. The main reason I was doing this was to eliminate the third line when calling this class:

require_once("../app/controller/AddController.php");
$add = new AddController();
$add->someFunction();


texts:
I have the following working code, but it is too slow because I have to run the same code for several files inside a folder. Please help me avoid the nested for loop or make it more efficient.
columnNames = {33:"boy", 24: "girl"}
events = [{1:"bo", 2: "irl"}, {1:"oy", 207: "gir"}, {1:"bboy", 2: "girly"}]

def create_game_data():
    columns = {}
    for column in columnNames.keys():
        columnValues = []
        for event in events:
            columnValues.append(columnNames[column]) if column in columnNames.keys() else columnValues.append("NA")
        columns[column] = columnValues
    return columns

Take note of the following.

columnNames is a dictionary of with 15 keys and pairs.
events is a list of dictionaries with 2000 items.
Every dictionary in the events list has 13 keys and pairs

My algorithm works in the following steps.

Loop through every list item in the events list (list of dictionaries) and append every value associated with the key from the outer for loop to the list called columnValues.

Replace the current key (from the outer for loop) with columnVales.
The desired output should be
{33: ['boy', 'boy', 'boy'], 24: ['girl', 'girl', 'girl']}


texts:
Users can have a Cookie called lang that contains either the value "default=1" (English) or "default=2" (French). This cookie is used to determine their preferred language. I have a function that needs to take the cookie and return the language has an Enum. If the cookie doesn't exist, I want to return English. I cannot change the cookie value.

Language enum:

  Public Enum Language
     Undefined = 0
     English = 1
     French = 2
  End Enum

Function:

  Public Function GetLangFromCookie() As Language
     If HttpContext.Current.Request.Cookies.Get("lang") IsNot Nothing Then
        Dim langCookie = HttpContext.Current.Request.Cookies.Get("lang").Value
        Return If(langCookie(langCookie.Length - 1) = "1", Language.English, Language.French)
     End If
     Return Language.English
  End Function

I feel like this is not efficient and not secure but I don't know how to improve it. Any suggestions?


texts:
I wrote an application that has a modular structure. Each module communicates with different remote servers. Time for execution of a task in each module varies. So communication should be asynchron.

Plus some restrictions like flexibility, scalability and so on are put.

So i decided to use CompletableFutures to build a composition of functions (monade), that modules execute.

Each module has its own FixedThreadPool und a public function, that create and sends back a CompletableFuture. Something like that:

private final ExecutorService executorService = Executors.newFixedThreadPool(10);

public CompletableFuture<String> function1(final String rawReport, final UUID id) {
     LOG.info("SEND a report for " + id);
     return CompletableFuture.supplyAsync(() -> run(rawReport, id), this.executorService);
}

private String run(final String rawReport, final UUID id) {
     // do something
}

The whole process through all modules is handled by ModuleChainHandler:

 public CompletableFuture<Result> handler(final RunnerJob job) {
        // @formatter:off
        return this.scanExecuterRegistry.function1(job).
                thenCompose(bArr -> this.module2.function2(bArr, job)).
                thenCompose(metrics -> this.module3.function3(metrics, job)).
                handle((vReport, throwable) -> {
                    if (vReport != null) {
                        this.module4.function4(vReport, job);
                        return builder().setResult(vReport).build();
                    } else {
                        return builder().setErrorMessage(throwable.getMessage()).build();
                    }
                });
        // @formatter:on
    }

The BIGGEST problem (at the beginning) was to add an error handling. Because you cant throw an exception directly out of a future. I had to create an object with two state (result and error). If a completable future completes exceptionally, will be one action executed and the result object has an error massage and an empty result.

There is no so much real examples in internet except some poor tutorials. So just interesting, if you do it in the same way.


texts:
This is my first ES6 & JSX React Component. It's just a simple counter with disabling/enabling buttons on certain conditions with notice.

I would like to know if this code is OK or if you could've done something another way. I want to avoid bad practices right from the beginning.

import React from 'react';

export default class Counter extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      number: 0,
    };

    this.decrement = this.decrement.bind(this);
    this.increment = this.increment.bind(this);
  }

  decrement() {
    this.setState({
      number: this.state.number - 1
    })
  }

  increment() {
    this.setState({
      number: this.state.number + 1
    })
  }

  disableIncrement() {
    if(this.state.number >= 10) {
      return true;
    } else {
      return false;
    }
  }

  disableDecrement() {
    if(this.state.number <= 0) {
      return true;
    } else {
      return false;
    }
  }

  notice() {
    if(this.disableIncrement()) {
      return 'You\'ve reached N° 10.';
    }
    if(this.disableDecrement()) {
      return 'You can\'t decrement. You\'re at N° 0';
    }
    return 'You can do both.';
  }

  render() {
    return(

{this.state.number}

        <button disabled={this.disableIncrement()} onClick={this.increment}>+</button>
        <button disabled={this.disableDecrement()} onClick={this.decrement}>-</button>

{this.notice()}

    )
  }
}


texts: Printing out a diamond with a user-inputted size

texts:
I made a program that prints out a diamond with n lines. n is equal to whatever the user inputted. I know I overuse the ternary or conditional operator, but in my opinion, it makes the code more compact, and since I am the only one reading my code, readability doesn't matter to me. My friend challenged me to write one of these programs in under 50 lines of code, so that is why I am cramming everything together.

#include <iostream>

int main() {

    int lineNum = 1, lines,  stars = 1, spaces = 0;

    std::cin >> lines;

    // if lines is even, split it equally, if not, split in half and add 1
    while (lineNum <= ((lines % 2 == 0) ? (lines / 2) : (lines / 2) + 1)) {

        for (int c = (((lines % 2 == 0) ? (lines / 2) : (lines / 2) + 1) - lineNum); c != 0; c--)
            std::cout << " ";

        for (int c = 0; c < stars; c++)
            std::cout << "*";

        std::cout << "\n";

        lineNum++;
        stars += 2;

    }

    stars = (lines % 2 == 0) ? stars - 2 : stars - 4;
    spaces = (lines % 2 == 0) ? spaces = 0 : spaces = 1;

    while (lineNum <= lines) {

        for (int c = 0; c < spaces; c++)
            std::cout << " ";

        for (int c = stars; c != 0; c--)
            std::cout << "*";

        std::cout << "\n";
        stars -= 2;
        spaces++;
        lineNum++;

    }

}


texts: Get typed results for examine indexer using Umbraco

texts:
Continuing on this question on Stack Overflow, I've found a working solution.

The case

The case I'll create is that I've got a lot of persons and a knows person get 0, 1 or multiple languages. The language can get 0, 1 or multiple MVPs. Inside the back office of Umbraco I've created two document types:

Person: with the first name, last name, photo and a (Obsolete) Multinode Treepicker for the known programming languages of that person.
Language: With the name and a piece of code.

The code

On the template of the language, I'll create a table with the language, the code sample and the MVPs.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage<ProgrammingLanguages>
@using EventCalendar.Website.Models;

@{
    Layout = "Master.cshtml";

    var searcher = ExamineManager.Instance.SearchProviderCollection["PersonsSearcher"];
    var searchCriteria = searcher.CreateSearchCriteria();
    var query = searchCriteria.Field("nodeTypeAlias", "person").Compile();
    var persons = searcher.Search(query);
}

        Name
        Output <samp>Hello World!</samp>
        MVP

    @foreach (ProgrammingLanguage lang in Model.Content.Children)
    {
        var res = persons.Where(x => x.Fields["knowledge"] != null && x.Fields["knowledge"].Split(',').Contains(lang.Id.ToString())); @* <-- instead of this *@

            @lang.PageTitle

@lang.HelloWorld

                    @foreach (var r in res)
                    {

@r.Fields["firstName"] @r.Fields["lastName"]

                    }

    }

knowledge is a comma separated string with the IDs of the language.

This outputs this:

Good to know

I've created an indexer and a searcher for the persons.

After building:

My questions

Is this code performance enough?
Can I use typed persons? I'll like to use this code below instead of the marked line.

var res = persons.Where(x => x.Knowledge != null && x.Knowledge.Contains(lang)));

Remark: I've written .Contains(lang) so I'll get an IEnumerable<Person>!


texts: Same function, variable parameters and types with lambda

texts:
In my current project, I find myself using Dispatcher.Invoke a lot. Before each call I test if the current dispatcher is the right one. I want to write a wrapper class like so:

class SafeRunner
{
    //From the thread we always need to run on
    public static System.Windows.Threading.Dispatcher disp;

    public static void Run<T>(Action<T> f, T arg)
    {
        if (disp != System.Windows.Threading.Dispatcher.CurrentDispatcher)
        {
            disp.Invoke(f, arg);
        }
        else
        {
            f(arg);
        }
    }
    public static void Run<T1, T2>(Action<T1,T2> f, T1 arg1, T2 arg2)
    {
        if (disp != System.Windows.Threading.Dispatcher.CurrentDispatcher)
        {
            disp.Invoke(f, arg1, arg2);
        }
        else
        {
            f(arg1, arg2);
        }
    }
    public static void Run<T1, T2, T3>(Action<T1,T2,T3> f, T1 arg1, T2 arg2, T3 arg3)
        {...}
    public static void Run<T1, T2, T3, T4>(Action<T1,T2,T3,T4> f, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
        {...}
}

And I can use it like this:

SafeRunner.Run<string,string>((a,b) => {
    doSomething(a,b);
    doSomethingElse(a);
    // Maybe a few more lines here
}, "Hello", "World");

This works, but doesn't feel right. Is there a better way?


texts:
Can someone please review my code and let me know if there are some bugs or possible improvements?

    /**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //return true if the root node is null or there is only root node.
    public boolean isBalanced(TreeNode root) {
        if (root == null || (root != null && root.left == null && root.right == null)) {
            return true;
        } else {
            int balancedRight = 0;
            int balancedLeft = 0;
            if (root.left != null) {
                balancedLeft = findHeight(root.left);
            }
            if (root.right != null) {
                balancedRight = findHeight(root.right);
            }

            return Math.abs(balancedLeft - balancedRight) <= 1 ? true : false;
        }

    }
//find the height of the tree
    public int findHeight(TreeNode root) {
        if (root == null) {
            return 0;
        } else if (root.left == null && root.right == null) {
            return 1;
        } else if (root.left == null && root.right != null) {
            return 1 + findHeight(root.right);
        } else if (root.left != null && root.right == null) {
            return 1 + findHeight(root.left);
        } else {
            return Math.max(1+findHeight(root.left), 1+findHeight(root.right));
        }
    }
}


texts: Interactive complete Brainfuck Interpreter

texts:
This is another Brainfuck interpreter in Python. I personaly think this is better than most of the other once you find online, because it keeps a bracket_map, which makes both [ and ] instant actions. The data array is a simple defaultdict(int), so it is infinite is size in both directions (which  maybe a bad decision?) I am open to all critics and hope that somebody can tell if this is realy as efficient as I think.

from collections import defaultdict
from msvcrt import getch

program = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."

def evaluate(sourcecode):
    bracket_map = {}
    stack = []
    for i, c in enumerate(sourcecode):
        if c == "[":
            stack.append(i)
        elif c == "]":
            s = stack.pop()
            bracket_map[s], bracket_map[i] = i, s
    assert not stack
    del stack
    data = defaultdict(int)
    data_index = 0
    program_index = 0
    while program_index < len(sourcecode):
        c = sourcecode[program_index]
        if c == "+":
            v = data[data_index] + 1
            if v > 255:
                v = 0
            data[data_index] = v
        elif c == "-":
            v = data[data_index] - 1
            if v < 0:
                v = 255
            data[data_index] = v
        elif c == ">":
            data_index += 1
        elif c == "<":
            data_index -= 1
        elif c == ".":
            print(chr(data[data_index]), end="")
        elif c == ",":
            data[data_index] = getch()[0]
        elif c == "[":
            if not data[data_index]:
                program_index = bracket_map[program_index]
        elif c == "]":
            if data[data_index]:
                program_index = bracket_map[program_index]
        program_index += 1

evaluate(program)

(if you are not on windows, you need an alternative for the getch function)


texts:
I wrote a little bash script that displays the transaction info in json:

#!/usr/bin/env bash
set -e
set -o errexit

function process_block() {
  date --rfc-3339=ns
  bhash=${1:-$(bitcoin-cli getbestblockhash)}
  block=$(bitcoin-cli getblock $bhash)
  pbhash=$(echo "$block" | jq -r .previousblockhash)
  height=$(echo "$block" | jq -r .height)
  echo "height: $height"
  nTx=$(echo "$block" | jq -r .nTx)
  echo "$nTx transactions"
  Tx=$(echo "$block" | jq -r .tx[])
  IFS=$'\n'
  for txhash in $Tx; do
    txjson=$(bitcoin-cli getrawtransaction $txhash 1 $bhash)
    addresses=$(echo "$txjson" | jq -r '.vout[].scriptPubKey | select(.type == "pubkeyhash") | .addresses | .[]')
    for a in $addresses; do
      if [[ $a == ${2} ]]; then
        echo "$txjson"
      fi
    done
  done
  process_block $pbhash ${2}
}

process_block "" ${1}

Can be used as:

./btc.sh 1...

I ran bitcoind in pruned mode to get a blockchain. I downloaded the latest snapshot like this:

aria2c http://utxosets.blob.core.windows.net/public/$(curl https://raw.githubusercontent.com/btcpayserver/btcpayserver-docker/master/contrib/FastSync/utxo-sets | grep -F mainnet | tail -n 1 | grep -Po utxo.*)

The only problem is that it is really slow.  It takes about a minute to process about 1k transactions.  Any advice how the things could be speed up?


texts: Entity Framework Core verify SaveChanges count

texts:
I am using ASP.NET Core 3.1 and have been assigned a task to verify the count of changes done using SaveChanges().
It is expected that the developer should know how many records will be changed before-hand when SaveChanges() will be called.
To implement it, I have created an extension method for DbContext called SaveChangesAndVerify(int expectedChangeCount) where I am using transaction and equating this parameter with the return value of SaveChanges().
If the values match, the transaction is committed and if it doesn't match, the transaction is rolled back.
Please check the code below and let me know if it would work and if there are any considerations that I need to make. Also, is there a better way to do this?
public static class DbContextExtensions
{
    public static int SaveChangesAndVerify(this DbContext context, int expectedChangeCount)
    {
        context.Database.BeginTransaction();
        var actualChangeCount = context.SaveChanges();
        if (actualChangeCount == expectedChangeCount)
        {
            context.Database.CommitTransaction();
            return actualChangeCount;
        }
        else
        {
            context.Database.RollbackTransaction();
            throw new DbUpdateException($"Expected count {expectedChangeCount} did not match actual count {actualChangeCount} while saving the changes.");
        }
    }

    public static async Task<int> SaveChangesAndVerifyAsync(this DbContext context, int expectedChangeCount, CancellationToken cancellationToken = default)
    {
        await context.Database.BeginTransactionAsync();
        var actualChangeCount = await context.SaveChangesAsync();
        if(actualChangeCount == expectedChangeCount)
        {
            context.Database.CommitTransaction();
            return actualChangeCount;
        }
        else
        {
            context.Database.RollbackTransaction();
            throw new DbUpdateException($"Expected count {expectedChangeCount} did not match actual count {actualChangeCount} while saving the changes.");
        }
    }
}

A sample usage would be like context.SaveChangesAndVerify(1) where a developer is expecting only 1 record to update.


texts: Use if/else/elif conditionals to write a basic Rock Paper Scissors game

texts:
I have the following code for the Rock, Paper, Scissor game. The code works fine in Python 2.7. Are there other more concise, more readable, or more pythonic ways of solving this problem in Python?

player1 = raw_input ("?")
player2 = raw_input ("?")

if (player1 == 'rock' and player2 == 'scissors'):
    print "Player 1 wins."

elif (player1 == 'rock' and player2 == 'rock'):
    print "Tie"

elif (player1 == 'scissors' and player2 == 'paper'):
    print "Player 1 wins."

elif (player2 == 'scissors' and player2 == 'scissors'):
    print "Tie"

elif (player1 == 'paper' and player2 == 'paper'):
    print "Tie"

elif (player1 == 'paper' and player2 == 'scissors'):
    print "Player 2 wins."

elif (player1 == 'rock'and player2 == 'paper'):
    print "Player 2 wins."

elif (player1 == 'paper' and player2 == 'rock'):
    print "Player 2 wins."

elif (player1 == 'scissors' and player2 == 'rock'):
    print "Player 2 wins."
else:
    print "This is not a valid object selection."


texts:
Hoping somebody has knowledge of the range based additions going into the standard. So they can point out all the things I need to add to make it compliant.
IterableStream.h
#include <iostream>
#include <iterator>

namespace ThorsAnvil::Util
{

template<typename T>
class IterableStream
{
    std::istream&      stream;
    public:
        IterableStream(std::istream& stream)
            : stream(stream)
        {}
        operator std::istream&()            {return stream;}

        std::istream_iterator<T> begin()    {return std::istream_iterator<T>(stream);}
        std::istream_iterator<T> end()      {return std::istream_iterator<T>();}
};

}

Example usage
#include "IterableStream.h"
#include <iostream>
#include <fstream>

namespace TaU = ThorsAnvil::Util;
int main()
{
    std::ifstream x("plop");

    for(auto const& y: TaU::IterableStream<int>(x)) {
        std::cout << y << "\n";
    }
}


texts: Finding a word with the most occurrences of a character

texts:
I am new to PHP development. So Kindly, review my code and guide me make it better/optimize. Currently, it works well with inputs that I have tried.

<?php
// Program to find the word in a sentence with maximum specific character count
// Example: "O Romeo, Romeo, wherefore art thou Romeo?”
// Solution: wherefore
// Explanation: Because "e" came three times
$content = file_get_contents($argv[1]); // Reading content of file
$max = 0;
$arr = explode(" ", $content); // entire array of strings with file contents
for($x =0; $x<count($arr); $x++) // looping through entire array
{
$array[$x] = str_split($arr[$x]); // converting each of the string into array
}
for($x = 0; $x < count($arr); $x++)
{
    $count = array_count_values($array[$x]);
    $curr_max = max($count);
    if($curr_max > $max)
    {
        $max = $curr_max;
        $word = $arr[$x];
    }
}
echo $word;
?>


texts: Idiomatic way to write proper F# (x)unit + fsunit tests?

texts:
I am writing some unit tests using XUnit in F# and I am wondering what is the most idiomatic way in the F# sense to write them.

Let's start a simple case:

BicValidationTests.fs:

module Rm.Bai.Domain.BicValidationTests
open Rm.Bai.Domain.BicValidation
open FsUnit
open Xunit

let shortValidBic    = "MYMB gb 2L"
let expectedShortBic = "MYMBGB2L"
let ok               = Result<string, ValidationError>.Ok
let error            = Result<string, ValidationError>.Error

[<Fact>]
let ``Short Bic should be valid when all rules are respected`` () =
    shortValidBic
    |> validateAndFormat
    |> should equal (ok expectedShortBic)

One thing I am not too sure is whether it is better to include directly the values knowing that there is nothing shared among different test functions right into the test functions, such as:

[<Fact>]
let ``Short Bic should be valid when all rules are respected`` () =
    "MYMB gb 2L"
    |> validateAndFormat
    |> should equal (ok "MYMBGB2L")

This seems to be even more so the case since the answer I got here
which seems to indicate that if you have several test files, you need to rely on declaring types / classes to contain let variables for things other than primitive types like number or strings.

For example:

let sepaCompliantBics = [
    "DSXLAD46";
    "KAOLADZOAQC";
    "GFDIATGN";
    "XHOCATENR1X";
    "IMITBEW1";
    "JYPPBEPW807";
    "AHODBGG2";
    "LTQJBGMRKKA";
    "LAHYHRDK";
    ...
]

[<Fact>]
let ``Bics should be valid with SEPA-compliant countries`` () =
    sepaCompliantBics
    |> List.map(fun bic -> (validateAndFormat bic, bic))
    |> List.iter(fun (validation, bic) -> validation |> should equal (ok bic))

sepaCompliantBics in the example above will be set to null if it happens to not be the first file in the test project.

The solutions are then:

type Tests() =
    let ok               = Result<string, ValidationError>.Ok
    let error            = Result<string, ValidationError>.Error

    let sepaCompliantBics = [
        "DSXLAD46";
        "KAOLADZOAQC";
        "GFDIATGN";
        "XHOCATENR1X";
        "IMITBEW1";
        "JYPPBEPW807";
        "AHODBGG2";
        "LTQJBGMRKKA";
        "LAHYHRDK";
        ...
    ]

    [<Fact>]
    let ``Bics should be valid with SEPA-compliant countries`` () =
        sepaCompliantBics
        |> List.map(fun bic -> (validateAndFormat bic, bic))
        |> List.iter(fun (validation, bic) -> validation |> should equal (ok bic))

or:

let getSepaCompliantBics() = [
        "DSXLAD46";
        "KAOLADZOAQC";
        "GFDIATGN";
        "XHOCATENR1X";
        "IMITBEW1";
        "JYPPBEPW807";
        "AHODBGG2";
        "LTQJBGMRKKA";
        "LAHYHRDK";
        ...
    ]

[<Fact>]
let ``Bics should be valid with SEPA-compliant countries`` () =
    getSepaCompliantBics()
    |> List.map(fun bic -> (validateAndFormat bic, bic))
    |> List.iter(fun (validation, bic) -> validation |> should equal (ok bic))

or again:

[<Fact>]
let ``Bics should be valid with SEPA-compliant countries`` () =
    [
        "DSXLAD46";
        "KAOLADZOAQC";
        "GFDIATGN";
        "XHOCATENR1X";
        "IMITBEW1";
        "JYPPBEPW807";
        "AHODBGG2";
        "LTQJBGMRKKA";
        "LAHYHRDK";
        ...
        // this can be a pretty long list btw
    ]
    |> List.map(fun bic -> (validateAndFormat bic, bic))
    |> List.iter(fun (validation, bic) -> validation |> should equal (ok bic))

So I am wondering if having a long list like the example above is problem if it is defined in the test function itself rather than said outside? Is it still an idiomatic way to write unit tests with F#?


texts: Web scraper for parsing names and email addresses from Yellowpage

texts:
I've written a script using python to parse the names and email addresses of different pizza shops in USA. I am very new in writing classes using python so I'm not very sure I didn't do anything wrong with it's design.

However, it serves the purpose scraping the required fields. Firstly, it scrapes all the links of different pizza shops then parses the links to the next page and finally tracking down the links of each pizza shops to it's main page to harvest the documents from there. I would be very happy if I could learn the way I could improve my class crawler.

Here is what I have tried with:

import requests

from lxml import html

class YellowPage:
    main_url = "https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=Los+Angeles%2C+CA"

    def __init__(self):
        self.links = [self.main_url]
        self.storage = []

    def crawl(self):

        for link in self.links :
            self.get_link(link)

    def get_link(self, link):

        print('Scraping Now: ' + link)
        url = "https://www.yellowpages.com"
        response = requests.get(link)
        tree = html.fromstring(response.text)

        #scraping links of each pizza shop
        for items in tree.xpath("//div[@class='info']"):
            link_page = items.xpath(".//a[@class='business-name'][not(@itemprop='name')]/@href")
            for page in link_page:
                if page and url + page not in self.links:
                    self.links += [url + page]

        #parsing the links to the next page
        next_page = tree.xpath("//div[@class='pagination']//li/a/@href")
        for nepage in next_page:
            if nepage and url + nepage not in self.links:
                self.links += [url + nepage]

        #going to the main page of each pizza shop and harvest the record
        for posts in tree.xpath("//*[@id='main-header']"):
            name = posts.xpath(".//div[@class='sales-info']/h1/text()")[0] if posts.xpath(".//div[@class='sales-info']/h1/text()") else ""
            email = posts.xpath(".//a[@class='email-business']/@href")[0] if posts.xpath(".//a[@class='email-business']/@href") else ""
            records = name, email
            self.storage.append(records)

    def __str__(self):
        return self.storage

crawler = YellowPage()
crawler.crawl()
for item in crawler.storage:
    print(item)

Btw, when I write the above code using function then i find that very speedy.


texts:
I am trying to implement smart pointers for our project.
We're using FreeRTOS which is written with a C API so it was quite a challenge to implement sending smart pointers around but somehow I managed it by combining casts, new calls (dont really like that..) move semantics and some other tricks.

On the surface it behaves as expected, but I want to be sure there is not any memory leak.
Furthermore, is there a way to use make_unique together with new? I have not really found a way yet.

Here is the code, it should work with an online C++ compiler (or use this link). It would be great if an expert could look over this. Maybe some things can be optimized, or maybe this code is not save at all and I just dont see it.

// Example program
#include <iostream>
#include <string>
#include <memory>
#include <cstring>

class DummyHelper {
public:
    DummyHelper(uint8_t someResource): someResource(someResource) {}

    virtual ~DummyHelper() {
       someResource = 0;
       std::cout << "Dtor called" << std::endl;
    }

    int getResource() {
       return someResource;
    }
private:
   int someResource = 0;
};

class CommandMessage {
public:
    CommandMessage() = default;
    virtual~ CommandMessage() {};

    void setParameter(uint64_t parameter) {
        memcpy(rawContent.data() + 4, &parameter, sizeof(parameter));
    }

    uint64_t getParameter() const {
       uint64_t param;
       memcpy(&param, rawContent.data() + 4, sizeof(param));
       return param;
    }

private:
    std::array<uint8_t, 12> rawContent;
};

void setTestMessage(CommandMessage *testMsg,
       uint8_t someResource) {
  auto unique_pptr = new std::unique_ptr<DummyHelper>(new DummyHelper(someResource));
  uint64_t test_ptr = reinterpret_cast<uint64_t>(unique_pptr);
  testMsg->setParameter(test_ptr);
}

std::unique_ptr<DummyHelper> getUniquePtr(
       CommandMessage *testMsg) {
   uint64_t raw_ptr = testMsg->getParameter();
   auto unique_pptr = reinterpret_cast<std::unique_ptr<DummyHelper>*>(raw_ptr);
   auto unique_ptr = std::move(*unique_pptr);
   delete unique_pptr;
   return unique_ptr;
}

int main()
{
  auto storagePtr = std::make_unique<DummyHelper>(42);
  CommandMessage testMessage;
  std::cout << "Setting message" << std::endl;
  setTestMessage(&testMessage, 42);
  // a message has been set and can be sent, e.g. via a message queue

  // in another class, the pointer is retrieved.
  auto unique_ptr = getUniquePtr(&testMessage);
  DummyHelper & test = *unique_ptr;
  std::cout << test.getResource() << std::endl;
  unique_ptr.reset();
}


texts: Tarjan's strongly connected component finding algorithm

texts:
Here is my code for Tarjan's strongly connected component algorithm. Please point out any bugs, performance/space (algorithm time/space complexity) optimization or code style issues.

from collections import defaultdict
class SccGraph:
    def __init__(self, vertex_size):
        self.out_neighbour = defaultdict(list)
        self.vertex = set()
        self.visited = set()
        self.index = defaultdict(int)
        self.low_index = defaultdict(int)
        self.global_index = 0
        self.visit_stack = []
        self.scc = []
    def add_edge(self, from_node, to_node):
        self.vertex.add(from_node)
        self.vertex.add(to_node)
        self.out_neighbour[from_node].append(to_node)
    def dfs_graph(self):
        for v in self.vertex:
            if v not in self.visited:
                self.dfs_node(v)
    def dfs_node(self, v):
        # for safe protection
        if v in self.visited:
            return
        self.index[v] = self.global_index
        self.low_index[v] = self.global_index
        self.global_index += 1
        self.visit_stack.append(v)
        self.visited.add(v)
        for n in self.out_neighbour[v]:
            if n not in self.visited:
                self.dfs_node(n)
                self.low_index[v] = min(self.low_index[v], self.low_index[n])
            elif n in self.visit_stack:
                self.low_index[v] = min(self.low_index[v], self.index[n])
        result = []
        if self.low_index[v] == self.index[v]:
            w = self.visit_stack.pop(-1)
            while w != v:
                result.append(w)
                w = self.visit_stack.pop(-1)
            result.append(v)
            self.scc.append(result)

if __name__ == "__main__":
    g = SccGraph(5)
    # setup a graph 1->2->3 and 3 -> 1 which forms a scc
    # setup another two edges 3->4 and 4->5
    g.add_edge(1,2)
    g.add_edge(2,3)
    g.add_edge(3,1)
    g.add_edge(3,4)
    g.add_edge(4,5)
    g.dfs_graph()
    print g.scc


texts: Dynamically changing available select options

texts:
I have the following code working here on JSFIDDLE:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

<input class="radio-button-selector" type="radio" name="account" id="opt1" value="opt1">Opt1
<input class="radio-button-selector" type="radio" name="account" id="opt2" value="opt2">Opt2

     <select id="term" name="term" class="form-control">
          <option value="0">Please select</option>
          <option value="6">6 months</option>
          <option value="9">9 months</option>
          <option value="10">10 months</option>
          <option value="12">12 months</option>
          <option value="18">18 months</option>
          <option value="24">24 months</option>
          <option value="30">30 months</option>
          <option value="36">36 months</option>
          <option value="42">42 months</option>
          <option value="48">48 months</option>
    </select>

Questions:

Any way to improve the jQuery code? I saw a lot of times what surprisingly elegant things can be done in JS
Any way to improve the html code?
I only use the class "input-button-selector" for the JavaScript, is this actually needed or could I select the radio buttons in a different way?

Note that this code won't work on IE 8/9/10 (jQuery is not loading)


texts:
For several of my pet projects, I have had to interpret and/or send JSON WebSocket or HTTP responses in Java. I did some research and picked the library GSON to use. In each project, I have implemented a custom deserializer in order to correctly interpret different packet types.

For example:

{"type": "set-name", "data":{"name":"daniel"}}
{"type": "set-timeperiod", "data":{"start":"2017-03-16", "end":"2017-03-17"}}

In this case I would use two classes, SetName and SetTimePeriod:

public class SetName implements Data {
    private String name;

    @Override
    public void handle(Foo foo) throws InvalidPacketException {
        if(name == null) throw new InvalidPacketException();
        foo.doThingWithName(name);
    }

    @Override
    public String getType() { return "set-name"; }
}

Foo represents any arbitrary resources, the packet might need to perform its function. The data interface is fairly straightforward:

public interface Data {
    void handle(Foo foo);
    String getType();
}

The Data objects are wrapped in a Packet representing the whole thing:

public void Packet {
    private String type;
    private Data data;

    public Packet(Data data) {
        this.data = data;
        type = data.getType();
    }

    public void handle(Foo foo) throws InvalidPacketException { data.handle(foo); }

    public Packet initData(Data data) {
        if(this.data != null) throw new IllegalStateException("Data already initialised.");
        this.data = data;
        return this;
    }
}

And finally, the packet would be converted from raw JSON to an instance of Packet using a custom Deserializer.

public class PacketDeserializer implements JsonDeserializer<Packet> {

    @Override
    public Packet deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        // Remove data object, GSON won't know what to turn it into.
        JsonObject dataObject = jsonObject.remove("data").getAsJsonObject();
        // Determine what type of data object we need.
        Class dataClass = typeToClass(jsonObject.get("type").getAsString());
        // Construct and return a Packet of the correct type.
        Data data = context.deserialize(dataObject, dataClass);
        return new Gson().fromJson(jsonObject, Packet.class).initData(data);
    }

    private Class<? extends Data> typeToClass(String type) throws JsonParseException {
        switch(type) {
            case("set-name"): return SetName.class;
            case("set-timeperiod"): return SetTimePeriod.class;
            default: throw new JsonParseException("Type " + type + " is invalid.");
        }
    }
}

This means GSON will now deserialize the object into a Packet and then call the handle() to do whatever needs to be done with that packet:

Packet packet = new GsonBuilder()
    .registerTypeAdapter(Packet.class, new PacketDeserializer())
    .create()
    .fromJson(message, Packet.class);
packet.handle(foo);

In addition, a Packet instance can be converted to JSON without the need for any custom serializer. Once this structure is built, it is very easy to add new packet types or to send/parse packets.

This seems like an elegant solution to me, but I have some concerns:

Is it actually efficient? Would it be much faster to parse the JSON directly?
I can end up with a lot of subclasses of Data which makes me feel like there could be a better way of doing it
If this is a good solution, would it be a good thing to use wherever I'm parsing JSON with some object with varying contents like data?

I came up with this solution years ago, when I was fairly new to programming and haven't changed it much at all, so I feel like I must be doing something wrong.


texts:
I am automating a login page. I am using the page object design pattern Selenium with Java. What should I improve on in my code?

package Pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage
{
    private WebDriver driver;

       @FindBy(id="userName")
       WebElement username;
       @FindBy(id="password")
       WebElement password;
       @FindBy(className="btn-info")
       WebElement button;
       public LoginPage(WebDriver driver)
       {
        //initialize elements
          PageFactory.initElements(driver, this);

       }
       public void set_username(String usern)
       {
        username.clear();
        username.sendKeys(usern);
       }
       public void set_password(String userp)
       {
        password.clear();
        password.sendKeys(userp);
       }
       public void click_button()
       {
        button.submit();
       }
}

package Test;
import org.testng.annotations.Test;

import Pages.LoginPage;
import org.testng.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class LoginTest
{
WebDriver driver;
@BeforeTest
public void setup()
{
    System.setProperty("webdriver.firefox.marionette","pathToGeckodriver");
    driver=new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://twhyderabad.github.io/demo_site/");
}
@Test(priority=5)
public void verify1()
{
    LoginPage login=new LoginPage(driver);
    login.set_username("admin");
    login.set_password("admin");
    login.click_button();
    Assert.assertTrue(driver.getPageSource().contains("Blog"));
}
@Test(priority=1)
public void verify2()
{
    LoginPage login=new LoginPage(driver);
    login.set_username("adm");
    login.set_password("admin");
    login.click_button();
    Assert.assertEquals(driver.findElement(By.xpath("//*[@id='errorMessage']")).getText(),"Wrong username or password!");
}
@Test(priority=2)
public void verify3()
{
    LoginPage login=new LoginPage(driver);
    login.set_username("admin");
    login.set_password("adm");
    login.click_button();
    Assert.assertEquals(driver.findElement(By.xpath("//*[@id='errorMessage']")).getText(),"Wrong username or password!");
}
@Test(priority=3)
public void verify4()
{
    LoginPage login=new LoginPage(driver);
    login.set_username("adm");
    login.set_password("adm");
    login.click_button();
    Assert.assertEquals(driver.findElement(By.xpath("//*[@id='errorMessage']")).getText(),"Wrong username or password!");
}
@Test(priority=4)
public void verify5()
{
    LoginPage login=new LoginPage(driver);
    login.set_username("");
    login.set_password("");
    login.click_button();
    Assert.assertEquals(driver.findElement(By.xpath("//*[@id='errorMessage']")).getText(),"Wrong username or password!");
}
@AfterTest
public void close()
{
    driver.close();
}
}


texts:
The following algorithm is meant to generate a password from a given set of characters, and a length. Is it biased or predictable in any way? And are graphemes the appropriate Unicode thing to use here, or should I be using Unicode Scalar Values, or just using raw bytes?

// cargo-deps: ring="0.9"

extern crate ring;

use ring::rand::{SystemRandom, SecureRandom};

fn pwgen(
    length: usize,
    chars: &[&str]
) -> String {
    if chars.len() > 256 {
        panic!("Alphabet too large.");
    }

    if chars.len() == 0 {
        panic!("Alphabet too small.");
    }

    let mut result = String::with_capacity(length);
    let mut bytes = vec![0; length];
    let mut complete = 0;

    // The largest multiple of `chars.len()` <= 256.
    // This is necessary to maintain uniformity.
    let bound = 256 - (256 % chars.len());

    while complete < length {
        if SystemRandom.fill(&mut bytes).is_err() {
            panic!("RNG error.");
        }

        for &byte in &bytes {
            let byte = byte as usize;
            if byte < bound {
                result.push_str(chars[byte % chars.len()]);

                complete += 1;
                if complete == length {
                    return result;
                }
            }
        }
    }

    result
}

fn main() {
    println!("{}", pwgen(24, &["←", "→", "↑", "↓"]))
}

Note: The code can be compiled with cargo-script and all error handling code has been replaced with panics to keep it short.


texts:
I am wondering if this is a safe and/or sensible way of going about doing the following task:

My problem is that I have a folder with loads of directories with names of form YYYY-MM-DD. They are from my camera. Each directory contains picture files. The problem is that the picture files are designated by just 4 digits like C4018.jpeg. Hence after a few days of shooting I will find myself with duplicate file names! My objective is then to just add the date of the containing folder to each file, which solves my problem.

Here is my current solution. I tested it so that it also doesn't keep adding the date each time I run the code - once the files have been renamed they are not renamed in the future.

Am I safe running this code? By safe, I mean I don't end up with a renaming catastrophe. Also, please feel free to comment on the efficiency and style of my code.

 import os
 import re
 rootdir = '/Volumes/Misc/Pictures/test/' #Location of video folders to rename

  # Regexp for YYYY-MM-DD or YYYY/MM/DD
  date_re = re.compile('\d{4}[-/]\d{2}[-/]\d{2}')
  subdirs = [subdir[0] for subdir in os.walk(rootdir)]

  for subdir in subdirs:
      match = date_re.findall(subdir)
      if match:
          os.chdir(subdir)
          for (_,_,files) in os.walk(os.getcwd()):
              for f in files:
                  match2 = date_re.findall(f)
                  if not match2:
                      new_name = match[0] + '-' + f
                      os.rename(f, new_name)
          os.chdir('..')


texts: Python Secure Implementation Of AES-256-CTR Using Cryptography.Hazmat

texts:
I've implemented a wrapper for AES 256 CTR mode using the cryptography.hazmat module, I am wondering if there are any vulnerabilities in my implementation, specifically about the counter and its encoding. Here is the code:

from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CTR
from cryptography.hazmat.backends import default_backend as backend
from base58 import b58encode,b58decode
import os

#AES Cipher Class
class AES_Cipher:
  #Initialise Class, Set Countner And Key
  def __init__(self,key):
    self.counter = 0
    self.key = key

    #AES 256 Requirement
    assert len(self.key) == 32

  #Encryption Function
  def encrypt(self,plain_text):
    plain_text = plain_text.encode()
    self.counter += 1
    cipher = Cipher(AES(self.key),CTR(self.padCounter()),backend())
    encryption_engine = cipher.encryptor()
    cipher_text = self.padCounter() + encryption_engine.update(plain_text) + encryption_engine.finalize()
    return b58encode(cipher_text)

  #Decryption Function
  def decrypt(self,cipher_text):
    cipher_text = b58decode(cipher_text)
    self.counter = cipher_text[:16]
    cipher = Cipher(AES(self.key),CTR(self.counter),backend())
    decryption_engine = cipher.decryptor()
    plain_text = decryption_engine.update(cipher_text[16:]) + decryption_engine.finalize()
    return plain_text.decode()

  #Pad The Counter Into 16 Bytes
  def padCounter(self):
    return bytes(str(self.counter).zfill(16),"ascii")

Usage:

    key = os.urandom(32)
    aes_engine = AES_Cipher(key)
    aes_engine.encrypt("hello world")
    aes_engine.decrypt(b"7WkHvZEJRr8yMEasvh3TESoW8nBTkEUNVu2Li")


texts: Changing the prototype of the String object

texts:
Are there any pitfalls in changing the prototype of the String object? I'd like to change the word substr to "left":

String.prototype.left = function(n) {
    return this.substr(0,n)
}

Is this ok, or should I just get over it?

Next, I'm going to write a .right(), a .mid(), a .val() and a .int().


texts:
I wrote some C++ code using the OpenCV library. The program reads the image and plot histograms of Red, Green, and Blue components. I am very new to OpenCV so I need comments and advice. What do you think about my code? Is there any better way to do that? Are there unnecessary parts in my code? Is there any part I should change?

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(){
    Mat image = imread("C:/image.jpg");
    int HistR[257] = {0};
    int HistG[257] = {0};
    int HistB[257] = {0};
    for (int i = 0; i < image.rows; i++)
        for (int j = 0; j < image.cols; j++)
        {
            Vec3b intensity = image.at<Vec3b>(Point(j, i));
            int Red = intensity.val[0];
            int Green = intensity.val[1];
            int Blue = intensity.val[2];
            HistR[Red] = HistR[Red]+1;
            HistB[Blue] = HistB[Blue]+1;
            HistG[Green] = HistG[Green]+1;
        }
    Mat HistPlotR (500, 256, CV_8UC3, Scalar(0, 0, 0));
    Mat HistPlotG (500, 256, CV_8UC3, Scalar(0, 0, 0));
    Mat HistPlotB (500, 256, CV_8UC3, Scalar(0, 0, 0));
    for (int i = 0; i < 256; i=i+2)
    {
        line(HistPlotR, Point(i, 500), Point(i, 500-HistR[i]), Scalar(0, 0, 255),1,8,0);
        line(HistPlotG, Point(i, 500), Point(i, 500-HistG[i]), Scalar(0, 255, 0),1,8,0);
        line(HistPlotB, Point(i, 500), Point(i, 500-HistB[i]), Scalar(255, 0, 0),1,8,0);
    }
    namedWindow("Red Histogram");
    namedWindow("Green Histogram");
    namedWindow("Blue Histogram");
    imshow("Red Histogram", HistPlotR);
    imshow("Green Histogram", HistPlotG);
    imshow("Blue Histogram", HistPlotB);
    waitKey(0);
    return 0;
}


texts: spyOn click events and check call function

texts:
I'm trying to write Jasmine tests and I need a review and some advice on spying on events and their behavior.

// my example source code
;(function () {
  var app = {

    exampleModuleName: {
      navigateTo: function () { /* do something */ }
    },

    navigation: {
      init: function () {
        this.routeHandler = this.handleRouteTo.bind(this);

        // bind all events
        this.bind();
      },
      bind: function () {
        $(document).on('click', '.js-route-to', this.routeHandler);
      },
      teardown: function () {
        $(document).off('click', this.routeHandler);
      },

      handleRouteTo: function (event) {
        event.preventDefault();
        this.routeTo($(event.currentTarget).data('target'));
      },

      routeTo: function (target) {
        var module = app[target];
        if (module && $.isFunction(module.navigateTo)) {
            module.navigateTo();
        }
      },
    }
  };
}());

And that is my uncompleted spec file.

// my test code
describe('App Navigation', function () {

  describe('initiation the navigation module', function() {

    it ('spy on behavior', function () {
        var spy = spyOn(app.navigation, 'init');
        app.navigation.init();
        expect(spy).toHaveBeenCalled();
    });

    // which tests are missing to be sure about well tested properties and methodes?
   });

  describe('test routeTo handler', function() {
    var nav = app.navigation;

    beforeEach(function () {
        this.routeHandler = nav.handleRouteTo.bind(this);
    });

    it ('should be defined', function () {
        expect(this.routeHandler).toBeDefined();
    });

    it ('click at a link', function () {
        var node = $('some text');

        expect(node.length).toBe(1);

        spyOn(nav, 'handleRouteTo');
        node.click();

        // why is it failed?
        expect(nav.handleRouteTo).toHaveBeenCalled();
    });

  });
});

Please take a look and let us talk about this example. I want to learn more about testing.