texts:
I have made a form in HTML and the form data should be send via email.
For that purpose I have created a PHP script.

I did read a lot about the importance of form validation in order to prevent hackers on using the form to redirect to different website and other malicious use.

Can someone please check if I secured the form from hackers attacks?

Form:

            <form method="post" action="send_form.php">

                    Full name:
                    <input type="text" class="form-control" id="input-name" name="full_name" placeholder="Name Surname" required>

                    Email address:
                    <input type="email" class="form-control" id="input-email" name="email" placeholder="email@domain.xy" required>

                    Wedding date:
                    <input type="text" class="form-control" id="input-date" name="date" placeholder="dd/mm/yyy" required>

                    Location:
                    <input type="text" class="form-control" id="input-location" name="location" placeholder="Town, restaurant">

                    <button type="submit" class="btn btn-primary" name="submit">Submit</button>

            </form>

<?php
// check if form was submited
if (isset($_POST['submit'])) {
    $name = test_input($_POST['full_name']);
    $emailFrom = test_input($_POST['email']);
    $date = test_input($_POST['date']);
    $location = test_input($_POST['location']);

    $emailTo = "xxx";
    $subject = "Form was submited at xxx by: ".$emailFrom;
    $txt = "
        name: $name \n
        email: $emailFrom \n
        date: $date \n
        location: $location";

    if (mail($emailTo, $subject, $txt)) {
        // return to the main page after form submited
        header("Location: xxx");
    }
}
// remove empty spaces and convert html characters
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>


texts:
Would you be kind to make me a code review? It would be nice to have some comments, whether you would have done something differently and so on.  I am not sure about the way I handle the exception.  Is there a better way?

@Transactional
public classServiceImpl implements Service {

    private static final Logger LOG = Logger.getLogger(HermesServiceImpl.class);

    @Autowired(required = true)
    private Client client;

    @Autowired
    private SubmissionDAO submissionDAO;

    @Autowired
    private SubmissionSender hrsQueueSender;

    @Transactional
    @Override
    public void registerDocument(String submissionId) {

        final long start = System.currentTimeMillis();
        final List<HermesItem> items = submissionDAO.getSubmissionItems(submissionId);
        RegistrationSummary regSummary = null;

        if (!items.isEmpty()) {
            final HrsDocumentBuilder builder = new HrsDocumentBuilder();
            final Date docDate = new Date();
            builder.setTitle(submissionId);
            builder.setDocumentDate(docDate);
            builder.setSentDate(docDate);
            builder.setMailType(HermesMailType.INTERNAL);

            /* Document is constructed, try to invoke Hermes - upload annexes and register document. */
            try {
                regSummary = client.registerDocument(builder.buildDocument());
            } catch (final ClientException e) {
                LOG.error("Unable to register document with Submission Id= [" + submissionId + "], " + e.getMessage());
            }
            if (regSummary != null) {
                final String hermesDocId = regSummary.getHermesDocumentId();
                /* Update the DB with the documentID received from Hermes. */
                final int update = submissionDAO.updateSubmission(submissionId, hermesDocId, SubmissionStatus.HRS_REGISTERED.name());

                if (update < 1) {
                LOG.error("update error");
                }
            } else {
                submissionDAO.updateSubmission(submissionId, null, SubmissionStatus.HRS_FAILED.name());
                hrsQueueSender.sendMesage(submissionId);
            }

        } else {
            LOG.error("Not found");
            submissionDAO.updateSubmission(submissionId, null, SubmissionStatus.ANNEXES_NOT_FOUND.name());
        }
    }
}


texts: Partial view for frequently used drop down lists

texts:
I have one input that is needed in many forms, so I created a partial view for that. In the partial view I query the database and generate a drop down list.

I just want to make sure, this is the best way to achieve this.

The partial view looks like this:

@model long?

@{
    var data = Utility.GetData();
}

@Html.DropDownListFor(m => m, new SelectList((System.Collections.IEnumerable)data, "Id", "Text"),
    new { @class = "form-control input-sm" })

And I'll use it like this:

@Html.EditorFor(x => x.LiIdPeriod, "Years")

I should note that this is a SPA and intranet application.


texts:
The program asks for a user to set the max number of the range. That number is used to set the max range of a randomly generated number. The program keeps track of the number of guesses. I have taken a couple classes recently on different programming languages. I wrote a Hi/Low program in C a while back and decided to convert it to Python 3. I would appreciate someone looking at the code of the program and give me feedback on what I did good/bad and ways that I could improve.

def tooHigh():
    guess = int(print("Your guess is too high, please try again: "))
    return guess

def tooLow():
    guess = int(print("Your guess is too low, please try again: "))
    return guess

def guessLoop(x):
    guess=x
    counter+=1
    if guess>gennum:
        guess = tooHigh()
    elif guess<gennum:
        guess = tooLow()
    elif guess==gennum:
        print("you guessed it!")
    return guess

import random
range=int(input("Please enter the maximum number of the range you would like to guess within: "))
gennum = random.randrange(range+1)
guess = int(input("Please enter a number within the range: "))
counter =1

if guess==gennum:
    print("Congrats, you guessed right on the first try!")

while not guess==gennum:
    loop(guess)

print("It took you",counter,"guesses to guess correctly.")


texts:
Yes, I realize there are many, many, many, many, many, prime generators on the Code Review SE. However, I have been unable to find any using this method for generating primes inside a vector, so I figure it should be covered.

Here's the C++ code:

long int primeCap = 1e10;
std::vector<long int> primes;
primes.push_back(2);
for(long int i = 2; i < primeCap; i++){
    bool isPrime = true;
    for(long int j = 0; primes[j] <= sqrt(i); j++){
        if(i % primes[j] == 0){
            isPrime = false;
            break;
        }
    }
    if(isPrime)
        primes.push_back(i);
}

This code takes a while to fill a vector with \$10^{10}\$ (or more, depending on how much is needed) primes. How can this code be improved for the generation primes?

Update: The issue described below was a nonissue, and was simply an error on my part, the part below can be ignored.

There may also be an issue where the very last item in the vector is set to \$2\$. I have not effectively verified this, but modifying the if(isPrime) statement to be:

if(isPrime){
    std::cout << i << '\n';
    primes.push_back(i);
}

Results in the last output being two. Once again, I have not effectively verified this, but it is something to note.


texts:
I was asked to complete this CodeStepByStep problem. Here's a quick summary:

  Write a function named count_even_digits that accepts two integers as
  parameters and returns the number of even-valued digits in the first
  number. An even-valued digit is either 0, 2, 4, 6, or 8. The second
  value represents how many digits the number has. The second value is
  guaranteed to match the number of digits in the first number.

  For example, the number 8546587 has four even digits (the two 8s, the
  4, and the 6), so the call count_even_digits(8346387, 7) should return
  4.

  You may assume that the values passed to your function are
  non-negative.

My implementation:

def count_even_digits(digit, nums):
    count = 0
    digits = str(digit)
    for i in range(nums):
        if int(digits[i]) % 2 == 0:
            count += 1

    return count

I'm looking for any feedback on my implementation, and how to make this code more efficient. It seems weird that I have to cast the num to a string, then look at each char, convert it to int, then determine if it's even. Having to cast (int => string => analyzing as char => int) seems unnecessary to me.


texts:
Here is the function which does exactly what is specified by its name:

sub runCmd_getStdoutStderrAndExitCode(@)
{
  my @cmd = @_;

  # fork a child
  my ($child_pid, $child_stdout, $child_stderr);
  eval
  {
    $child_pid = open3(\*STDIN, # is /dev/null when collectl is a daemon, UPDATE: can pass 'undef' here
                       $child_stdout,
                       $child_stderr,
                       @cmd);
  };
  if ($@ =~ /^open3:/)
  {
    syslog(LOG_ERR, 'Error in "%s" : %s', "@cmd", $@);
    return (undef, undef, -1);
  }

   # result buffers
  my $stdout = '';
  my $stderr = '';

  # read into result buffers avoid blocking
  my $selector = IO::Select->new();
  $selector->add($child_stdout, $child_stderr);
  while (my @ready = $selector->can_read(SOME_TIMEOUT_CONSTANT))
  {
    foreach my $fh (@ready) {
      my $target_buf = ($fh == $child_stdout)
                     ? \$stdout
                         : \$stderr;
      if (!sysread($fh, $$target_buf, 4096, length($$target_buf)))
      {
        $selector->remove($fh);
        close $fh;
      }
    }
  }
  close $_ for ($selector->handles());

  my $finished = waitpid($child_pid, WNOHANG);
  return ($stdout, $stderr, $?) if $finished;

  if (kill 'TERM' => $child_pid) {
    # hang until SIGTERM is processed then bury child process
    waitpid($child_pid, 0);
  } else {
    syslog(LOG_WARNING, 'Error sending TERM to child process "%s"', "@cmd");
  }
  return ($stdout, $stderr, -1);
}

After the script successfully completes its job and before Perl interpreter exits, I get this message in the terminal:

  stty: standard input: Bad file descriptor

It would be nice to have your opinion about the code correctness, and get a piece of advice about how to avoid that message, as a bonus.

UPDATE: The message mentioned gone away when I replaced '\*STDIN' arg with 'undef'.

Major update: It appears that this code is not functioning properly. It mixes stderr and stdout from child process, and returns everything back as stdout. I have no clue, why it is so, and I started looking towards replacing my own bicycle with IPC::Run.

UPDATE 2: Finally, here is valid and working replacement of aforementioned bicycle masterpiece. The only disadvantage, in my opition, is that IPC::Run is not part of standard Perl distribution:

sub _runCmd_getStdoutStderrAndExitCode(@)
{
  use IPC::Run qw(run timeout);

  my @cmd = @_;
  my ($out, $err, $ok);

  my @args = (\@cmd, \*STDIN, \$out, \$err);
  push @args, timeout(SOME_TIMEOUT_CONSTANT) if SOME_TIMEOUT_CONSTANT;
  eval{ $ok = run @args };
  if ($@)
  {
    return ($out, $err, -1);
  }
  else
  {
    return ($out, $err, ($ok? 0 : $?));
  }
}

Thanks for your comments!


texts:
I'm trying to solve a Hackerrank problem where you perform k array[n] rotations, and at the end, ask for m and print array[m]. My program is probably correct (it runs perfectly for most of tests, but some of them terminate due to timeout), but is inefficient and I don't know how to improve it.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n;
    int k;
    int q;
    scanf("%d %d %d",&n,&k,&q);
    int *a = malloc(sizeof(int) * n);
    int *b = malloc(sizeof(int) * n);
    for(int a_i = 0; a_i < n; a_i++){
       scanf("%d",&a[a_i]);
    }
    for(int i = 0; i < k; i++){
        b[0] = a[n-1];
        for(int a_i = 1; a_i < n; a_i++){
        b[a_i] = a[a_i-1];
        }
        for(int a_i = 0; a_i < n; a_i++) a[a_i] = b[a_i];
    }
    for(int a0 = 0; a0 < q; a0++){
    int m;
    scanf("%d",&m);
    printf("%d\n", b[m]);
    }
    return 0;
}


texts: Python OOP - Web App (Flask) - User registration class?

texts:
I am working on a simple CRUD app as a personal project using Flask. I am currently working on the user blueprint and trying to use as less as libraries as I could and no ORM (for learning purposes). On my blueprints, I have multiple folders including a user folder. I wrote 2 classes in blueprints/user/models.py:
User: represent a User entity
UserService : register and login (login is not present yet)

Does it make sense to have2 separate classes? I am actually thinking to move all of my User methods to the UserService class and just have a UserService class with setters and getters.

I am confused about is where and when to interact with the database. Should I do it directly on my route.py vs create a new class?

For instance, to add a new User to the database, my SQL should look more or less like this:
sql = "INSERT INTO users (email, password) VALUES (%s, %s)"
cursor = conn.cursor()
cursor.execute(sql, (email, password))
cursor.fetchall()
conn.commit()

blueprints/user/models.py
class UserService():
    def register_user(self,
                      email,
                      password,
                      registration_date,
                      active,
                      sign_in_count,
                      current_sign_in_on,
                      last_sign_in_on):
        new_user = User(email, password, registration_date, active, sign_in_count, current_sign_in_on, last_sign_in_on)
        return new_user.__str__()

class User():
    def __init__(self, email, password, registration_date, active, sign_in_count, current_sign_in_on, last_sign_in_on ):
        self.email = email
        self.password = password
        self.registration_date = registration_date
        self.active = active

        # Activity tracking
        self.sign_in_count = sign_in_count
        self.current_sign_in_on = current_sign_in_on
        self.last_sign_in_on = last_sign_in_on

    def desactivate_user(self):
        if self.active == False:
            print(f"User {self.email} is already inactive")
        self.active = False

    def reactive_user(self):
        if self.active == True:
            print(f"User {self.email} is already active")
        self.active = True

    def is_active(self):
        return self.active

    def update_activity_tracking(self, ip_address):
        self.sign_in_count += 1
        self.last_sign_in_on = self.current_sign_in_on
        self.current_sign_in_on = datetime.datetime.now()

    def update_password(self, new_password):
        self.password = get_hashed_password(new_password)

    def __str__(self):
        user_attributes = vars(self)
        return (', '.join("%s: %s" % item for item in user_attributes.items()))

blueprints/user/views.py
from flask import Blueprint, render_template, request, jsonify
from prepsmarter.extensions import conn #database connection variable

user = Blueprint('user', __name__, template_folder='templates')

@user.route('/register')
def login():
    return render_template('register.html')

@user.route('/new-user',methods = ['POST'])
def register_user():
   # where I am going to register a new user

extensions/Database.py
import pymysql

class Database:
    instance = None

    def __init__(self, host, user, password, db):
        self.host = host
        self.user = user
        self. password = password
        self.db = db

    def connect(self):
        try:
            conn = pymysql.connect(
                host = self.host,
                user = self.user,
                passwd = self.password,
                db = self.db
            )
            return conn
        except Exception as e:
            print(e)


texts: Tiny app to track working time on Jira tickets

texts:
I'm a .NET intern. For my project management we work with Jira and we have to track real working time on a ticket to log the work and compare it to the original estimate. For this purpose I have written a tiny WPF app that shows a timer, because I have difficulties to track the time manually.

I was just wanting to get some comments on my code for educational purpose and self-improvement.

Example

Code

using System;
using System.Windows;
using System.Windows.Threading;

namespace Timer
{public partial class MainWindow : Window
    {
        private int counter = 20000;
        private bool IsTimerPaused = false; // used to switch the text of the button (pause - resume) timer
        private bool IsTimerStarted = false;
        private readonly DispatcherTimer timer = new DispatcherTimer();
        private const int SECONDS_IN_MINUTE = 60;
        private const int SECONDS_IN_HOUR = 3600;

    public MainWindow()
    {
        InitializeComponent();
        StartButton.Click += StartTimer;
        ResetButton.Click += ResetTimer;
        PauseButton.Click += PauseTimer;
    }

    private void PauseTimer(object sender, RoutedEventArgs e)
    {
        if (!IsTimerPaused)
        {
            timer.IsEnabled = false;
            PauseButton.Content = "Resume";
        }
        else
        {
            timer.IsEnabled = true;
            PauseButton.Content = "Pause";
        }
        IsTimerPaused = !IsTimerPaused;
    }

    private void ResetTimer(object sender, RoutedEventArgs e)
    {
        timer.Stop();
        ToggleStartButton();
        counter = 0;
        DisplayTimer();
    }

    private void StartTimer(object sender, EventArgs e)
    {
        if (IsTimerStarted) return;

        ToggleStartButton();
        timer.Interval = new TimeSpan(0, 0, 0, 1);
        timer.Tick -= IncreaseCounter; // prevents double call when start has been pressed multiple times
        timer.Tick += IncreaseCounter;
        timer.Start();

    }

    private void ToggleStartButton()
    {
        StartButton.IsEnabled = !StartButton.IsEnabled;
        IsTimerStarted = !IsTimerStarted;
    }

    private void IncreaseCounter(object sender, EventArgs e)
    {
        counter++;
        DisplayTimer();
    }

    private void DisplayTimer()
    {
        string timeEllapsed;
        int seconds;
        int minutes;

        if (counter <= 60)
        {
            seconds = counter;
            timeEllapsed = seconds + "s";
        } else if (counter <= 3600)
        {
            minutes = counter / SECONDS_IN_MINUTE;
            seconds = counter % SECONDS_IN_MINUTE;
            timeEllapsed = minutes + "m " + seconds + "s";
        }
        else
        {
            var hours = counter / SECONDS_IN_HOUR;
            minutes = (counter - (hours * SECONDS_IN_HOUR)) / SECONDS_IN_MINUTE;
            seconds = ((counter - (hours * SECONDS_IN_HOUR)) - (minutes * SECONDS_IN_MINUTE)) % SECONDS_IN_MINUTE;
            timeEllapsed = hours + "h " + minutes + "m " + seconds + "s";
        }

        TimerTextBox.Text = timeEllapsed;
    }
}
}


texts: A simple program using branching to guess the answer

texts:
As a rookie to programming, i'm really excited about finishing my first program.

But I know I only learn by making mistakes and through constructive criticism.

I'm open to any feedback regarding my use of branching, and any way to "clean up" my code.

puts 'Hi! Pick a number between 0 and 10'
number = gets.chomp
puts 'Got it; your number is ' + number.to_s + ', right?'
check1 = gets.chomp

if
  check1 == 'yes'
  puts 'awesome. now double your number. What\'s your new number?'
else
  puts 'Oops. Either: A. I oopsie-daisied up or B. you\'re lying.'
end

number_doubled = gets.chomp
if
  number_doubled.to_i == number.to_i * 2
  puts 'cool. Now add 6. What\'s the new number?'
else
  puts 'Oopsie-daisies'
end

number_plus_6 = gets.chomp
if
  number_plus_6.to_i == number.to_i * 2 + 6
  puts 'cool; Now divide your new answer by 2; What\'s your new number?'
else
  puts 'Oopsie-daisies'
end

number_halved = gets.chomp
if
  number_halved.to_i == number_plus_6.to_i / 2
  puts 'cool. Now, if you subtract the number you originally picked, ' + number + ', you\'re answer will be 3. Is it?'
else
  puts 'Oopsie-daisies'
end

check2 = gets.chomp
if
  check2 == 'yes'
  puts 'See? I told you i was a smarty!!'
else
  puts 'hmm, i think you\'re bad at math'
end


texts: Find the shortest whole repetitive substring (part 2)

texts:
This is a continued improvement from discussion here (Find the shortest whole repetitive substring), since code has changed a lot dues to improvement, I post it here. Major smart ideas are from arvindpdmn.

Major algorithm ideas,

since we need to find wholly repetitive sub-strings, we only build Trie tree if the sub-string length is a factor of total string length (if not a factor, such sub-string are not eligible dues to not able to wholly repetitive)
If wholly repetitive, all nodes need to have only one child node. I did the checking in method checkChildNumber.

Questions,

Trie tree is the best way I can think of to resolve this problem for the purpose of reducing algorithm time complexity, not sure if any other better ideas to make it even faster (in terms of algorithm time complexity perspective).

from __future__ import print_function
from collections import defaultdict

class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.isEnd = False
    def addNode(self, word):
        node = self
        for ch in word:
            node = node.children[ch]
        node.isEnd = True
    def checkChildNumber(self):
        node = self
        while node.isEnd == False:
            if len(node.children) != 1:
                return False
            for child in node.children.values():
                node = child
        return True

if __name__ == "__main__":
    word = "catcatcat" # output is 3
    #word = "aaaaaaa" # output is 1
    #word = "aaaaaab" # output is 7
    result = len(word)
    for subLength in range(1, len(word)//2 + 1):
        if len(word) % subLength == 0:
            start = 0
            root = TrieNode()
            while start <= len(word) - subLength:
                root.addNode(word[start:start+subLength])
                start += subLength
            if root.checkChildNumber():
                result = min(result, subLength)

    print (result)


texts: Verifying boardgame mathematics with MATLAB

texts:
I recently bought this math-based boardgame for my little cousins, and am now trying to verify its design with some MATLAB code. The relevant parts of the game are:

A board with numbers from 1 to 100 in one tile each, and each tile colored in one of nine colors
There are three dice, the usual kind  (1-6)
In your turn, you roll all three dice. You have three numbers x, y and z now, from the dice. Now, using these three numbers, and applying the four basic math operations on them (+, -, *, /) in any order, you must arrive at one of the numbers on the board (i.e. from 1 to 100). The catch is, the resulting numbers have scores based on their color on the board, so that for eg. arriving at 13 or 26 (red tile) gives you a much higher score compared to arriving at 25 (pink). So if you die values are 5, 5, 1, you're much better off going with (5*5+1) = 26 than with (5*5*1) = 25. Choosing these operations right in each turn is the crux of the game.

Now, the part I had doubts about was the coloring of the tiles - were they really colored
according to the difficulty of arriving at them? That seemed easy enough to verify - find the frequency of occurrence of each number from 1 to 100 given three dice and four mathematical operations - and so that's what this MATLAB code attempts to do:

function freq = compute_freq

idx = 1;
for x = 1:6
    for y = 1:6
        two_die_combos = get_combos(x, y);
        for z = 1:6
            three_die_combos = get_combos(two_die_combos, z);

            valid_combos = three_die_combos(three_die_combos > 0 & ...
                                                three_die_combos <= 100 & ...
                                                (three_die_combos == floor(three_die_combos))); % only integer values
            all_combos(idx:idx + length(valid_combos) - 1) = valid_combos;
            idx = idx+length(valid_combos);
        end
    end
end
freq = tabulate(all_combos);

end

function combos = get_combos(a, b)

num_results = length(a) * 6 * length(b);
combos = zeros(1, num_results);
idx = 1;
for x = a
    for y = b
        combos(idx) = x + y;
        combos(idx + 1) = x - y;
        combos(idx + 2) = -x + y;
        combos(idx + 3) = x * y;
        combos(idx + 4) = x / y;
        combos(idx + 5) = x \ y;
        idx = idx + 6;
    end
end

end

I get some frequency values from this, but:

first of all, I have no way of verifying the correctness of results themselves, so I would like to know if there are any logical errors in the code
secondly, I'd love feedback on the quality of the code itself. Loops within loops make me feel icky, but there doesn't seem to be any other reasonable way of doing this (one other option that occurred to me was having character arrays like ['1' '2' '3' '4' '5' '6'] and ['+' '-' '*' '/'], using MATLAB's permutation functions to get all possible expressions and then eval them, but that has complications with commutativity and order, and also... eval!). Am I missing some other better option?


texts:
I'm trying to make a small parabola calculator just for fun. Is this code good?

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

#define _X_UNTIL_Y(q,w)          \
    while (argv[1][q] != w) {    \
        q++;                     \
    }

#define _ATOI(s,d,f,g)           \
    strncpy(s, argv[1]+f, g);    \
    d = atoi(s)

int main(int argc, char const *argv[]) {
    int i=0, j, l;
    float D, a=1, b=1, c=1, r, k;
    char A[5], B[5], C[5], d;

    if(argv[1][0] == 'x');
    else{
        _X_UNTIL_Y(i,'x');
        _ATOI(A,a,0,i);
    }
    if(argv[1][0] == '-' && argv[1][1] == 'x') a=-1;

    j = i += 3;
    _X_UNTIL_Y(j,'x');
    if(argv[1][j-1] == '+' || argv[1][j-1] == '-');
    else{
        _ATOI(B,b,i,j);
    }
    if(argv[1][j-1] == '-') b=-b;

    l = j += 1;
    _X_UNTIL_Y(l,'=');
    _ATOI(C,c,j,l);

    D = pow(b,2)-4*a*c;

    if(D < 0){
        d = 'n';
        printf("Parabola doesn't have real roots.\n");
    }else if(D == 0){
        d = 's';
        printf("Parabola has one real root.\n");
    }else if(D > 0){
        d = 'p';
        printf("Parabola has two real roots.\n");
    }else
        return -1;

    r = -(b/(2*a));
    k = -(D/(4*a));

    a < 0 ? printf("Parabola look downwards.\n") : printf("Parabola look upwards.\n");
    printf("Vertex: %.1f,%.1f\n", r, k);
    printf("Axis of symmtery: %.1f\n", r);
    printf("y-intercept: %.1f\n", c);

    if(d=='n');
    else if(d=='s')
        printf("x-intercept: %.1f\n", r);
    else if(d=='p'){
        float x1, x2;
        x1=(-b + sqrt(D)) / (2*a);
        x2=(-b - sqrt(D)) / (2*a);
        printf("x-intercepts: %.1f, %.1f\n", x1, x2);
    }
    return 0;
}


texts:
I implemented a function for pager link creation, it looks like this:

function createPagerObject(pageUri, page, totPages) {

    const MAX_PAGES_IN_PAGER = 6;
    // for the first three pages the starting would be 1
    let pageNumber = Math.sign(page - 3) > 0 ? page - 3 : 1;

    let pager = [];
    for(let i = 0; i < MAX_PAGES_IN_PAGER; i++){
        pager.push({
            "page": pageNumber,
            "href": pageUri.replace("list-" + page, "list-" + pageNumber),
            "type": pageNumber == page ? "current" : pageNumber > page ? "next" : "prev"
        });
        pageNumber++;
        if(pageNumber > totPages) {
            break;
        }
    }

    return pager;
}

the code is self explanatory, but the idea is to create an Array of objects with the structure:

  page → the page number
  href → the link to the destination page
  type → "current", "next" or "prev" depending on the current page

having as input the current page URI, the current page number and the number of pages.

The question is "it could be improved", because it seems not so clean to me.


texts:
I want to implement a function that enumerates all files in directory. I think the function should

Return a Promise, because underlying readdir call is prefered over readdirSync.
Be a generator function, because checking statSync(...).isFile() might take some time and maybe, I will need only first few files...

So my attempt

import * as fs from 'fs';
import * as path from 'path';

function enumerateFiles(dir: string): Promise<IterableIterator<string>> {
    let result = function* (files: string[]): IterableIterator<string> {
        for (let enty of files) {
            let fullpath = path.join(dir, enty);

            if (fs.statSync(fullpath).isFile())
                yield fullpath;
        }
    };

    return new Promise<IterableIterator<string>>((resolve, reject) => {
        fs.readdir(dir, (err, files) => {
            if (err)
                reject(err);
            else
                resolve(result(files));
        });
    });
}

And usage

for (let file of await enumerateFiles(String.raw`C:\Windows\Web\Screen`))
    console.log(file);

// C:\Windows\Web\Screen\img100.jpg
// C:\Windows\Web\Screen\img101.jpg
// ...

What do you think? I'm really not sure about combining Promises with generator functions. Especially in this order...


texts: Create monthly calendar with number of days and offset (day of week) as user input

texts:
I am taking a beginning programming class and have been given the assignment to create a calendar as described in the title.  Per the assignment the user entering offset of 0 will begin the calendar on a monday and 6 will start on sunday.  There are to be 4 spaces per column and the request for input should prompt the user again if the given input isn't a valid option (ie more than 6 days or a month with less than 28 or more than 31 days).

The program works as written, what I am looking for is suggestions/critiques on ways that I might have done it better given what has been taught in the class so far.  It is early in the class, so far it has been limited to pretty much if/else and loops.

#include <iostream>

int getInputDays()
{
  int inputDays = 0;
  bool validInput = false; // used to verify input is valid
  while (validInput == false)
    {
      std::cout << "Number of Days: ";
      std::cin >> inputDays;
      // will call input valid if between 28 and 31 days
      if (inputDays >= 28 && inputDays <= 31)
    validInput = true;
    }
  return inputDays;
}

int getInputOffset()
{
  int inputOffset = 0;
  bool validInput = false; // used to verify input is valid
  while (validInput == false)
    {
      std::cout << "Offset: ";
      std::cin >> inputOffset;
      // will call input valid if between 0 and 6
      if (inputOffset >= 0 && inputOffset <= 6)
    validInput = true;
    }
  // convert offset from 0 being monday to 0 being sunday
  if (inputOffset == 6)
    inputOffset = 0;
  else
    inputOffset += 1;
  return inputOffset;
}

void displayOffset(int offset)
// used to create offset on the first line of calendar
{
  if (offset == 1)
    std::cout << "       1";
  else if (offset == 2)
    std::cout << "           1";
  else if (offset == 3)
    std::cout << "              1";
  else if (offset == 4)
    std::cout << "                   1";
  else if (offset == 5)
    std::cout << "                       1";
  else
    std::cout << "                           1";
}

void drawCalendar (int days, int offset)
{
  int date = 1;
  int spaces = 0; // used to keep track of location on each line
  std::cout << "  Su  Mo  Tu  We  Th  Fr  Sa"  << std::endl;  // calendar header
  while (date <= days)
    {
      if (offset > 0)  // for months starting on any date other than sunday
    {
      displayOffset(offset);
      date = 2;
      spaces = (offset * 4) + 4;
      offset = 0;
    }
      while (spaces < 28) // 28 spaces per line per assignment
    {
      if (date >= 10) // 2 spaces before double digit numbers
        {
          if (date > days)
        break;
          std::cout << "  " << date;
        }
      else            // 3 spaces before single digit numbers
        std::cout << "   " << date;
      date += 1;
      spaces += 4;
    }
      std::cout << std::endl;
      spaces = 0; // reset spaces to 0 at the end of each line
    }
}

int main()
{
  // prompt user to input days and offset per assignment
  int days = getInputDays();
  int offset = getInputOffset();
  // use input information to create calendar display
  drawCalendar(days, offset);
}


texts: Suspending and resuming threads for Azure bus service

texts:
I am new to thread programming in python. I am trying to read message from azure service bus, the message may or may not be present in the queue. So this is the logic I come up with

bus_service = ServiceBusService(
service_namespace='eventservice',
shared_access_key_name='key-name',
shared_access_key_value='password')

logger.info("Created bus_service object")

def service_bus_listner(callback):
    """thread worker function"""
    global currentBackOff
    logger.info('Started listening to service bus messages')
    current_thread = threading.currentThread()
    while True:
        msg = bus_service.receive_subscription_message('python-test', 'AllMessages', peek_lock=True)
        if msg.body is not None:
            currentBackOff = 0
            process_message(msg)
        else:
            if currentBackOff < maxBackOff:
                currentBackOff += 10

            logger.info("No message to process. Backing off for {0} seconds".format(currentBackOff))
            time.sleep(currentBackOff)

def process_message(msg):
    try:
        message = json.loads(msg.body.decode())
        message_id = message.get('Id')
        logger.info("Received message with id: %s" % message_id)
    except Exception as e:
        logger.exception(e)
    finally:
        msg.delete()

if __name__ == '__main__':
    thread = threading.Thread(target=service_bus_listner, args=(process_message, ))
    thread.start()

So if the message queue is empty service_bus_listner waits for some specified seconds (controlled by currentBackOff variable) and retry till it receives a message and the value of currentBackOff variable is set to 0. The function service_bus_listner is running in a separate thread.

I have gone through the documentation of time.sleep function here Time.sleep Document and it says that calling of this function Suspend execution of the current thread for the given number of seconds.

Does calling time.sleep in service_bus_listner functions free up the CPU for the specified time (in seconds).

I want to know the most ideal way(in terms of Memory and CPU utilization) of pausing and resuming a thread in python.


texts: Display data based on read configuration file from ssh sessions

texts:
I started playing with Python last week. This is a section of code from an application which reads a configuration file and launches ssh sessions and continuously displays data back to the local user.

The whole project is on Github.

def open_connections(sessions):
    """ open_connections(sessions)
    Opens ssh connections and forks them to the background. Passwords are sent
    from the user via STDIN to each process. If correctly identified, the
    process is successfully created and added to the Session object.
    """

    for server in sessions:
        usr = raw_input("Enter username for " + server.address + ": ")
        pwd = getpass.unix_getpass("Enter passphrase for " + server.address + ": ")
        con = paramiko.SSHClient()
        con.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        con.connect(server.address,
                    username=usr,
                    password=pwd)
        print "[OK]"
        server.connection = con

def run(sessions):
    """ run(sessions)
    Takes the file descriptors from the open sessions and runs the commands
    at the specified intervals. Display the STDOUT to the current tty.
    """

    while True:
        time.sleep(TIMEOUT)
        os.system("clear")
        for session in sessions:
            print session.command + " @ " + session.address
            print "------------------------------------------------------------"
            stdin, stdout, stderr = session.connection.exec_command(session.command)
            print format_stdout(stdout.readlines())

A couple of my concerns:

Am I doing any big Python no-nos?
Am I following proper comment/code conventions?
Is this the best way to display continuous information to user (screen refreshes)?

This is my first contact with Python so I'm definitely doing something I shouldn't be.  The rest of the code for this project is really only 1 file, and what I posted above is the bulk of it. If anyone went to the Github page and wanted to comment on something else, I'd be happy to respond.


texts: Project Euler, #4: Incorrect Results on 7-digit numbers

texts:
I've got my answer working (up until a 7-digit answer is requested, anyway), and would like some help

returning the correct answer
speeding up the results

I was thinking of storing the values of the possible palindromes before beginning my calculations, but I know it wouldn't speed things up anyhow. I've also read around that the 'divide by 11' trick isn't always reliable (see comment #2...900009 / 11 = 81819).

My code skims the top 10% of both the inner and outer loop before it decrements the outer loop by one, and repeats until the first result is found. This works fine, until the answer for 7-digit numbers is requested.

"""http://projecteuler.net/problem=4

Problem 4
16 November 2001

A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 * 99.

Find the largest palindrome made from the product of two 3-digit numbers.

"""

def main(n):
    """return the largest palindrome of products of `n` digit numbers"""
    strstart = "9" * n
    multic = int(strstart)
    multip = multic -1
    top = multic
    while multic > top * .9:
        while multip > multic * .9:
            multip -= 1
            if isPalin(multic * multip):
                return multic, multip, multic*multip
        multip = multic
        multic -= 1

def isPalin(n):
    n = str(n)
    leng = len(n)
    half = n[:leng/2]
    if n[leng/2:] == half[::-1]:
        return True
    return False

if __name__ == '__main__':
    main(3)

How's my approach here?


texts: Send multiple broadcast to multiple listeners

texts:
I want to send multiple broadcast to multiple listeners in go.

I can't send data through a channel, because only one listener will get it, except for the close signal (second "multiple" of my title).

However once a channel is closed, I can't send any other signal (first "multiple" of my title).

Hence I wrote the following code (explanation at the end of this post):

package main

import "sync"

// Broadcast allows to send a signal to all listeners
type Broadcast struct {
    lock sync.RWMutex
    ch   chan struct{}
}

// NewBroadcast creates a new broadcast
func NewBroadcast() *Broadcast {
    return &Broadcast{
        lock: sync.RWMutex{},
        ch:   make(chan struct{}),
    }
}

// Receive a channel on which the next (close) signal will be sent
func (b *Broadcast) Receive() <-chan struct{} {
    b.lock.RLock()
    defer b.lock.RUnlock()
    return b.ch
}

// Send a signal to all listeners
func (b *Broadcast) Send() {
    b.lock.Lock()
    defer b.lock.Unlock()
    close(b.ch)
    b.ch = make(chan struct{})
}

Usage example:

func main() {

    b := NewBroadcast()

    done := make(chan bool)
    quit := make(chan struct{})

    go func() {
        <-b.Receive()
        done <- true
    }()

    go func() {
        <-b.Receive()
        <-b.Receive()
        <-b.Receive()
        <-b.Receive()
        done <- true
    }()

    go func() {
        <-done
        <-done
        close(done)
        close(quit)
    }()

    func() {
        for {
            select {
            case <-quit:
                return
            case <-time.After(1 * time.Millisecond):
                b.Send()
            }
        }
    }()

}

I simply close the "current" channel to send a broadcast to all listeners and I create a new channel for the next Send. A ReadWriteMutex is added to prevent concurrency issues.

I would appreciate any comment regarding the code, the style and anything else!


texts: Project Euler #12 in Scala — Highly divisible triangular numbers

texts:
I generally work in Python for programming competitions, but I'm teaching myself Scala. As an exercise, I've attempted Project Euler problem #12 in Scala. I hope that somebody familiar with Scala can point out anything I'm doing which is not idiomatic in "functional style" Scala. My code produces the correct result, and is reasonably fast, so I'm mostly looking for coding style advice.

object HighlyDivisibleTriangularNumber {
  val triangleCache = collection.mutable.Map[Int, Int]()
  val triangle: Int => Int = {
    case 1 => 1
    case n => triangle(n - 1) + n
  }
  def cachedTriangle(n: Int) = triangleCache.getOrElseUpdate(n, triangle(n))

  def nFactors(x: Int): Int = {
    val maxFactor: Int = math.round(math.sqrt(x.floatValue).floatValue)
    val smallFactors: Set[Int] = (1 to maxFactor).filter(f => x % f == 0).toSet
    val allFactors: Set[Int] = smallFactors ++ smallFactors.map(f => x / f)
    allFactors.size
  }

  def main(args: Array[String]): Unit = {
    val triangleNumbers = Iterator.from(1).map(cachedTriangle)
    val firstWith500Factors = triangleNumbers.dropWhile(nFactors(_) < 500).next
    println(firstWith500Factors)
  }
}

I realize that a mutable collection is not a great starting point for functional Scala, but struggled to implement a memoized version of triangle without the mutable map.


texts:
Following my java class is required to be reviewed and couple of clarifications about class variable loading is required. Following is my class.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidateUtil{

    private static Pattern pattern;
    private static final String REFFERENCE_PATTERN = "The regex pattern here";

    public static boolean validate(final String reference){
    if(pattern ==null){
      pattern = Pattern.compile(REFFERENCE_PATTERN ); //Line 10
    }

      Matcher  matcher = pattern.matcher(reference);
      return matcher.matches();
    }

     /* Many util Methods here
      *
      */

}

There is only one method shown above, but there are many static utility methods are in this class. Based on the requirement, those methods are invoked.
In above class, variable pattern is declared, but not initialized. Instead, it is initialized inside the method validate(). The purpose of initializing so is to avoid initializing unnecessarily and initialize variables or create objects only if they are required and they are going to be used. That means, if it is defined

private static Pattern pattern = Pattern.compile(REFFERENCE_PATTERN );

as a class variable (not initialize inside the method), there will be a pattern object created whether the validate() method is used or not.  Actually, this is only one sample, there can be many situations like variables for supporting Object or array of Objects.

My question is that, is doing so is actually worth in a code ? This may lead to increase the line of codes and sometime, the performance gain can be neglectable (For our own custom objects). On the other hand, is this really worth only for heavy, large objects (like Database connections)?


texts:
I have a function which is supposed to replace all instances of variables (represented as NSStrings) from an NSDictionary with their corresponding values before calling another procedure. I ended up doing this with a simple for loop, though I suspect that there is a better way.  Do you have a suggestion how to do this differently?

+ (double)runProgram:(id)program usingVariables:(NSDictionary *)variables {
    NSMutableArray *stack;
    if ([program isKindOfClass:[NSArray class]]) {
        stack = [program mutableCopy];
        for (int i=0; i<stack.count; i++) {
            /* replace variable values with NSNumber values */
            NSNumber *variableValue = [variables valueForKey:[stack objectAtIndex:i]];
            if ([variableValue isKindOfClass:[NSNumber class]]) {
                [stack replaceObjectAtIndex:i withObject:variableValue];
            }
            /* all variables should be replaced now */
        }
    }
    return [self popOperandOffProgramStack:stack];
}


texts: Speeding up and fixing phone numbers from CSVs with Regex

texts:
I've hodgepodged together an attempt to extract all phone numbers from all CSVs in a directory, regardless of where they are and what format they're in.  I want all phone numbers to be printed to a compilation CSV with no repeat elements in the format 8885551234 with NO leading ones.  E.g., 1 (510) 533-2134 would become 5105332134, as would 510-5332134 (and the latter would count as a dupe and fail to be written).

My challenges are that the numbers are in different formats, in different columns (and sometimes in several columns), and that the files in the directory are, in total, many gigabytes in size.

What I came up with, first, fails to weed out numbers that start with 0 or 1 (though it does seem to "skip" the 1 in 11-digit numbers); second, I need checked by a regexpert to see if it is even doing what I want (identifying and printing phone numbers); and third, is far too slow:

import csv
import re
import glob
import string

with open('phonelist.csv', 'wb') as out:
    seen = set()
    output = []
    out_writer = csv.writer(out)
    csv_files = glob.glob('*.csv')
    #csv_files2 = glob.glob('*.csv')
    for filename in csv_files:
        with open(filename, 'rbU') as ifile:
            read = csv.reader(ifile)
            for row in read:
                for column in row:
                    s1 = column.strip()
                    result = re.match(
                        r'.*(\+?[2-9]?[0-9]?[0-9]?-?\(?[0-9][0-9][0-9]\)? ?[0-9][0-9][0-9]-?[0-9][0-9][0-9][0-9]).*', s1) or re.match(
                        r'.*(\+?[2-9]?[0-9]?[0-9]?-?\(?[0-9][0-9][0-9]\)?-?[0-9][0-9][0-9]-?[0-9][0-9][0-9][0-9]).*', s1)
                    if result:
                        tempStr = result.group(1)
                        for ch in ['(', ')', '-', ' ']:
                            tempStr = tempStr.replace(ch, '')
                        if tempStr not in seen:
                            seen.add(tempStr)
                            output.append(tempStr)
    for val in output:
        out_writer.writerow([val])


texts: Check that input is list of lists of coordinates

texts:
I have a factory method that should accept a list of coordinate lists, which are pairs of numbers, for example [[(2,4),(3,3),(2,4)],[(6,6),(7,6),(7,7),(6,7),(6,6)]]. I'd like to make sure the input is indeed in this format, but without specifying the types of sequences (might be lists, tuples, numpy arrays, and mixtures of those) or format of the numbers (int, float, etc., but no strings). So I wrote this checking method:

def _check_args(self,coords_features):
    """Check whether the input is a list of lists of pairs of numbers."""
    err = "Invalid input (not a list of coordinate lists): {}".format(coords_features)
    try:
        for coords in coords_features:
            for coord in coords:
                assert(len(coord) == 2)
                for f in coord:
                    1+f
    except (TypeError,AssertionError):
        raise ValueError(err)

Does this look "pythonic" and non-restrictive enough, or should I do anything differently?


texts:
I was reviewing the following code block and noticed there was validation check at the top.  The 3rd line in the function checks if the invoice belongs to the logged in customer.

I am wondering what the correct way of doing this might be.  Some options that come to me head are:

GetInvoice should take an overload and also take in the loggedInCustomerId.  The GetInvoice method would then throw an exception if it was an invalid call. (Would the business logic be the best place for this)
Filter attribute should be created (i think this is overkill)

What would the best approach to something like this be?

    public ActionResult ViewInvoice(Guid invnum)
    {
        int loggerInCustomerId = GetTheLoggedInCustomerId();
        Invoice invoice = _invoiceLogic.GetInvoice(invnum);

        if (invoice.CustomerId != loggerInCustomerId)
        {
            //Invalid Action
            return RedirectToAction("Index", "MyInvoices");
        }
        //do other stuff as normal
    }


texts: Enumerating RCData resources from the EXE file which has been launched

texts:
I am running Delphi XE6.

I recently integrated all of my read-only language INI files into the executables.

As a consequence, I need to enumerate RCData resources (and then simply filter out the languages).

I stumbled across solution, which I lightly changed into this form:

function EnumRCDataProc(hModule: HMODULE; lpszType, lpszName: PChar; lParam: NativeInt): BOOL; stdcall;
begin
  TStrings(lParam).Add(lpszName);
  Result := True;
end;

function EnumerateResourceNames: string;

var
  ExecutableHandle: HMODULE;
  ResourcesList: TStringList;

begin
  ExecutableHandle := LoadLibrary(PChar(Application.ExeName));
  try
    ResourcesList := TStringList.Create;
    try
      EnumResourceNames(ExecutableHandle, RT_RCDATA, @EnumRCDataProc, NativeInt(ResourcesList));
      Result := ResourcesList.Text;
    finally
      ResourcesList.Free;
    end;
  finally
    FreeLibrary(ExecutableHandle);
  end;
end;

It is indeed working. Do you see any possible problems?


texts: Sanity Checking an unordered_set of unique_ptrs to objects

texts:
I have a use case for a data store containing uniquely identified large objects where I can get partial updates over time. Each object can be identified by a 'key' consisting of a trio of values embedded in different parts of the structure of the object. Yes, this is terrible, and no, I can't change it.

I decided I wanted to use an unordered_set to store my objects because I did not want to have to extract the key to search in a map, and I have a distaste for multiple copies of data, in this case a separate key and the key data embedded in the object.

I have constructed a test case for my needs and it works exactly as I expected. But I am an old dog learning new tricks with respect to smart pointers and wanted some experienced eyes and minds to review it or point out pitfalls my basic test case won't trigger. So without further verbage:

#include <memory>
#include <string>
#include <unordered_set>
#include <list>
#include <iostream>

struct TestRecord
{
   std::string strVal;
   int intVal;
   int intVal2;
   std::string nonKeyStr;
};

using TestPtr = std::unique_ptr<TestRecord>;
using TestList = std::list<TestPtr>;

struct TestPtrHash
{
   std::size_t operator()(TestPtr const& s) const
   {
      if (!s)
      {
         return 0;
      }

      std::size_t h1 = std::hash<std::string>{}(s->strVal);
      std::size_t h2 = std::hash<int>{}(s->intVal);
      std::size_t h3 = std::hash<int>{}(s->intVal2);
      return h1 ^ (h2 << 1) ^ (h3 << 2);
   }
};

struct TestPtrEquals
{
   bool operator()(const TestPtr& lhs, const TestPtr& rhs) const
   {
      if (!lhs || !rhs)
      {
         return false;
      }

      if ((lhs->strVal == rhs->strVal) && (lhs->intVal == rhs->intVal) && (lhs->intVal2 == rhs->intVal2))
      {
         return true;
      }

      return false;
   }
};

using TestSet = std::unordered_set<TestPtr, TestPtrHash, TestPtrEquals>;

bool DoThings(const std::string context, const TestPtr& item)
{

   std::cout << context << ":" << item->strVal << " " << item->intVal << " " << item->intVal2 << " " << item->nonKeyStr << "\n";

   return true;
}

int main(int argc, char* argv[])
{
   TestList thisList;
   TestSet thisSet;

   thisList.emplace_back(new TestRecord{ "name", 1, 2, "Other" });
   thisList.emplace_back(new TestRecord{ "name2", 1, 2, "Less" });
   thisList.emplace_back(new TestRecord{ "name", 3, 2, "Is" });
   thisList.emplace_back(new TestRecord{ "name", 1, 5, "More" });
   thisList.emplace_back(new TestRecord{ "name2", 1, 2, "More" });

   while (!thisList.empty())
   {
      TestPtr finder(std::move(thisList.front()));
      thisList.pop_front();

      auto look = thisSet.find(finder);

      if (look != thisSet.end())
      {
         (*look)->nonKeyStr = finder->nonKeyStr;
         DoThings("replace",*look);
      }
      else
      {
         DoThings("new node",finder);
         thisSet.emplace(std::move(finder));
      }
   }

    return 0;
}


texts:
In my rails controllers,  I am consistently using this logic:

def report
  dump = params[:dump] ? params[:dump] : 'false'

  data = {}

  if dump != 'false'
    return render :json => p(data)
  end
end

Is there a better way to write this?  A ternary operation is just an eyesore.  I thought maybe just using the || operator:

dump = params[:dump] || false

But that doesn't yield the desired result.

How can I better write this?


texts: My solution to the 100 prisoners challenge

texts:
I stumbled across the 100 prisoners problem on Rosetta Code. I thought it would be fun to add a Common Lisp solution, see below.

Before I publish my solution I would like to have some feedback on my code. I have used lists for the task because I think it is most natural in CL and performance isn't an issue here.

Thanks for your comments!

(defparameter *samples* 10000)
(defparameter *prisoners* 100)
(defparameter *max-guesses* 50)

(defun range (n)
  "Returns a list from 0 to N."
  (loop
     for i below n
     collect i))

(defun nshuffle (list)
  "Returns a shuffled LIST."
  (loop
     for i from (length list) downto 2
     do (rotatef (nth (random i) list)
                 (nth (1- i) list)))
  list)

(defun build-drawers ()
  "Returns a list of shuffled drawers."
  (nshuffle (range *prisoners*)))

(defun strategy-1 (drawers p)
  "Returns T if P is found in DRAWERS under *MAX-GUESSES* using a random strategy."
  (loop
     for i below *max-guesses*
     thereis (= p (nth (random *prisoners*) drawers))))

(defun strategy-2 (drawers p)
  "Returns T if P is found in DRAWERS under *MAX-GUESSES* using an optimal strategy."
  (loop
     for i below *max-guesses*
     for j = p then (nth j drawers)
     thereis (= p (nth j drawers))))

(defun 100-prisoners-problem (strategy &aux (drawers (build-drawers)))
  "Returns T if all prisoners find their number using the given STRATEGY."
  (every (lambda (e) (eql T e))
         (mapcar (lambda (p) (funcall strategy drawers p)) (range *prisoners*))))

(defun sampling (strategy)
  (loop
     repeat *samples*
     for result = (100-prisoners-problem strategy)
     count result))

(defun compare-strategies ()
  (format t "Using a random strategy in ~4,2F % of the cases the prisoners are free.~%" (* (/ (sampling #'strategy-1) *samples*) 100))
  (format t "Using an optimal strategy in ~4,2F % of the cases the prisoners are free.~%" (* (/ (sampling #'strategy-2) *samples*) 100)))


texts: Loading files or directories based on type

texts:
I am building a config class for PHP which initially loads all given config files. To add files, users should be able to provide either a single file or a directory where files can be JSON or PHP.

Below is what I have so far, but it seems sluggish and inefficient to me. Is there a more elegant way to give users a wide choice of input? Should I split up the individual input cases into several private (or public?) methods? Are there any problems with this code apart from performance?

/**
* add function.
* merges the config data with another array
*
* @access public
* @param string|array $input  the data to add
* @return void
*/

public function add($input)
{
    // if we got a string, it can be either JSON, a filename or a folder path.
    if (is_string($input)) {

      // if we got a directory, add each file separately again (except . and ..).
      if (is_dir($input)) {
        if (! is_readable($input)) throw new \RuntimeException('Directory "' . $input . '" is not readable.');

        // add each file in a directory to the config
        foreach (array_diff(scandir($input), array('..', '.')) as $file) {
          $this->add(rtrim($input, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file);
        }
        return;
      }

      // if we got a filename, decide how to handle it based on the extension, then add its parsed content again
      if (is_file($input)) {
        if (! is_readable($input)) throw new \RuntimeException('File "' . $input . '" is not readable.');

        switch(pathinfo($input, PATHINFO_EXTENSION)) {
            case 'php':
              $content = require($input);
            break;

            case 'json':
              $content = $this->parseJSON(file_get_contents($input));
            break;
          }

        $this->add($content);
        return;
      }

      // string input is generally treated as JSON
      $this->add($this->parseJSON($input));
      return;
    }

    // if the input is an array, it must be plain config data, ready to merge in.
    if (is_array($input)) {
      $this->data = array_replace_recursive($this->data, $input);
      return;
    }

    // if we have no match, throw an exception (this happens if neither a string nor an array was given).
    throw new \RuntimeException('Provided data could not be parsed ("' . substr($input, 0, 20) . '...").');
    return;
}

To give a little context to the file extension switch: I used it to be able to implement more file extensions later on. I also thought about creating a parser interface for each type to be more expandable, that would prohibit further use of a single class file tho.

PHP config files consist of the following:

<?php return array(
  'foo' => 'bar'
);


texts:
Recently, I was given a math assignment to calculate Gini Indexes for a table of percent distributions of aggregate income.

The table takes the form of:

Year    1st Quintile    2nd Quintile    3rd Quintile    4th Quintile    5th Quintile
----    ------------    ------------    ------------    ------------    ------------
1929        0.03             12.47           13.8           19.3              54.4
1935        4.1              9.2             14.1           20.9              51.7
...         ...              ...             ...            ...               ...

Because of the length of the actual table I wrote a short python script to calculate the Gini Indexes. However, I'm fairly new to Python so I'd like to see what needs improvement.

Method of Calculation:

Calculate the log of the percentages with the quintile as the base of the logarithm (i.e. log(0.0003)/log(0.2), log(0.1247)/log(0.4) ...) and then average these values to find an approximate exponent for the Lorenz curve. Calculate the Gini Index by finding twice the area between y=x and the Lorenz curve from 0 to 1.

import numpy as np
import scipy.integrate as integrate
import itertools as it

def log_slope(x, y):
    return np.log(y)/np.log(x)

# read in data from file
years, data = read_values('Quintiles')  # shape: [[0.03, 0.12,...], [], []..., []]
accumulated_vals = [list(it.accumulate(v)) for v in data]

# percentiles; remove 0.0 and 1.0 after calculating
percentiles = np.linspace(0.0, 1.0, np.shape(accumulated_vals)[1] + 1)[1:-1]

for j, vals in enumerate(accumulated_vals):
    sum = 0
    for i, val in enumerate(vals[:-1]):  # exclude the last accumulated value, which should be 1.0
        sum += log_slope(percentiles[i], val)
    average = sum / (len(vals)-1)
    gini = 2 * integrate.quad(lambda x: x - pow(x, average), 0.0, 1.0)[0]
    print('{:d}: {} -> {:.5f}'.format(int(years[j]), [round(k, 4) for k in vals], gini))

Questions:

The code produces correct values and is already pretty quick, but can its speed be improved? At the moment I'd like to keep the method of calculation the same because it's the method used in my calculus course, but are there any possible improvements to this method?
Can the clarity of the code be improved? Are the variable names clear?
Does the code follow standard python conventions? I'm new to Python so I'm not familiar with these.
Minor Question/Bug: Printing the accumulated values will sometimes result in the last value being 1.00001 or 0.999 rather than 1.0. I presume this is due to precision errors, but it's seems odd when dealing with adding numbers with only 3 decimal places. Is there an easy fix for this?


texts: Thread safe Parameters class (follow up)

texts:
This is a follow up question to my previous question. I am trying to design a thread safe parameters class with only readable getters. Idea is it should be possible to initialize this class once with some parameters - and throughout app I should be able to query values. Deinitialization should also be possible.

Please find below. I am interested if this is thread safe or not, or how much thread safe it is?. This is my real code. Other code related feedback also welcome.

static class Parameters
{
  private static int connectionTimeout; // only getters of these will be visible to outside world
  private static int responseTimeout;
  private static bool isInit;
  private static readonly object Locker = new object();

  public static bool isInited()
  {
   lock(Locker)
    {
    return isInit;
    }
  }

  public static int ConnectionTimeout()
  {
    lock(Locker)
    {
    if(isInit == false) throw new Exception("init first");
    return connectionTimeout;
    }

  }

  public static int ResponseTimeout()
  {
    lock(Locker)
    {
    if(isInit == false) throw new Exception("init first");
    return responseTimeout;
    }

  }

  public static void init(int ct, int rt)
  {
    lock(Locker)
    {
      if(isInit) throw new Exception ("Already inited");
      isInit = true;
      connectionTimeout= ct;
      responseTimeout= rt;
    }
  }

  public static void Deinit()
  {

    lock(Locker)
    {
      if(!isInit) throw new Exception ("Already deinited");
      isInit = false;
      connectionTimeout= 0;
      responseTimeout= 0;
    }
  }

}


texts: Readability of JavaScript shorthand for converting strings to numbers with default value

texts:
This is perfectly readable code to me, but I'm afraid it may be too confusing to others.  What do you think?

Note that I'm not interested in validation of the input here (validation will happen long before we get to this line in the code), so assume it is blank or a valid non-negative integer.

It's modified from this Stack Overflow question.

var numberToAdd = parseInt($('#number-to-add').val()) || 500; // if a number is not provided, use 500


texts:
I've posted a similar program previously, but I have not made any major modifications in the code, so I am posting it again by deleting the previous question.

I am afraid of the thread keyword and I am not too familiar with threads and blocking, so can you please review this code for me?

Is the use of future enough or not?

This code comes from here.

Note: The AWS credentials are fake.

package controllers

import java.awt.image.BufferedImage
import java.util.ArrayList

import scala.collection.JavaConversions.mapAsJavaMap
import scala.concurrent.Future

import org.apache.http.NameValuePair
import org.apache.http.message.BasicNameValuePair

import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.services.s3.AmazonS3Client
import com.twilio.sdk.TwilioRestClient
import com.twilio.sdk.TwilioRestException

import net.liftweb.json.DefaultFormats
import net.liftweb.json.Serialization.write
import play.api.Play.current
import play.api.i18n.Lang
import play.api.i18n.Messages
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Action
import play.api.mvc.Controller

object Application extends Controller {

  val bucketImages = "images35"
  val bucketVideos = "videos35"
  val bucketAudios = "audios35"

  val AWS_ACCESS_KEY = "qqqqqqqqqqqqqqqqqqqqqqqqqqq"
  val AWS_SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"

  val yourAWSCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY)
  val amazonS3Client = new AmazonS3Client(yourAWSCredentials)

  val ACCOUNT_SID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  val AUTH_TOKEN = "tytytytytyyyyyyyyyyyyyyyyyyyyyyyyyy"

  implicit val formats = DefaultFormats

 def uploadVideo = Action.async(parse.multipartFormData) { implicit request =>
session.get("userI").map { userId =>
  try {
    var videoName: String = null
    val upload = for {
      done <- Future {
    request.body.files.map { mov =>
      videoName =System.currentTimeMillis() + ".mpeg"
      amazonS3Client.putObject(bucketVideos, videoName, mov.ref.file)
      }
      }
    } yield done
    upload.map { res =>
      val map = Map("result" -> "success", "videoName" -> videoName)
      Ok(write(map))
    }
  } catch {
    case e: Exception =>
      Future{
      Ok(write(Map("result" -> "error")))
      }
  }
}.getOrElse {
  Future{
  Ok(write(Map("result" -> "nosession")))
   }
  }
 }
}

application.conf

play {
  akka {
    event-handlers = ["akka.event.slf4j.Slf4jEventHandler"]
    loglevel = WARNING
    actor {
      default-dispatcher = {
        fork-join-executor {
          parallelism-min = 300
          parallelism-max = 300
        }
      }
    }
  }
}
contexts {
  simple-db-lookups {
    fork-join-executor {
      parallelism-factor = 10.0
    }
  }
  expensive-db-lookups {
    fork-join-executor {
      parallelism-max = 4
    }
  }
  db-write-operations {
    fork-join-executor {
      parallelism-factor = 2.0
    }
  }
  expensive-cpu-operations {
    fork-join-executor {
      parallelism-max = 2
    }
  }
}

Contexts Object

object Contexts {
  implicit val simpleDbLookups: ExecutionContext = Akka.system.dispatchers.lookup("contexts.simple-db-lookups")
  implicit val expensiveDbLookups: ExecutionContext = Akka.system.dispatchers.lookup("contexts.expensive-db-lookups")
  implicit val dbWriteOperations: ExecutionContext = Akka.system.dispatchers.lookup("contexts.db-write-operations")
  implicit val expensiveCpuOperations: ExecutionContext = Akka.system.dispatchers.lookup("contexts.expensive-cpu-operations")
}


texts:
In order to implement my own Dictionary<TKey, TValue> in VB6, I've implemented a KeyValuePair class, which can accomodate any type as its key, or value.
This KeyValuePair class implements the IComparable and IEquatable interfaces which I'm also using in this custom List<T> implementation

KeyValuePair.cls
Private Type tKeyValuePair
    Key As Variant
    value As Variant
End Type

Private this As tKeyValuePair
Implements IComparable
Implements IEquatable
Option Explicit

Private Function IsComparable() As Boolean
    IsComparable = Not IsObject(this.Key) Or TypeOf this.Key Is IComparable
End Function

Public Property Get Key() As Variant
    If IsObject(this.Key) Then
        Set Key = this.Key
    Else
        Key = this.Key
    End If
End Property

Public Property Let Key(k As Variant)
    If IsEmpty(k) Then Err.Raise 5
    this.Key = k
End Property

Public Property Set Key(k As Variant)
    If IsEmpty(k) Then Err.Raise 5
    Set this.Key = k
End Property

Public Property Get value() As Variant
    If IsObject(this.value) Then
        Set value = this.value
    Else
        value = this.value
    End If
End Property

Public Property Let value(v As Variant)
    this.value = v
End Property

Public Property Set value(v As Variant)
    Set this.value = v
End Property

Public Function ToString() As String
    ToString = TypeName(Me) & "<" & TypeName(this.Key) & ", " & TypeName(this.value) & ">"
End Function

Private Function IComparable_CompareTo(other As Variant) As Integer

    Dim kvp As KeyValuePair
    Set kvp = other

    IComparable_CompareTo = ToString = kvp.ToString
    If Not IComparable_CompareTo Then Exit Function

    If IsObject(kvp.Key) Then
        IComparable_CompareTo = CompareReferenceTypes(this.Key, kvp.Key)
    Else
        IComparable_CompareTo = CompareValueTypes(this.Key, kvp.Key)
    End If

End Function

Private Function IEquatable_Equals(other As Variant) As Boolean

    Dim kvp As KeyValuePair
    Set kvp = other

    IEquatable_Equals = ToString = kvp.ToString
    If Not IEquatable_Equals Then Exit Function

    If IsObject(kvp.Key) Then
        IEquatable_Equals = EquateReferenceTypes(this.Key, kvp.Key)
    Else
        IEquatable_Equals = EquateValueTypes(this.Key, kvp.Key)
    End If

End Function

Private Function EquateReferenceTypes(value As Variant, other As Variant) As Boolean

    Dim equatable As IEquatable
    If IsObject(this.Key) And TypeOf this.Key Is IEquatable Then

        Set equatable = value
        EquateReferenceTypes = equatable.Equals(other)

    Else

        Debug.Print "WARNING: Reference type doesn't implement IEquatable, using reference equality."
        EquateReferenceTypes = (ObjPtr(value) = ObjPtr(other))

    End If

End Function

Private Function EquateValueTypes(value As Variant, other As Variant) As Boolean

    EquateValueTypes = (value = other)

End Function

Private Function CompareReferenceTypes(value As Variant, other As Variant) As Integer

    Dim comparable As IComparable

    If IsComparable Then

        Set comparable = value
        CompareReferenceTypes = comparable.CompareTo(other)

    Else

        Err.Raise 9 'object required
        Exit Function

    End If

End Function

Private Function CompareValueTypes(value As Variant, other As Variant) As Integer

    If value < other Then

        CompareValueTypes = -1

    ElseIf value > other Then

        CompareValueTypes = 1

    End If

End Function

In C#, a KeyValuePair is a struct, a value type - this implementation being a class, makes it analoguous to a reference type, are there any major drawbacks to this? If so, are there any viable alternatives?


texts:
I've built a multiplexer which takes 2 inputs: one array of std_logic_vector and one std_logic_vector to select the correct array. It should be written more generic, but I'm not sure how. The length of SEL grows if the length of X grows (4-bit if 16 inputs, 6-bit if 64, etc.). I'm currently using custom types as input, but this makes making the code more generic problematic.

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

LIBRARY work;
USE work.type_arrays.ALL;

entity mux_16to1 is
    Port ( SEL : in  STD_LOGIC_VECTOR ( 3 downto 0);
           X   : in  A16_SLV16;
           Y   : out STD_LOGIC_VECTOR (15 downto 0));
end mux_16to1;

architecture sel of mux_16to1 is
begin
with SEL select
    Y <= X(0) when "0000",
         X(1) when "0001",
         X(2) when "0010",
         X(3) when "0011",
         X(4) when "0100",
         X(5) when "0101",
         X(6) when "0110",
         X(7) when "0111",
         X(8) when "1000",
         X(9) when "1001",
         X(10) when "1010",
         X(11) when "1011",
         X(12) when "1100",
         X(13) when "1101",
         X(14) when "1110",
         X(15) when "1111",
         "0000000000000000"  when others;
end sel;

With work.type_arrays consisting of:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

PACKAGE type_arrays IS
    SUBTYPE SLV16 IS std_logic_vector( 15 downto 0 );
    TYPE A16_SLV16 IS ARRAY ( 0 to 15 ) OF SLV16;
    TYPE A256_SLV16 IS ARRAY ( 0 to 255 ) OF SLV16;
END type_arrays;

Does anyone have a solution/idea to make it generic? I want to use this mux for 256*16-bit solutions and perhaps even 1024*24-bit as well. Writing the whole thing by hand can't be the VHDL way to do it.

The alternative is letting a generator write the code, but I'd like to prevent that if possible.


texts:
This is my first foray into OOP, so I'd appreciate any kind of advice!

Here is the problem description:

  On the first line of the input, you will receive a number specifying
  how many lines of input to read. After that, the input consists of
  some number of lines of text that you will read and determine whether
  or not it is a palindrome.

  The only important factor in validating palindromes is whether or not
  a sequence of letters is the same backwards and forwards. All other
  types of characters (spaces, punctuation, newlines, etc.) should be
  ignored, and whether a character is lower-case or upper-case is
  irrelevant.

Here is my code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("How many lines will you be entering? ");
        int numberOfLines = Int32.Parse(Console.ReadLine());
        string mergedLine = MergeMultipleLinesIntoOneLine(numberOfLines);
        bool isPalindrome = IsPalindrome(mergedLine);
        Console.WriteLine(isPalindrome ? "Palindrome" : "Not a palindrome");
    }

    public static string MergeMultipleLinesIntoOneLine(int numberOfLines)
    {
        int line = 1;
        var stringResult = new StringBuilder();
        do
        {
            Console.WriteLine("Please enter phrase #{0}: ", line);
            stringResult.Append(Console.ReadLine() + " ");
            line++;
        } while (line <= numberOfLines);

        return stringResult.ToString();
    }

    public static bool IsPalindrome(string someString)
    {
        string regexPattern = @"(?i)[^a-z]";
        string replacement = "";
        string amendedString = Regex.Replace(someString, regexPattern, replacement).ToLower();
        string reverseAmendedString = new string(amendedString.Reverse().ToArray());

        return amendedString.Equals(reverseAmendedString);
    }
}


texts: Random Number Generator from user touch input

texts:
I have this in place for an RSA Key generation class. I force the user to swipe on the screen randomly and use that as a entropy pool.

class TouchRandom extends SecureRandom {

    private final Stack<Byte> pool = new Stack<>();

    @Override
    public synchronized void nextBytes(byte[] bytes) {
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = pool.pop();
        }
    }

    void addToPool(byte b) {
        pool.push(b);
    }

}

And here is how I feed the pool:

@Override
public boolean onTouchEvent(MotionEvent event) {
    touchRandom.addToPool((byte) event.getX());
    touchRandom.addToPool((byte) event.getY());
    return false;
}

Is this better or worse than a PRNG based on a Elliptic Curve or something else?

(Idea shamelessly stolen from VeraCrypt.)


texts: Insert a table row with text in cells when a button is clicked

texts:
I made a function to dynamically create this table and a button with a function to display texts inside the table shown as a message.

<!DOCTYPE html>

Click the button to add a new row at the first position of the table and then add cells and content.

<button onclick="myFunction()">Try it</button>


texts: Greasemonkey script to refresh page until target string is found

texts:
I've been working on this user script to hunt for a specific string in an HTML webpage with the goal of finding the time at which it appeared.  This feels needlessly complicated and I would like advice on how too condense and upgrade the code to more simply find the time.

// ==UserScript==
// @name           Magma Time Finder
// @namespace      Will.GG
// @description    Refreshes the page until target string is found
// @include        *www.website.com
// @include http://www.website.com
// @grant metadata
// ==/UserScript==
var strHTML = document.body.innerHTML;
var yourTime = new Date();
var count = 1;
if(strHTML.indexOf("Text to find here") < 0){
  alert(yourTime);

} else {

  var lastCheck = document.createElement("div");
  lastCheck.innerHTML = "Last Check: " + yourTime.toString();
  console.log('Iteration: ' + count);
  count++;
  var parent = document.getElementsByClassName("content")[0];
  parent.insertBefore(lastCheck, parent.children[1]);

  window.setTimeout(function(){window.location.reload() ;},300000) ;

}
return;


texts: JavaScript implementation of Pascal's Triangle

texts:
I'm currently trying to teach myself JavaScript. If someone could critique my implementation of Pascal's Triangle I would be very grateful.

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Pascal's Triangle</title>

My code is also hosted on JSFiddle if anyone wants to see it in action.


texts: Routes requiring authentication in react

texts:
I'm looking for a way to do some route protection with react-router-4. Looking at an example in the documentation, they create a Component which is rendered like this:

<PrivateRoute path="/protected" component={Protected} />

and the privateRoute component:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

I don't really understand why I should want to pass the "Protected" component as a property and then have to take care of spreading all the ...props and ...rest.

Before I was reading this doc (and other example), I created the following code, which just nest the routes in another component which takes care of the authentication part.

Because my example (which seems to work perfectly well), looks way more simplistic, I must be missing something.

Are there any downsides on this approach?

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';

import Nav from './Nav';

// dummy
const Auth = {
  isAuthenticated: () => { return true; }
}

const Home = () =>
Home

const SignIn = () =>
SignIn

const About = () =>
About

class PrivateOne extends Component {
  render() {
    console.log(this.props);
    return
Private

  }
}
const PrivateTwo = () =>
PrivateTwo

const PrivateThree = () =>
PrivateThree

const NotFound = () =>
404

const Private = ({isAuthenticated, children}) => {
  return(
    isAuthenticated ? (

Private

        {children}

    ) : (
      <Redirect to={{
        pathname: '/sign_in',
      }}/>
    )
  )
}

const App = () =>

    <Router>

        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/sign_in" component={SignIn} />
          <Private isAuthenticated={Auth.isAuthenticated()}> {/* or some state later on */}
            <Route path="/private1" component={PrivateOne} />
            <Route path="/private2" component={PrivateTwo} />
            <Route path="/private3" component={PrivateThree} />
          </Private>
          <Route component={NotFound} />
        </Switch>

    </Router>

export default App;


texts: Rust echo implementation that supports command line options

texts:
I rewrote echo from the manpage to learn Rust, and got the following:

// echo in rust - display a line of text
use std::env;

static HELP: &'static str = "\
echo the STRING(s) to standard output.\n\
-n     do not output the trailing newline\n\
-e     enable intepretation of backslash escapes\n\
-E     disable intepretation of backslash escapes (default)\n\
--help display this help and exit

If -e is in effect, the following sequence are recognized:

  \\\\   backslash
  \\a   alert (BEL)
  \\b   backspace
  \\c   produce no futher output
  \\e   escape
  \\f   form feed
  \\n   new line
  \\r   carriage return
  \\t   horizontal tab
  \\v   vertical tab";

fn main() {
    let mut args: Vec<String> = env::args().skip(1).collect();

    let mut nl: bool = true; // the "-n" flag can be used to indicate no new line
    let mut escape: bool = false; // Disable interpreation of backslashes
    let mut args_count: usize = 0; // first argument is binary name

    for stuff in &args {
        if !stuff.starts_with("-") {
            break;
        }
        if stuff == "-n" {
            nl = false;
            args_count += 1;
        }
        if stuff == "-e" {
            escape = true;
            args_count += 1;
        }
        if stuff == "-E" {
            escape = false;
            args_count += 1;
        }
        if stuff == "--help" {
            println!("{}", HELP);
            return;
        }
    }

    if escape {
        for stuff in &mut args[args_count..] {
            *stuff = stuff.replace("\\\\", "\\"); // backslashe
            *stuff = stuff.replace("\\a", ""); // alert (BEL)
            *stuff = stuff.replace("\\b", ""); // backspace
            *stuff = stuff.replace("\\c", ""); // produce no further output
            *stuff = stuff.replace("\\e", ""); // escape
            *stuff = stuff.replace("\\f", ""); // form feed
            *stuff = stuff.replace("\\n", ""); // new line
            *stuff = stuff.replace("\\r", ""); // carriage return
            *stuff = stuff.replace("\\t", ""); // horizontal tab
            *stuff = stuff.replace("\\v", ""); // vertical tab
        }
    }

    print!("{}", args[args_count..].join(" "));
    if nl {
        println!();
    }
}

I then had a look at previously asked questions on this topic, and learnt of skip from here.

I would particularly welcome feedback on string manipulation, notably on the argument parsing (i.e. here, I expect known flags before data to echo), and the if escape block.

Could the argument parsing be converted to a match statement, whilst retaining the arg_count increment and the break condition?

Another thing I'm unsure of is that I'm first collecting args and then checking each element within the vector and eventually joining it, using a bunch of for loops.

Is there a more idiomatic way to do so, such as vector subtraction or...?

Lastly, my manpage for echo mentions support for decoding bytes:

\0NNN  byte with octal value NNN (1 to 3 digits)
\xHH   byte with hexadecimal value HH (1 to 2 digits)

Would you have pointers on how to do this type of operation?


texts: Simple bash script for opening a repository in the browser from the command line

texts:
I'm relatively new to bash scripting, and I'm wondering how I've done on this. Basically it's a script where if I'm in a github or bitbucket repository in my terminal, I can type browse-repository to open it up in the browser. I can also type something like browse-repository issues to visit the issues page, or browse-repository issues 19 to see issue # 19 for the repository.

I alias the command as br to save on typing, and can type things like br i 19 to get to the page for issue # 19.

I'm mainly looking for tips on organization and scope, and of course if there's any other improvements as well. I couldn't figure out any sort of namespacing, so i prefixed commands with _browse_repository

The file as it currently stands is simple sourced from my .bash_profile, if that matters.

#!/bin/bash -e

function browse-repository() {
  local URL="https://$(git config remote.origin.url | sed 's/\.git//' | sed 's/https:\/\///' | sed 's/ssh:\/\///' | sed 's/git:\/\///' | sed 's/git@//' | tr ':' '/')"

  if _browse_repository_is_bitbucket_repo "$URL" || _browse_repository_is_github_repo "$URL"
  then
    case "$1" in
      "")
        URL="$URL"
        _browse_repository_go
        ;;
      i|issues|-i|--issues)
        if [[ -n $2 ]]
        then
          if _browse_repository_is_bitbucket_repo "$URL"
          then
            URL="$URL/issue/$2"
          else
            URL="$URL/issues/$2"
          fi
        else
          URL="$URL/issues"
        fi
        _browse_repository_go
        ;;
      p|pulls|-p|--pulls)
        if _is_bitbucket_repo "$URL"
        then
          URL="$URL/pull-requests"
        else
          URL="$URL/pulls"
        fi
        _browse_repository_go
        ;;
      w|wiki|-w|--wiki)
        URL="$URL/wiki"
        _browse_repository_go
        ;;
      h|help|-h|--help)
        _browse_repository_usage
        ;;
      *)
        _browse_repository_usage
        ;;
    esac
  else
    case "$1" in
      h|help|-h|--help)
        _browse_repository_usage
        ;;
      *)
        echo "Not a valid bitbucket or github repository"
        ;;
    esac
  fi
}

_browse_repository_is_bitbucket_repo() {
  [ "$URL" != "${URL#https:\/\/bitbucket.org\/}" ]
}

_browse_repository_is_github_repo() {
  [ "$URL" != "${URL#https:\/\/github.com\/}" ]
}

_browse_repository_usage() {
  cat <<EOF
usage: browse-repository [<command>] [<number>]

The following commands are performed on the current project.

Available commands:

  -i --issues [<number>] Open issues, optionally pass a number to open a specific issue
  -p --pulls             Open pull requests, optionally pass a number to open a specific pull request
  -w --wiki              Open wiki

When no argument is supplied the main project page will be opened.
EOF
}

_browse_repository_go() {
  open "$URL"
}


texts: Printing element combinations that make a neutral compound

texts:
An array is given with the element name and their respective pH values. Print the combination of 2 elements which make a neutral compound

Here is the solution that I came up with but uses a Hashmap hence O(N) space complexity. Any idea I can reduce space complexity but maintaining O(N) time complexity

   public static void FindCombinationSuchThatPHValueIsNeutralized(PhValue[] input)
         {
             var map = new Dictionary<int, string>();
             foreach (var phValue in input)
             {
                 if (!map.ContainsKey(-phValue.Value))
                 {
                     map.Add(phValue.Value, phValue.Element);
                 }

                 else
                 {
                     Console.WriteLine(phValue.Element + "," + map[-phValue.Value]);
                     break;
                 }

             }

         }


texts: Dockerfile to install Python and React in Linux container

texts:
I am learning how to use Docker. I'm creating a container that contains Python and React. This code works, but it seems so heavy when I install it. I only want React, but to get React, I install Node so I can use npm later on. Do you see ways to optimize this? Or are there any red flags?

Dockerfile:

FROM python:3.6-slim

# first two are for python, last five are for node
RUN apt-get update && \
    apt-get install -qq -y build-essential libpq-dev --no-install-recommends && \
    apt-get install -y curl && \
    apt-get -y autoclean && \
    curl -sL https://deb.nodesource.com/setup_5.x | bash && \
    apt-get install -y nodejs && \
    apt-get autoremove -y

# install python components
ENV INSTALL_PATH /brainlint
RUN mkdir -p $INSTALL_PATH
WORKDIR $INSTALL_PATH
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
RUN pip3 install --editable .
CMD gunicorn -b 0.0.0.0:8000 --access-logfile - "brainlint.app:create_app()"

Requirements.txt:

Flask==0.12.2
gunicorn==19.7.1


texts:
I am doing a code review and I have encountered a class in an application that is throwing an exception in the constructor:

class QueueMessage
{
private:
    std::string m_bucketName;
    std::string m_objectName;

public:
    QueueMessage(const std::string& messageIn)
    {
        std::stringstream ss;
        ss << messageIn;
        PTree pt;
        json::read_json(ss, pt);
        m_bucketName = pt.get<std::string>("bucket");
        m_objectName = pt.get<std::string>("path");
        if (m_bucketName.empty() || m_objectName.empty())
        {
            throw QueueMessageException("Empty fields in queue message");
        }
    }

    std::string getBucketName() const { return m_bucketName; }
    std::string getObjectName() const { return m_objectName; }
};

The class is used to store the message from the queue (that is a JSON-like text) in its members.  Is it ok to throw an exception in the constructor if the members of the class are string, int, vector, smart pointers, etc.?


texts:
For a little background, I'm a contributor to SquishIt and decided that I should start cleaning up the mess of unit tests (my updated version of one set of tests vs. original set of tests). After tackling only part of the "rewrite", I figured it would be a good opportunity to learn, try, and understand BDD style testing to hopefully help improve the unit tests being written and ran. I decided to go with NSpec after taking a look at some of the choices out there.

My problem is simply trying to break the tests down into the appropriate "groupings" that logically make sense and "conform" to xSpec. Here is what I've done so far and passes all tests as expected:

using NSpec;
using SquishIt.Framework;
using SquishIt.Framework.JavaScript;

namespace SquishIt.Tests
{
    class describe_JavaScriptBundle : nspec
    {
        public JavaScriptBundle bundle;

        public void AddTest1JS()
        {
            bundle.Add("test.js");
        }
    }

    class when_I_create_a_bundle : describe_JavaScriptBundle
    {
        void before_each()
        {
            if (bundle == null)
            {
                bundle = Bundle.JavaScript();
            }
        }

        void and_add_no_files()
        {
            it["GroupBundles containskey default"] = () => bundle.GroupBundles.ContainsKey("default").is_true();
            it["has no Assets"] = () => bundle.GroupBundles["default"].Assets.Count.Is(0);
        }
    }

    class then_I_add_a_file : when_I_create_a_bundle
    {
        void before_each()
        {
            AddTest1JS();
        }

        void it_should_contain_only_one_file()
        {
            bundle.GroupBundles["default"].Assets.Count.Is(1);
        }
    }

    class then_I_add_the_same_file : then_I_add_a_file
    {
        void it_should_still_contain_only_one_file()
        {
            bundle.GroupBundles["default"].Assets.Count.Is(1);
        }
    }
}

How can I improve this or am I already on the right track?


texts:
As a follow up to my previous question I've improved the code + algorithm. The compression now works the following way:

Each character is followed by a length byte. The top 3 bits of that byte denote the number of additional length bytes which encode the count. The count is stored in "little endian order" (least significant byte first) with the first 5 bits being encoded in the initial length byte.

Some examples:

Count == 1  yields in length byte  00000001
Count == 31 yields in length byte  00011111
Count == 32 yields in length bytes 00100000 followed by 0000001
Count == 33 yields in length bytes 00100001 followed by 0000001

The program supports a command line option for printing the output in hex for easier reading and debugging. I tried to use a const int for the NUM_LENGTH_BITS as well but then the compiler claimed that the initializer element for MAX_COUNT isn't constant. Not sure if that can be worked around.

I've limited the max count to 61 bits to leave 3 bits for the length specifier and have a maximum of 8 bytes for the length output.

All types of feedback appreciated.

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#define NUM_LENGTH_BITS 3
static const uint64_t MAX_COUNT = (~0ULL) >> NUM_LENGTH_BITS;

static bool print_hex = false;

static int most_significant_bit(uint64_t value)
{
    int i = 0;
    while (value)
    {
        ++i;
        value >>= 1;
    }
    return i;
}

static int num_bytes_required(uint64_t value)
{
    int msb = most_significant_bit(value);
    int bytes = msb / 8;
    int remainder = msb % 8;
    if (remainder)
    {
        bytes += (remainder + NUM_LENGTH_BITS) > 8 ? 2 : 1;
    }
    return bytes;
}

void write_char(int c)
{
    if (print_hex)
    {
        if (printf("0x%x ", c) < 0)
        {
            perror("error printing to stdout");
            exit(EXIT_FAILURE);
        }
    }
    else
    {
        if (EOF == putchar(c) && ferror(stdout))
        {
            perror("error writing to stdout");
            exit(EXIT_FAILURE);
        }
    }
}

void write_count(uint64_t count)
{
    int additional_length_bytes = num_bytes_required(count) - 1;
    assert(additional_length_bytes >= 0 && additional_length_bytes < 8);

    int first = ((additional_length_bytes << 5) | (count & 0x1F)) & 0xFF;
    write_char(first);

    count >>= 5;

    while (count)
    {
        write_char(count & 0xFF);
        count >>= 8;
    }
}

static void parse_args(int argc, char **argv)
{
    if (argc == 2)
    {
        print_hex = (stricmp(argv[1], "-h") == 0 || stricmp(argv[1], "--hex") == 0);
    }
    else
    {
        printf("Invalid number of arguments passed: %d\n", argc - 1);
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char** argv)
{
    int current_char = 0;
    int previous_char = 0;
    uint64_t current_char_count = 0;

    parse_args(argc, argv);

    while (true)
    {
        current_char = getchar();
        if (current_char_count == 0 || current_char_count == MAX_COUNT || previous_char != current_char)
        {
            if (current_char_count > 0)
            {
                write_count(current_char_count);
            }
            if (EOF != current_char)
            {
                write_char(current_char);
                current_char_count = 1;
                previous_char = current_char;
            }
            else
            {
                break;
            }
        }
        else
        {
            current_char_count += 1;
        }
    }
}


texts: Rolling loop with an array of data points

texts:
I have a NumPy array of about 2500 data points. This function is called on a rolling basis where 363 data points is passed at a time.

def fcn(data):
    a = [data[i]/np.mean(data[i-2:i+1])-1 for i in range(len(data)-1, len(data)-362, -1)]
    return a

This takes about 5 seconds to run. I think the bottleneck is the list slicing. Any thoughts on how to speed this up?


texts: Integer-to-ASCII algorithm (x86 assembly)

texts:
This is my best effort at converting a 32 bit integer in EAX, to an 8 character ascii string (result in RDI).  It will work accurately up to 99,999,999.  Higher values could be done using an xmm register.  The byte order in RDI is correct (e.g. if copied directly to video ram, the most significant byte is displayed first)  No expensive DIV instructions or memory accesses required.  Can this be improved further?

    mov ebx, 0xCCCCCCCD
    xor rdi, rdi
.loop:
    mov ecx, eax                    ; save original number

    mul ebx                         ; divide by 10 using agner fog's 'magic number'
    shr edx, 3                      ;

    mov eax, edx                    ; store it back into eax

    lea edx, [edx*4 + edx]          ; multiply by 10
    lea edx, [edx*2 - '0']          ; and ascii it
    sub ecx, edx                    ; subtract from original number to get remainder

    shl rdi, 8                      ; shift in to least significant byte
    or rdi, rcx                     ;

    test eax, eax
    jnz .loop


texts:
I have crated the following small script.  I just need to improve this complicated code if possible.

def convUnixTime(t):
    expr_date = int(t) * 86400
    fmt = '%Y-%m-%d %H:%M:%S'
    d1 = datetime.date.today().strftime('%Y-%m-%d %H:%M:%S')
    d2 = datetime.datetime.fromtimestamp(int(expr_date)).strftime('%Y-%m-%d %H:%M:%S')
    d1 = datetime.datetime.strptime(d1, fmt)
    d2 = datetime.datetime.strptime(d2, fmt)
    return (d2-d1).days


texts: Navigate to three pages in parallel with Selenium, ChromeDriver, and NUnit

texts:
As an experiment, I've created an NUnit test project that should, when running all tests, open three browser windows simultaneously, and each should load a particular page before closing.

My question is:  Am I using the WebDriver and ChromeDriver APIs correctly, especially with regard to best practices?

First, I created an assembly-level SetUpFixture.  This creates a ChromeDriverService to be shared between IWebDriver instances.

using NUnit.Framework;
using OpenQA.Selenium.Chrome;

[SetUpFixture]
public class AssemblySetup
{
    private static ChromeDriverService _chromeDriverService;

    [OneTimeSetUp]
    public static void OneTimeSetUp()
    {
        _chromeDriverService = ChromeDriverService.CreateDefaultService();
        _chromeDriverService.Start();
    }

    [OneTimeTearDown]
    public static void OneTimeTearDown()
    {
        _chromeDriverService.Dispose();
    }

    public static ChromeDriverService ChromeDriverService
    {
        get { return _chromeDriverService; }
    }
}

Then I created a TestBase to encapsulate the IWebDriver set-up and teardown:

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace SeleniumSandbox
{
    public abstract class TestBase
    {
        private IWebDriver _webDriver;

        [SetUp]
        public void SetUp()
        {
            _webDriver = new RemoteWebDriver(AssemblySetup.ChromeDriverService.ServiceUrl, DesiredCapabilities.Chrome());
        }

        [TearDown]
        public void TearDown()
        {
            _webDriver.Quit();
        }

        public IWebDriver WebDriver
        {
            get { return _webDriver; }
        }
    }
}

Finally, I created the three tests:

using NUnit.Framework;

namespace SeleniumSandbox
{
    [TestFixture]
    [Parallelizable]
    public class TestA : TestBase
    {
        [Test]
        public void Run()
        {
            WebDriver.Navigate().GoToUrl("https://www.microsoft.com");
        }
    }

    [TestFixture]
    [Parallelizable]
    public class TestsB : TestBase
    {
        [Test]
        public void Run()
        {
            WebDriver.Navigate().GoToUrl("https://www.google.com");
        }
    }

    [TestFixture]
    [Parallelizable]
    public class TestsC : TestBase
    {
        [Test]
        public void Run()
        {
            WebDriver.Navigate().GoToUrl("https://www.amazon.com");
        }
    }
}

I'm concerned that I've deviated from the examples I've found.  For example, I'm not using ChromeDriverService like the example under "Controlling ChromeDriver's lifetime" here.  I also deviated from the many examples I can find, in which people instantiate IWebDriver with new ChromeDriver(service, options), because doing so caused additional ChromeDriver instances to start with port-related error messages.


texts: Writing strcat (string concatenate) in C

texts:
char *cat_string(char *to_cat, char *destination) {
  char *copy = destination;
  while (*copy != '\0') {
    *copy++;
  }
  while (*to_cat != '\0') {
    *copy++ = *to_cat++;
  }
  *copy = '\0';
  return destination;
}

I would like to know if this is an efficient and effective way of writing this function. It seems silly to have to iterate through the whole array just to find the \0 character.

Also, should I be returning the pointer to the destination? What's the best practice there?