texts:
This is my first go at a Perl script to (semi-) automate setting the correct IP settings. I use it to configure a virtual machine after creation. It's also my first Perl script as a whole, so I'm looking for anyone who can give me pointers towards a better and more efficient coding style.

#!/usr/bin/perl

use strict;
use warnings;

use Getopt::Long;
use Tie::File;

sub printMissingValues;
sub gatherInputValues;
sub setValueForField;

my %resulthash = (
    "IPADDR"  => undef,
    "NETMASK" => undef,
    "GATEWAY" => undef,
     "DNS1"    => undef,
     "DNS2"    => undef,
);

my $filename = undef;

GetOptions ("filename=s"  => \$filename,
    "IP=s"        => \$resulthash{'IPADDR'},
            "NETMASK=s"   => \$resulthash{'NETMASK'},
            "GATEWAY=s"   => \$resulthash{'GATEWAY'},
            "DNS1=s"      => \$resulthash{'DNS1'},
    "DNS2=s"      => \$resulthash{'DNS2'})

or die ("Error in input values");

#gatherInputValues(\%resulthash);

open(my $fd, '>>', "$filename")
    or die("Cannot open file $filename");

tie my @array, 'Tie::File',  $filename
    or die "Cannot tie file '$filename': $!";

for my $line (@array)
{
   my @fields = split /=/, $line;

    if ($fields[0] eq 'BOOTPROTO') {
         $fields[1] = '"static"';
        $line = join '=', @fields;
        }

    elsif ($fields[0] eq 'IPADDR' ) {
            $line = setValueForField('IPADDR', @fields);
    }

    elsif ($fields[0] eq 'NETMASK') {
            $line = setValueForField('NETMASK', @fields);
    }

    elsif ($fields[0] eq 'GATEWAY') {
            $line = setValueForField('GATEWAY', @fields);
    }

    elsif ($fields[0] eq 'DNS1') {
            $line = setValueForField('DNS1', @fields);
    }

    elsif ($fields[0] eq 'DNS2') {
            $line = setValueForField('DNS2', @fields);
    }
}

untie @array;

addMissingValues(\%resulthash);

close($fd);

##functions##

sub addMissingValues {
    my $hash = shift @_;

    while(my($key, $value) = each %{$hash}) {
        if (defined ($value)) {
            createNewField($key, $value);
        }
    }
}

 sub createNewField {
    my $key = shift @_;
    my $value = shift @_;
    print $fd (join '=', $key, $value);
    print $fd ("\n");
}

sub setValueForField {
    my $fieldname = shift;
    my @fields = shift;

    $fields[1] = $resulthash{$fieldname};

    return  (join '=', @fields);
}

sub gatherInputValues {

    my $result_hash = shift @_;

    print "IP4-address: ";
    $result_hash->{'IPADDR'} = <STDIN>;
    print "subnet-mask: ";
    $result_hash->{'NETMASK'} = <STDIN>;
    print "gateway: ";
    $result_hash->{'GATEWAY'} = <STDIN>;
    print "dns1: ";
    $result_hash->{'DNS1'} = <STDIN>;
    print "dns2: ";
    $result_hash->{'DNS2'} = <STDIN>;
}

This is the file the script operates on (standard configuration script for CentOS systems - /etc/sysconfig/network-scripts/ifcfg-etho)

TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="static"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="eth0"
UUID="7cabbc98-e67d-4a64-a132-7e8bcbeb579b"
DEVICE="eth0"
ONBOOT="yes


texts: Reduce repetition in Pandas DataFrame column assignments

texts:
Could the aggregate functions after using grouping functions like groupby() and resample() be looped for cleaner code

____DateTime.____    |  Steps  | day_segment
2017-10-25 00:00:00| 4  | night
2017-10-25 00:01:00| 7  | night
2017-10-25 00:02:00| 10 | night
2017-10-25 00:03:00| 26 | night
.
.
.
2017-10-25 10:04:00| 80 | morning
2017-10-25 10:05:00| 45 | morning
2017-10-25 10:06:00| 53 | morning

DataFrame: data

day_segments = ['morning','afternoon','evening','night']
#all_steps is a list input from the user
all_steps = ['sumallsteps','maxallsteps','minallsteps','avgallsteps','stdallsteps']
finalDataset = pd.DataFrame()

#Descriptive Statistics Features:
for day_segment in day_segments:
    resampledData = pd.DataFrame()
    resampledData = data.loc[data['day_segment'] == str(day_segment)]
    if("sumallsteps" in all_steps):
        finalDataset["step_" + str(day_segment) + "_sumallsteps"] = resampledData['steps'].resample('D').sum()

    if("maxallsteps" in all_steps):
        finalDataset["step_" + str(day_segment) + "_maxallsteps"] = resampledData['steps'].resample('D').max()

    if("minallsteps" in all_steps):
        finalDataset["step_" + str(day_segment) + "_minallsteps"] = resampledData['steps'].resample('D').min()

    if("avgallsteps" in all_steps):
        finalDataset["step_" + str(day_segment) + "_avgallsteps"] = resampledData['steps'].resample('D').mean()

    if("stdallsteps" in all_steps):
        finalDataset["step_" + str(day_segment) + "_stdallsteps"] = resampledData['steps'].resample('D').std()
    finaDataset.to_csv('data'+str(day_segment)+'.csv',index=True)

IS THERE A WAY TO MAKE THE 'IF' STATEMENTS AND ITS FUNCTIONS SHORTER? LOOP IT IN A DICTIONARY SOMEHOW?

There are more assignments like this in my code so I would want to know if there is a way I could just loop the aggregate functions


texts: JSON serializer using generics rather than System.Object

texts:
I recently created a custom static class in C# to encode, hopefully, any object it is given (or collection of objects), because I was, at the time, unaware of a native C# library that did the same thing. I am using Generics instead of System.Object because I am aware of the overhead that comes with boxing/unboxing.

After discovering System.Web.Helpers, which had to be installed via NuGet, I discovered their methods usually take in an object and Type, so I assume they're using boxing/unboxing:

public static dynamic Decode(string value);

public static T Decode<T>(string value);

public static dynamic Decode(string value, Type targetType);

public static string Encode(object value);

public static void Write(object value, TextWriter writer);

Here is my code:

public static string ToJson<U, T>(U arg) where U : IEnumerable<T>
{
    StringBuilder json = new StringBuilder();
    json.Append(@"{""data"" : [");

    foreach (var item in arg)
    {// iterate through the IEnumerable

        json.Append("{");
        foreach (var property in typeof(T).GetProperties())
        {// iterate over the properties of the class stored in the IEnumerable argument
            var value = property.GetValue(item, null).ToString();
            if (value == null)// make sure value is not null or empty
                json.AppendFormat(@"""{0}"": """",", property.Name);
            else
            {
                if (value.Contains("\r\n"))
                {// convert the new lines into an array of strings, to be joined when read
                    json.AppendFormat(@"""{0}"": [""{1}""],", property.Name,
                        value.Replace("\"", "\\\"").Replace("\r\n", @""","""));
                    // can be read back by join('\n');
                }
                else
                    json.AppendFormat(@"""{0}"": ""{1}"",", property.Name,
                        value.Replace("\"", "\\\""));
            }
        }
        // remove the trailing comma
        json.Remove(json.Length - 1, 1);
        json.Append("},");// add another row in the array (another dictionary)
    }

    if (json.Length > 11)
    {
        // remove the trailing comma
        json.Remove(json.Length - 1, 1);
        json.Append("]}");
    }
    else
        // no results from sql query:
        json.Replace("[", @"""none""}");

    return json.ToString();
}

Is there something that I'm missing out on, or is my code not optimal/pretty?


texts: Calculate your total happiness, which depends on the integers in the given sets

texts:
I am a beginner in programming. And I am learning python as my first language. I went on to do some challenges on HackerRank and stumbled upon this problem. The problem goes like this:

  There is an array of \$\ n \$ integers. There are also \$\ 2 \$
  disjoint sets , \$\ A \$ and \$\ B \$ each containing \$\ m \$
  integers. You like all the integers in set \$\ A \$ and dislike all
  the integers in set \$\ B \$. Your initial happiness is \$\ 0 \$. For
  each \$\ i \$ integer in the array, if \$\ i \in A\$, you add \$\ 1 \$
  to your happiness. If \$\ i \in B\$, you add \$\ -1\$ to your
  happiness. Otherwise, your happiness does not change. Output your
  final happiness at the end.

  Input Format  The first line contains integers \$\ n \$ and \$\ m \$ separated by a space.  The second line contains \$\ n \$
  integers, the elements of the array.  The third and fourth line
  contains \$\ m \$ integers, of \$\ A \$ and \$\ B \$
  respectively.

  Output Format  Output a single integer, your total happiness.

  Sample input  3 2 1 5 3 3 1 5 7
  Sample output 1

Here's my attempt at the answer. My code is working fine with small inputs but when the values of \$\ n \$ and \$\ m \$ are in millions, it gives a Terminated due to timeout :( error. Please help me out with time-efficient code that will execute within the time limits.

elems_count = input().split()
my_set = input().split()
happy_set = input().split()
sad_set = input().split()

happy = 0
for i in range(int(elems_count[0])):
    if my_set[i] in happy_set:
        happy = happy + 1
    else:
        happy = happy - 1
print(happy)


texts:
I have been building my data access layer and performance is key for the project I am working on.

I have chosen to use Dapper and dotnet core 3. I want to make use of the latest and greatest async features in dotnet core and Dapper to allow for smarter resource allocation under heavy load, however there is not much documentation out there.

All the dapper wrappers seem to be using non async and most examples I find for SqlConnection use non async methods.

I was wondering if the use of all async and await is worth the overhead.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Outible.API.Model;
using Outible.DataAccess.Interfaces;

namespace Outible.DataAccess.Models
{
    public class Db : IDb
    {
        private readonly IOptionsMonitor<ConnectionStrings> _connectionStrings;
        private readonly ILogger<Db> _logger;

        public Db(IOptionsMonitor<ConnectionStrings> connectionStrings, ILogger<Db> logger)
        {
            _connectionStrings = connectionStrings;
            _logger = logger;
        }

        private async Task<T> CommandAsync<T>(Func<IDbConnection, IDbTransaction, int, Task<T>> command)
        {
            var connection = new SqlConnection(_connectionStrings.CurrentValue.MainDatabase);
            await connection.OpenAsync().ConfigureAwait(false);
            await using var transaction = await connection.BeginTransactionAsync();
            try
            {
                var result = await command(connection, transaction, 300).ConfigureAwait(false);

                await transaction.CommitAsync().ConfigureAwait(false);

                return result;
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync().ConfigureAwait(false);
                _logger.LogError(ex, "Rolled back transaction");
                throw;
            }
        }

        public Task<int> ExecuteAsync(string sql, object parameters)
        {
            return CommandAsync((conn, trn, timeout) => conn.ExecuteAsync(sql, parameters, trn, timeout));
        }

        public Task<T> GetAsync<T>(string sql, object parameters)
        {
            return CommandAsync((conn, trn, timeout) => conn.QuerySingleOrDefaultAsync<T>(sql, parameters, trn, timeout));
        }

        public Task<IEnumerable<T>> SelectAsync<T>(string sql, object parameters)
        {
            return CommandAsync((conn, trn, timeout) => conn.QueryAsync<T>(sql, parameters, trn, timeout));
        }
    }
}


texts: compare different pandas dataframes to find matching rows

texts:
I have two dataframes: One contains of name and year.

**name** **year**

ram       1873

rob       1900

Second contains names and texts.

**name** **text**

ram      A good kid

ram     He was born on 1873

rob     He is tall

rob     He is 12 yrs old

rob     His father died at 1900

I want to find the indices of the rows of second dataframe where the name of second dataframe matches with name of the first df and the text in second df contains the year in first df.

The result should be indices 1,4

My Code:

ind_list = []
for ind1, old in enumerate(A.name):
    for ind2, new in enumerate(B.name):
        if A.name[ind1] == B.name[ind2]:
            if A.year[ind1] in B.text[ind2]:
                ind_list.append(ind2)

Any better way to write the above code?


texts: Optimal Implementation Choice for Producer-Consumer in Java

texts:
I am looking for an optimal producer-consumer implementation in Java with the following aspects:

Producer reads from server1 socket, and writes to a shared buffer, as well as another server 2 socket:

Server1 -> Server2 + shared buffer

Consumer reads from a shared buffer, and writes to server3 socket:

Shared Buffer -> Server3

Writes to shared buffer from Server 1 should be non-blocking (i.e. if the buffer is full it should not block the communication with Server 2).

I have considered the following options:

Java NIO Pipe
ConcurrentLinkedQueue<Byte> queue
PipedInputStream and PipedOutputStream
I assume buffer can have a pre-allocated memory to avoid dynamic memory allocation overhead? Or should that not be a concern? If so what would be a fast implementation.

What would be the fastest?
I have already tried out PipedInputStream and PipedOutputStream. My overhead compared to just forwarding data from server1->server2 was more than 12% this seemed excessive, which is why I came up with more options.
The specific part of the code already implemented, which is in the critical region (pertains to performance) is as follows in CommunicateToServerAndPipe:
 public void run() {
        try {
            String line = null;

            final byte[] request = new byte[1024];
            int bytesRead;

            //read from server 1 socket
            while (isRunning && (bytesRead = in.read(request)) != -1) {
                //write to server 2 socket
                out.write(request, 0, bytesRead);
                out.flush();
                //write to shared buffer pipe
                this.register.pos.write(request, 0, bytesRead);
            }
     register.kill();

    } catch (IOException ex) {
        if(ex instanceof SocketTimeoutException) {
            // The socket simply timed out. Kill, then exit.
            register.kill();
            return;
        }
        this.kill();
    }
}

I have made my initial code available here.


texts:
As an exercise, I have implemented a circular bounded queue using arrays as the base data structure. I'd appreciate it if someone can review it for me.

    class BoundedQueue<T> {

    T[] que;
    int head;       // remove from head
    int tail;       // insert at tail

    public BoundedQueue(int quesize)
    {
        head = tail = -1;
        que = new T[quesize];
    }

    public void enqueue(T elem)  // if next index to tail == head => Q is FULL
    {
        int newIndex = nextIndex(tail);
        if ( newIndex == head)
            throw new BoundedQueueException(Full);

        tail = newIndex;
        que[newIndex] = elem;
        if (head == -1)
            head = 0;
    }

    public T dequeue()  // After removing from head, if that was the only element in Q
    // Mark Q to be empty by setting head and tail to -1
    {
        if (head == -1)
            throw new BoundedQueueException(Empty);

        T elem = que[head];
        que[head] = default(T);

        if (head == tail)
        {
            head = tail = -1;
        }
        else
        {
            head = nextIndex(head);
        }

        return elem;
    }

    private int nextIndex(int index)
    {
        return (index + 1) % que.Length;
    }

}


texts: API POST to save a new item in a Database via PHP & MYSQLI

texts:
Is this correct MYSQLI implementation?
IS it safe from injection?
IS the object cleanup done properly?

<?php

include_once '../../securelogin/db_connect.php';
include_once '../../securelogin/functions.php';

sec_session_start();

if (login_check($mysqli) == true)
{
    $con = new mysqli("localhost", "username", "password", "databasename_todo");

    // Check connection
    if ($con->connect_errno)
    {
        echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
    }
    else
    {
        $jsonText = file_get_contents('php://input');
        $decodedText = html_entity_decode($jsonText);
        $myArray = json_decode('[' . $decodedText . ']', true);

        $newText = $myArray[0]['TEXT'];
        $newOwnerID = $myArray[0]['OWNER_ID'];
        $newCreateDate = date("Y-m-d");
        $newCompleted = 'N';

        $newText = mysqli_real_escape_string($con, $newText);

        if(!($sql = $con->prepare("INSERT INTO checklistitems (TEXT, OWNER_ID, COMPLETED, CREATE_DATE, CREATE_USER) VALUES (?,?,?,?,?)")))
        { echo "Prepare failed: (" . $con->errno . ") " . $con->error;}

        if(!$sql->bind_param('sissi', $newText, $newOwnerID, $newCompleted, $newCreateDate, $newOwnerID))
        {echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;}

        if(!$sql->execute())
        {echo "Execute failed: (" . $sql->errno . ") " . $sql->error;}

        echo "SUCCESS - Affected rows ADD: " . $con->affected_rows;

        $sql->close();
    }

    $con->close();
    $con = null;
}
else
{
    echo "Error! You are not authorized to access this page. Please login.";
}
?>


texts:
I have made a General Knowledge quiz in python as a project from my school

import time

score=int()
print("Welcome to the General knowledge Quesions Quiz")
time.sleep(2)
print("Question 1")
time.sleep(2)
Question1 = input ("A vehicle with the national registration code ‘PK’ would originate from which country? ")
if Question1 == ("Pakistan") or Question1 == ("pakistan"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect answer, the correct answer is Pakistan")
time.sleep(2)
print("Question 2")
time.sleep(2)
Question2 = input("In which English county is Blenheim Palace? ")
if Question2 == ("Oxfordshire") or Question2 == ("oxfordshire"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect answer, the correct answer is Oxfordshire")
time.sleep(2)
print("Question 3")
time.sleep(2)
Question3 = input("How many hours are there in a leap year? ")
if Question3 == ("8784"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect answer, the correct answer is 8784")
time.sleep(2)
print("Question 4")
time.sleep(2)
Question4 = input("In which sport could you win the Davis Cup? ")
if Question4 == ("Tennis") or Question4 == ("tennis"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect answer, the correct answer is Tennis")
time.sleep(2)
print("Question 5")
time.sleep(2)
Question5 = input("What is the capital of Afghanistan? ")
if Question5 == ("Kabul") or Question5 == ("kabul"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect answer, the correct answer is Kabul")
time.sleep(2)
print("Question 6")
time.sleep(2)
Question6 = input("How many golden stars feature on the flag of the European Union? ")
if Question6 == ("twelve") or Question6 == ("Twelve") or Question6 == ("12"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect answer, the correct answer is twelve")
time.sleep(2)
print("Question 7")
time.sleep(2)
Question7 = input("In which year did Channel 4 begin transmission in the UK? ")
if Question7 == ("1982"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect answer, the correct answer is 1982")
time.sleep(2)
print("Question 8")
time.sleep(2)
Question8=input("In which year did Theresa May become Prime Minister? ")
if Question8 == ("2016"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect answer, the correct answer is 2016")
time.sleep(2)
print("Question 9")
time.sleep(2)
Question9 = input("What is six-fourteenths of 112? ")
if Question9 == ("48") or Question9  == ("forty eight"):
    print("Correct answer")
    score = score + 1
else:
    print("Incorrect asnwer, the correct answer is 48")
time.sleep(2)
print("Question 10")
time.sleep(2)
Question10 = input("Which type of angle is greater than 90 degrees but less than 180 degrees? ")
if Question10 == ("obtuse") or ("Obtuse"):
    print("Correct answer")
    score = score + 1
time.sleep(2)
print("This is the end of the quiz")
time.sleep(1)
print("You got",(score),"/ 10")
num1 = (score)
num2 = 10
print('{0:.2f}%'.format((num1 / num2 * 100)))

I have finished the quiz and if anyone has any suggestions on how I could have improved it, they will be greatly appreciated. So please suggest how I can improve it!

Thanks :)


texts: Project Euler 30 - Digit fifth powers in Rust

texts:
I am trying to move from Python to a systems programming language so this is a bit of a challenge for me.

fn main() {
    let mut total_pow = 0;
    for x in 2..360000 {
        let values: Vec<char> = x.to_string().chars().collect();
        let mut total = 0;
        for i in values {
            let value = i.to_digit(10).unwrap();
            total += value.pow(5);
        }
        if total == x {
            total_pow += x
        }
    }
    println!("Numbers {}", total_pow);
}

It runs in just under 1 second, which I think is slow:

$ time cargo run
Total: 443839
real  0m0.894s
user  0m0.888s
sys   0m0.012s

After building with the --release flag the time has greatly improved:

$ time cargo run --release
Numbers 443839

real  0m0.083s
user  0m0.072s
sys   0m0.012s

Some of my concerns are:

Converting x, the loop value, to a char array and then converting each char back into a digit to perform pow on. Is there an easier way? In Python it is really simple (list(str(x))).
I feel the speed of this is really slow.
Best practices for rust/systems level code. I realize this is a fairly simple program but I want to make sure that I learn the good habits early.


texts: FactoryPattern without If-else construct

texts:
Someone asked me if I can create factory pattern in java without using If-else construct. So I come with the following. Please provide your inputs if this seems a good example for using factories.

public enum EnumButtonFactory {

RADIO(RadioButton.class),
SUBMIT(SubmitButton.class),
NORMAL(NormalButton.class);

private Class<? extends Button> button;

EnumButtonFactory(Class<? extends Button> b) {
    this.button = b;
}

public Button get() {
    try {
        return button.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}
}


texts: Validate if time is valid including tests

texts:
So, I'm working on a method to validate if given time(s) are valid. In most cases, the input comes from the user. I'm not exactly sure on a few points:

Readability
Integrity
Performance

I'm also rather new at writing tests. Am I missing anything?

exports = module.exports = {};

var moment = require('moment'),
    _ = require('lodash');

module.exports = {
  methods: {
    /*
     * Valids if the time passed is valid, format is 0:00
     * @param {String} time Required.
     */
    'timeIsValid': function (time) {
      // TODO: make sure it can accept a moment object..
      if (typeof time == 'object') {
        this.timesAreValid(time);
      }

      if (typeof time != 'string') {
        return false;
      }

      return /^\d+(:)([0-5][0-9])$/.test(time);
    },

    /*
     * Valids if times passed are valid, format is 0:00
     * @param {Array} times Required.
     */
    'timesAreValid': function (times) {
      // TODO: make sure it can accept a moment object..
      var errors = 0;

      if (typeof times == 'string') {
        this.timeIsValid(times);
      }

      if (typeof times != 'object') {
        return false;
      }

      if (! times.length) {
        return false;
      }

      _.forEach(times, function (time) {
        if (! this.timeIsValid(time)) {
          errors ++;
        }
      }.bind(this));

      if (errors > 0) {
        return false;
      }

      return true;
    }
  }
};

And the tests:

var helpers = require('../../resources/src/js/mixins/_helpers.js');
var assert = require('assert');

describe('timeIsValid()', function () {
  it('should return true if passed a valid date below 24h', function () {
    var valid1 = helpers.methods.timeIsValid('0:00');
    var valid2 = helpers.methods.timeIsValid('3:00');
    var valid3 = helpers.methods.timeIsValid('03:00');
    var valid4 = helpers.methods.timeIsValid('13:45');
    var valid5 = helpers.methods.timeIsValid('24:00');
    assert.equal(valid1, true);
    assert.equal(valid2, true);
    assert.equal(valid3, true);
    assert.equal(valid4, true);
    assert.equal(valid5, true);
  });
  it('should return true if passed a valid date above 24h', function () {
    var valid1 = helpers.methods.timeIsValid('24:01');
    var valid2 = helpers.methods.timeIsValid('100:00');
    assert.equal(valid1, true);
    assert.equal(valid2, true);
  });
  it('should return false if passed an invalid time', function () {
    var valid1 = helpers.methods.timeIsValid('24:61');
    var valid2 = helpers.methods.timeIsValid('-1:00');
    var valid3 = helpers.methods.timeIsValid(':00');
    var valid4 = helpers.methods.timeIsValid('abc');
    assert.equal(valid1, false);
    assert.equal(valid2, false);
    assert.equal(valid3, false);
    assert.equal(valid4, false);
  });
});

describe('timesAreValid()', function () {
    it('should return true if passed array contains valid dates', function () {
      var validDates = ['0:00', '3:00', '03:00', '13:45', '24:00'];
      var valid = helpers.methods.timesAreValid(validDates);
      assert.equal(valid, true);
    });
    it('should return false if passed array contains an invalid date', function () {
      var validDates1 = ['0:00', '3:00', '03:00', '13:45', 'a'];
      var validDates2 = ['0:00', '3:00', '03:00', '13:45', 0];
      var validDates3 = ['0:00', '3:00', '03:00', '13:45', '00:61'];
      var valid1 = helpers.methods.timesAreValid(validDates1);
      var valid2 = helpers.methods.timesAreValid(validDates2);
      var valid3 = helpers.methods.timesAreValid(validDates3);
      assert.equal(valid1, false);
      assert.equal(valid2, false);
      assert.equal(valid3, false);
    });
    it('should return false if passed array is empty', function () {
      var validDates = [];
      var valid = helpers.methods.timesAreValid(validDates);
      assert.equal(valid, false);
    });
  });


texts:
The Softmax function, or normalized exponential function, is defined as:

$$
\sigma(z)_j = \frac{e^{zj}}{\sum^K_{k=1} e^{zk}} \text{for} \space j \space \text{in} \space [1, \dots, K]
$$

I am trying to implement this in C, starting with an answer here.

#include <stdio.h>
#include <math.h>
#include <assert.h>

static void softmax(float *input, int input_len)
{
    assert (input != NULL);
    assert (input_len != 0);
    int i;
    float m;
    /* Find maximum value from input array */
    m = input[0];
    for (i = 1; i < input_len; i++) {
        if (input[i] > m) {
            m = input[i];
        }
    }

    float sum = 0;
    for (i = 0; i < input_len; i++) {
        sum += expf(input[i]-m);
    }

    for (i = 0; i < input_len; i++) {
        input[i] = expf(input[i] - m - log(sum));

    }
}

int main() {
   float arr[7] = {1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0};
   softmax(arr, 7);
   printf("%.3f %.3f %.3f %.3f %.3f %.3f %.3f", arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6]);
}

Output:

0.024 0.064 0.175 0.475 0.024 0.064 0.175

Any suggestion and comment are welcome.


texts: SQL subquery to determine whether or not a particular row is the first item that matches the subquery

texts:
Here is my VB.NET and SQL query (which is one of the things I'm particularly interested in having critiqued):

Private Sub BindHistory()

    Dim list = New List(Of CSRate)

    ' I hate the "case when" and subquery here - it seems like there should
    ' be a better way to do this
    Const Query As String =
        "select n.PayRate,
                n.CreatedOn,
                n.CreatedByUserName,
                (case when exists(select top 1 m.BusinessUnitID
                                  from TrackRates m
                                  where m.RateID = n.RateID AND
                                        m.TrackRateID < n.TrackRateID)
                 then 'entered rate of' else 'edited rate to' end) as Verb
        from    Rates, TrackRates n
        where   Rates.RateID = n.RateID AND
                Rates.ClientID = @id"
    Using reader = DBAccess.ExecuteReader(User.ActiveBusinessUnitID, CommandType.Text, Query, New SqlParameter("@id", SessionState.Client.ID))
        If reader.HasRows Then
            While reader.Read()
                Dim rate = New CSRate()
                rate.ActionDate = reader.Item("PayRate")
                rate.Action = $"User {reader.Item("Verb")} {reader.Item("PayRate")}"
                rate.UserID = reader.Item("CreatedByUserName")

                list.Add(rate)
            End While
        End If
    End Using

    CSHistory.DataSource = list
    CSHistory.DataBind()
End Sub

For the record, yes, I do realize that I should probably move the query to a stored procedure rather than having it "directly" in code-behind like this. Also, n and m are probably terrible names that I should refactor.

What I'm trying to accomplish with this SQL query is to determine whether a particular item is the first row that matches the criteria in the where clause (the text I have to display on the front end will differ). For example:

| TrackRateID | Other columns |
| 1           | ...           |
| 2           | ...           |
| 3           | ...           |

In this case, 2 and 3 should have the verb edited rate to (because there's a TrackRateID that's less than their TrackRateID) and 1 should have the verb entered rate of. (There is, of course, no guarantee that the "first" row will actually have an ID of 1).

Here's my ASP.NET front-end code:

<div id="clientHistoryPopup" style="display:none">
        <asp:GridView runat="server" ID="CSHistory" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="UserID" HeaderText="User ID" />
                <asp:BoundField DataField="ActionDate" HeaderText="Date" />
                <asp:BoundField DataField="Action" HeaderText="Pay Rate History" />
            </Columns>
        </asp:GridView>
    </div>

The case when and subquery particularly irk me. If I'm reading this properly (and please correct me if I'm wrong because I'm not too confident about this point), this would make the whole thing O(n log n).

Also, it seems like that makes the database logic too tightly "coupled" to my front-end logic, which strikes me as architecturally inappropriate.

Am I correct about the computational complexity? Is there a better way to do this that has a lower computational complexity and is less "coupled" to the front end?


texts: Minimum path sum in a triangle (Project Euler 18 and 67) with Python

texts:
Project Euler 18
Project Euler 67

As problem 67 is harder, I'll go with that one:

  By starting at the top of the triangle below and moving to adjacent
  numbers on the row below, the maximum total from top to bottom is 23.

             3
            7 4
           2 4 6
          8 5 9 3

  That is, 3 + 7 + 4 + 9 = 23.

  Find the maximum total from top to bottom in triangle.txt (right click
  and 'Save Link/Target As...'), a 15K text file containing a triangle
  with one-hundred rows.

  NOTE: This is a much more difficult version of Problem 18. It is not
  possible to try every route to solve this problem, as there are 2^99
  altogether! If you could check one trillion (10^12) routes every second
  it would take over twenty billion years to check them all. There is an
  efficient algorithm to solve it. ;o)

I solved this using dynamic programming. Here's my code:

def max_triangle_sum(triangle, height):
    if height == 1:
        return triangle[0][0]

    dp = [[-1] * row_index for row_index in range(1, height + 1)]

    dp[0][0] = triangle[0][0]

    for i in range(1, height):
        dp[i][0] = dp[i-1][0] + triangle[i][0]
        dp[i][i] = dp[i-1][i-1] + triangle[i][-1]

        for j in range(1, i):
            dp[i][j] = max(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j]

    return max(dp[-1])

if __name__ == '__main__':
    height = None

    while True:
        try:
            height = int(input('Please enter height of the triangle: '))

            if height <= 0:
                raise Exception('Height cannot be negative or 0')

            break

        except Exception as e:
            print(f'Error occurred: {e}')
            print()

    triangle = []

    for row_index in range(1, height + 1):
        while True:
            try:
                row = list(map(int, input(f'Please enter {row_index} space seperated integer(s): ').split()))

                if len(row) != row_index:
                    raise Exception(f'Exactly {row_index} numbers required')

                if any(number < 0 for number in row):
                    raise Exception(f'Numbers cannot be negative')

                triangle.append(row)

                break

            except Exception as e:
                print(f'Error occurred: {e}')
                print()

    print('The maximum triangle sum is: ')
    print(max_triangle_sum(triangle, height))

This runs quite fast, considering it would actually take 20 billion years (If your computer can compute 10^12 operations in 1 second) to solve using brute force. But still, it doesn't look that good

How do I improve this code?


texts:
#include <iostream>
#include <vector>

void function(std::vector<std::vector<int>>& matrix1, const std::vector<std::vector<int>>& matrix2)
{
    std::vector<std::vector<int>> matrix(matrix1.size(), std::vector<int>(matrix1.size()));
    int result = 0;
    int column = 0;
    if (matrix1.size() == matrix2.at(0).size() && matrix1.at(0).size() == matrix2.size())
    {
        for (int i = 0; i < matrix1.size(); ++i)
        {
            for (int j = 0; j < matrix1.at(0).size(); ++j)
            {
                result += matrix1.at(i).at(j) * matrix2.at(j).at(column);
            }
            matrix.at(i).at(column) = result;
            if (column != matrix1.size() - 1)
            {
                --i;
                ++column;
            }
            else
                column = 0;
            result = 0;
        }
    }
    matrix1 = matrix;
}
int main()
{
    std::vector<std::vector<int>> matrix1{ {1,0,2}, {-1,3,1} };
    std::vector<std::vector<int>> matrix2{ {3,1}, {2,1}, {1,0} };
    function(matrix2, matrix1);
}

The function (i.e. function) multiplies two matrix variables and changes the first parameter(i.e. matrix1). Is it possible to improve my algorithm?

I know that I can change variable names, but that isn't important. Its only an example. Maybe I can avoid two variable ints? I think that I always must create helper variables (matrix).


texts: performance of modulus operator vs if statement

texts:
The following code

if (i >= N)
    i = 0;

has been corrected to:

i %= N;

for performance reasons. Does it makes sense?

More context: i is guaranteed to be non negative. The code is used to fill a circular buffer of length N, i is first incremented and then the check is performed. N depends on user input. The code is an interview exercise so there is no clear context.


texts: How to get the indexes of smallest value per row in a DF, as column index and not column name?

texts:
I'd like, from a DataFrame, to retrieve a Series which contains the index of the minimal value per row (so axis=1). From the documentation it seems idxmin may be useful
Let' take
import pandas as pd
import numpy as np
df = pd.DataFrame({
    'col1': [0, 10, 2, 30, 4],
    'col2': [2,  3, 4,  5, 6],
    'col3': [9,  7, 5,  3, 1],
})

I've managed to get column names of minimal value
> df.idxmin(axis=1)
0    col1
1    col2
2    col1
3    col3
4    col3
dtype: object

I've managed to get the index of column of minimal vlaue
df.apply(np.argmin, axis=1)
0    0
1    1
2    0
3    2
4    2
dtype: int64

Is there any better way to obtain the 2. result using maybe a full-pandas code ?


texts: Condense repetitive jQuery .click function

texts:
I'm looking for a better way of writing this repetitive jQuery function:

(function($) {
  var mobileAmount = 300;

  $('#_100').click(function() {
    $('*').removeClass('-amount-active');
    $('#_100').addClass('-amount-active');
    mobileAmount = 100;
  });
  $('#_200').click(function() {
    $('*').removeClass('-amount-active');
    $('#_200').addClass('-amount-active');
    mobileAmount = 200;
  });
  $('#_300').click(function() {
    $('*').removeClass('-amount-active');
    $('#_300').addClass('-amount-active');
    mobileAmount = 300;
  });

  ...

})( jQuery );

There is a number of amount buttons and each time one is clicked it receives the active class for styling and updates the mobileAmount variable.


texts:
Question Description:

Given a list of companies, eg {ABC, BBC} and a large list of data looks like below:

Timestamp Security
10000000  IBM
10000001  Apple
10000005  PEAR
10000008  ABC
10000012  BBC

Find minimum time range where you can find all companies from list above.

My solution works and is brute force. But it has 3 loops. Can someone point out some ways to improve this solution in terms of runtime?

import java.util.*;

public class MinimumTimeRange {
    public static int findMinimumTimeRange(String [] list, String [] input){
        int n = list.length;
        Set<String> mySet = new HashSet<String>(Arrays.asList(list));
        int result = Integer.MAX_VALUE;
        for(int i=0; i<=(input.length-n);i++){
            for(int idx =n; idx<=(input.length-i);idx++){
                int [] timeList = new int [idx];
                Set<String> compSet = new HashSet<String>();
                for(int j=0;j<idx;j++){

                    String[] tokens = input[i+j].split(" ");
                    String time = tokens[0];
                    String comp = tokens[1];
                    timeList[j]=Integer.parseInt(time);
                    compSet.add(comp);
                }
                if(compSet.containsAll(mySet)&& (timeList[idx-1]-timeList[0])<result){
                    result = timeList[idx-1]-timeList[0];
                }
            }

        }
        return result;
    }
    public static void main(String[] args){
        String [] listCompanies = {"IBM","GE","GOOGLE"};
        String [] input = {
                "10000000 IBM",
                "10000001 Apple",
                "10000005 GOOGLE",
                "10000012 IBM",
                "10000013 TEST",
                "10000014 GE"
        };
        System.out.println(findMinimumTimeRange(listCompanies, input));
    }
}

Above code output 9, which is correct.

Other test examples:

String [] listCompanies = {"ABC","APPLE"};
String [] input = {
                    "1 ABC",
                    "2 TEST",
                    "3 APPLE",
                    "4 BBC",
                    "12 APPLE",
                    "13 ABC"
            };

Output: 1


texts:
Here you can find my implementation of sieve of Eratosthenes in Java.

/**
 * Return an array of prime numbers up to upperLimit
 * using sieve of Erastosthenes.
 * @param upperLimit
 * @return array of prime numbers up to upperLimit
 */
public static int[] sieve(int upperLimit) {
    // for corner cases
    if (upperLimit < 2) {
        return new int[0];
    }

    if (upperLimit == 2) {
        int[] result = {2};
        return result;
    }
    //--

    int arrLength = ((upperLimit - 3) / 2) + 1;

    // This arrray will be used to perform the sieve
    int[] temp = new int[arrLength];

    // Counter for number of primes encountered
    int numPrimes = 1; // because of 2

    // populate temp array with with 3,5,7,...,upperLimit
    for(int i=3; i <= upperLimit; i=i+2) {
        temp[(i-3) / 2] = i;
    }

    // Perform sieve
    for(int i=0; i < arrLength; i++ ) {
        int num = temp[i];
        if (num == 0) continue;
        numPrimes++;
        for (int k = i+num; k < arrLength; k=k+num) {
            temp[k] = 0;
        }
    }

    // Create result array
    int[] result = new int[numPrimes];
    result[0] = 2;
    int currentIndex = 1;

    for(int i: temp) {
        if (i!=0) result[currentIndex++] = i;
    }

    return result;
}

How does it look?


texts: Task for all objects in model with datetime operations

texts:
I created this quite important piece of code, but I am not pretty sure is it good enough.

Goal:

I have a big task for a database and have decided to use Django-Celery. I want to go through all objects of a particular model and create monthly statistics for each of them based on other foreign objects of it. The task will be run on the 1st day of every month.

The application will be rather dedicated for particular social group. No, I will not have millions of users.

My main worries are:

Date and time and time zone calculations.
Is it good Idea to do it with Celery? Maybe do it on the statistics view every time somebody wants to see his stats but it may take too many queries?

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import calendar
from datetime import datetime, time

from djcelery import celery
import pytz

from models import MonthlyStatistics, Scope, Entry, Action, Support

@celery.task
def calculate_monthly_statistics():
    """\
    Create Monthly Statistic objects for all Scope models.
    In statistics there are numbers of created Actions, Entries and Supports
    in last month period.
    """
    for scope in Scope.all():

        # Create datetime range for querying
        now = datetime.utcnow().replace(tzinfo=pytz.utc)

        last_month = {}
        last_month['year'] = now.year if now.month > 1 else now.year - 1
        last_month['month'] = now.month - 1 if now.month > 1 else 12
        last_month['first_day'] = 1
        last_month['last_day'] = \
            calendar.monthrange(last_month['year'], last_month['month'])[1]

        last_month_range = \
            (datetime.combine(datetime(last_month['year'],
                                       last_month['month'],
                                       last_month['first_day']),
                              time.min).replace(tzinfo=pytz.utc),
             datetime.combine(datetime(last_month['year'],
                                       last_month['month'],
                                       last_month['last_day']),
                              time.max).replace(tzinfo=pytz.utc))

        # Get Entries for current month
        entries = Entry.filter(created__range=last_month_range, diary__scope=scope)

        # Get Actions for current month
        actions = Action.filter(created__range=last_month_range, scope=scope)

        # Get Supports for current month
        supports = Support.filter(created__range=last_month_range, scope=scope)

        # Create Stats
        monthly_statistics = MonthlyStatistics.create(scope=scope,
                                                      year=now.year,
                                                      month=now.month,
                                                      support_number=len(supports),
                                                      entries=len(entries),
                                                      actions=len(actions))
        monthly_statistics.save()


texts: Finding the Players with the highest score

texts:
Given a list of Players with score, I want to find the ones with the highest score. There can be multiple players with the same score. I'm doing it like this now:

class Player {
    final String name;
    final int score;

    Player(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

class PlayerComparatorByScore implements Comparator<Player> {
    @Override
    public int compare(Player o1, Player o2) {
        return -Integer.compare(o1.score, o2.score);
    }
}

class PlayerUtil {
    static Collection<Player> getHighestScoringPlayers(Collection<Player> players) {
        List<Player> sortedPlayers = new ArrayList<>(players);
        Collections.sort(sortedPlayers, new PlayerComparatorByScore());

        Set<Player> highestScoringPlayers = new HashSet<>();
        Iterator<Player> iterator = sortedPlayers.iterator();
        Player highestScoringPlayer = iterator.next();
        highestScoringPlayers.add(highestScoringPlayer);

        while (iterator.hasNext()) {
            Player player = iterator.next();
            if (player.score == highestScoringPlayer.score) {
                highestScoringPlayers.add(player);
            } else {
                break;
            }
        }

        return highestScoringPlayers;
    }
}

public class PlayersSortedByScoreTest {
    @Test
    public void testSortingByScore() {
        Collection<Player> players = new HashSet<>();
        players.add(new Player("Alice", 3));
        players.add(new Player("Bob", 1));
        players.add(new Player("Mike", 3));

        Collection<Player> highestScoringPlayers = PlayerUtil.getHighestScoringPlayers(players);

        assertEquals(2, highestScoringPlayers.size());
        assertEquals(3, highestScoringPlayers.iterator().next().score);
    }
}

So this is pretty awkward... Is there a better way?


texts:
This code reaches time limit on 1 test case, solving this challenge. The approach that I'm using is from the book Algorithms Functional Programming Approach, which is a backtracking depth searching method. How do I improve speed of this code? Or is there better way to do it?

searchDfs :: (Eq node) =>
             (node -> [node]) -> -- generates successor nodes
             (node -> Bool) -> -- is goal
             node -> -- first node
             [node]
searchDfs succ goal x = search' ([x])
  where
    search' s
      | null s = []
      | goal (head s) = head s : search' (tail s)
      | otherwise = let x = head s
                    in search' (succ x ++ tail s)

type Degree = Int
type CurrentSum = Int
type CurrentNumber = Int
type Node = (CurrentSum,CurrentNumber,Degree,Goal)
type Goal = Int

succN :: Node -> [Node]
succN (sum,i,d, goal)  = [( sum+i'^d, i', d, goal) | i' <- [(i+1)..goal], sum+i'^d <= goal ]

goal :: Node -> Bool
goal (sum,_,_,m) = sum == m

countSols :: Degree -> Goal -> Int
countSols d m = foldr (+) 0 $ map (\(sum,i) -> length (searchDfs succN goal (sum,i,d,m))) startingNumbers
  where startingNumbers = [ (i^d,i) | i <- [1..m], i^d <= m]

main = do
  m <- readLn
  d <- readLn
  let c = countSols d m
  print c


texts: Calculating large powers of 2 in decimal

texts:
So, this is my problem to solve:

I want to calculate \$2^n\$ where \$0 < n< 10000\$

I am representing each element of array as a space where 4digit number should be "living" and if extra digit appears, I am replacing it to the next element of this array.

The principle I am using looks like this:

The code I am using is the following:

static string NotEfficient(int power)
{
if (power < 0)
    throw new Exception("Power shouldn't be negative");
if (power == 0)
    return "1";
if (power == 1)
    return "2";

int[] A = new int[3750];

int current4Digit = 0;

//at first 2 is written in first element of array
A[current4Digit] = 2;

int currentPower = 1;

while (currentPower < power)
{
    //multiply every 4digit by 2
    for (int i = 0; i <= current4Digit; i++)
    {
        A[i] *= 2;
    }

    currentPower++;

    //checking every 4digit if it
    //contains 5 digit and if yes remove and
    //put it in next 4digit
    for (int i = 0; i <= current4Digit; i++)
    {
        if (A[i] / 10000 > 0)
        {
            int more = A[i] / 10000;
            A[i] = A[i] % 10000;
            A[i + 1] += more;

            //if new digit should be opened
            if (i + 1 > current4Digit)
            {
                current4Digit++;
            }

        }

    }
}

//getting data from array to generate answer
string answer = "";

for (int i = current4Digit; i >= 0; i--)
{
    answer += A[i].ToString().PadLeft(4,'0') + ",";
}

return return answer.TrimStart('0');
}


texts: Create composition instead of inheritance

texts:
[DataContract(Name = "jobDateTimeFilterRequest", Namespace = Constants.ManagementNamespace)]
public class JobDateTimeFilterRequest : TimeFrame
{
    [DataMember(Name = "jobType")]
    public BackgroundJobType JobType { get; set; }
}

[DataContract(Name = "timeFrame", Namespace = Constants.ManagementNamespace)]
public class TimeFrame
{
    [DataMember(Name = "from")]
    public DateTime From { get; set; }

    [DataMember(Name = "to")]
    public DateTime To { get; set; }
}

I would like to use composition instead of inheritance. To do this I will need to create:

[DataContract(Name = "jobFilterRequest", Namespace = Constants.ManagementNamespace)]
public class JobFilterRequest
{
    [DataMember(Name = "jobType")]
    public BackgroundJobType JobType { get; set; }
}

And JobDateTimeFilterRequest will be like this:

[DataContract(Name = "jobDateTimeFilterRequest", Namespace = Constants.ManagementNamespace)]
public class JobDateTimeFilterRequest
{
    [DataMember(Name = "jobType")]
    public JobFilterRequest JobFilter { get; set; }

    [DataMember(Name = "timeFrame")]
    public TimeFrame TimeFrame{ get; set; }
}

I'm I right? Or it's incorrect understanding of composition?


texts: Creating a pure Ruby object (PORO) to email files in a Rails application

texts:
I wrote a service object that emails a list of files to a list of email addresses.

I am unsure about my emails method. It splits a string into an array of emails. It then loops over the array and rejects any elements that do not match the email regex. The return value is an array of valid emails stripped of whitespace.

Another thing I'm getting a bad feeling about is the caching of the bucket, @bucket ||= ..., and the url = get_urls temp variable in the send_email method.

class FileSharingService
  def initialize(files, params)
    @files = files
    @params = params
    @client = AWS::S3.new
  end

  def send_email
    urls = get_urls
    emails.each do |email|
      FileSharingMailer.email_files(email, params[:message], urls)
    end
  end

  def emails
    @params[:emails].split(',').reject do |email|
      email.strip!
      email !~ /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    end
  end

  def get_urls
    @files.map do |file|
      bucket.objects[file.current_version.path].url_for(:get, expires: 1.week.from_now)
    end
  end

  def bucket
    @bucket ||= @client.buckets[ENV['S3_BUCKET']]
  end
end


texts: Randomizing all class variables in constructor c++

texts:
I'm playing around with making random items and decided to implement the following structure.

#include <stdlib.h> //uints
#include <limits>
#include <random>
#include <iostream>

class RandomItem {
private:
    struct _physical_properties { uint16_t length; uint16_t width; uint16_t sqew; uint16_t weight; };
    struct _color { uint8_t r; uint8_t g; uint8_t b; uint8_t a;};
    //etc
public:
    _physical_properties physical;
    _color main_color;
    _color secondary_color;
    uint16_t durability;
    uint32_t type;

    RandomItem() = default;
    RandomItem(uint32_t _type) {
        union thing {
            RandomItem item;
            uint8_t buf[sizeof(RandomItem) / sizeof(uint8_t) ];
        };
        thing bad{};
        std::random_device dev;
        std::mt19937 gen(dev());
        std::uniform_int_distribution<> dist(0, std::numeric_limits<uint8_t>::max());
        for (auto& b : bad.buf) {
            b = static_cast<uint8_t>(dist(gen));
        }
        *this = bad.item;
        this->type = _type;
    }
};

int main() {
    RandomItem a(1);
    RandomItem b(2);
    std::cout << "item type: " << a.type << " Some values: " << (int)a.physical.length << ", " << a.durability << std::endl;
    std::cout << "item type: " << b.type << " Some values: " << (int)b.physical.length << ", " << b.durability << std::endl;
    return 0;
}

(edited slightly to post here in a more minimal form...using iostream instead of fmt sticking in one file etc)

seeing as how:

The total number of properties in the class can increase and have (potentially) different types
I don't particularly feel like

prop1 = dist(gen);
prop2 = dist(gen);
prop3 = dist(gen);
//etc

is very scalable...

I wrote the displayed constructor and that's specifically what I'm asking for feedback on (rest of the dummy class is just for the example)

It uses a union between the item and a buffer and fills that buffer with random values then sets the current object equal to the unionized item.

This feels hacky however might be better than alternatives (individually setting each variable manually or the other end of the gross hack scale making a macro that expands to setting each variable)

Are there any major gotchas with doing this?

Am I relying on undefined behavior and or will this style of code introduce bugs down the line? (as far as I can see it doesn't quite matter what the endianness of the computer is 'cause the value is random)

Is this the best way to implement my goal? (set all the variables and nested variables to random values on construction).

I'm posting here instead of StackOverflow because it appears to work (compiles and  and I assume any answers would just be opinion-based.
I'm not working with other people and for now, I'm just experimenting with things. (this isn't being used in a project but I might add it into one in the future.).

Is it "better" to make the class nothing but POD without a constructor and then implement a function that does pretty much the same code and return the constructed item? (something like)

Item& randomItem(uint32_t type){
    union thing{
        Item item;
    //snip
    ...
    return item;
}

To avoid the hacky *this = item; code (smell?)

Of course, if I was actually writing a game or similar program that implemented a class of random variables I'd probably have some constraints for what the random values for different types of items could be. (For example, length/width might be a distribution between (300-1000) instead of (0-maxValueOfType) so maybe this is just a contrived example. However, if anyone has any feedback on the rest of the concept I'd be interested.


texts:
I've made code that scores each letter in a word you input according to the table below:

  1: AEILNORSTU
  2: DG
  3: BCMP
  4: FHVWY
  5: K
  8: JX
  10: QZ

I appreciate any feedback, but the main reason of this post concerns the charPoint method. Should I rewrite this using switch? Or is there an even better way to write it?

package exercicios;

import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;

import acm.program.*;

public class Ex5 extends ConsoleProgram{

    public void run(){
        String word = readLine("Enter a word: ");
        println(wordScore(word));

    }

    private int wordScore(String word){
        int score = 0;

        for (int i = 0; i < word.length(); i++){
            score += charPoint(word.substring(i, i+1));
        }

        return score;
    }
    private int charPoint(String ch){

        if (ch.matches("[AEILNORSTU]")){
            return 1;
        } else if (ch.matches("[DG]")){
            return 2;
        } else if (ch.matches("[BCMP]")){
            return 3;
        } else if (ch.matches("[FHVWY]")){
            return 4;
        } else if (ch.matches("[K]")){
            return 5;
        } else if (ch.matches("[JX]")){
            return 8;
        } else if (ch.matches("[QZ]")){
            return 10;
        } else return 0;

    }
}


texts:
I am making a simple function that retrieves a 3x3 cells out of NxM grid and determines the direction of cells base on their previous and next neighbor. It will return either any of the following

HORIZONTAL
VERTICAL
TOP_LEFT
TOP_RIGHT
BOTTOM_LEFT
BOTTOM_RIGHT
or INDETERMINATE

Suppose I have this data:

0 1 0
0 1 0
0 1 0
// Direction: VERTICAL

0 0 0
1 1 1
0 0 0
// Direction: HORIZONTAL

0 1 0        0 1 0        0 0 0        0 0 0
1 1 0        0 1 1        1 1 0        0 1 1
0 0 0        0 0 0        0 1 0        0 1 0
//TOP_LEFT   TOP_RIGHT    BOTTOM_LEFT  BOTTOM_RIGHT

0 0 0
1 0 0
1 0 0
// Direction: INDETERMINATE

This function would run many times and would vary(increase) depending on some other factors.

My functioning code so far is this:

var SNAKE_BODY = 1;
var SNAKE_HEAD = 2;

function isSnake(cell) {
    return cell == SNAKE_BODY || cell == SNAKE_HEAD;
}

function getMatrixNeighbors(x, y, board) {
    var neighbors = [];

    for(var row = y - 1; row <= y + 1; ++row) {
        for(var col = x - 1; col <= x + 1; ++col) {
            if ( col >= 0 && col < board.width
              && row >= 0 && row < board.height) {
                var cell = board.at(row, col);
                neighbors.push(cell);
            } else {
                neighbors.push(EMPTY);
            }
        }
    }
    return neighbors;
}

function getBodyDir(x, y, board) {

    var cells = getMatrixNeighbors(x, y, board);

    var top     = cells[1];
    var bottom  = cells[7];
    var left    = cells[3];
    var right   = cells[5];

    if ( isSnake(top) && isSnake(bottom) ) {
        if ( isSnake(cells[0])
          || isSnake(cells[2])
          || isSnake(cells[6])
          || isSnake(cells[8]) ) {
            return BODY_DIR_NEGLECT;
        }
        return BODY_DIR_VERTICAL;
    }

    if ( isSnake(left) && isSnake(right) ) {
        if ( isSnake(cells[0])
          || isSnake(cells[2])
          || isSnake(cells[6])
          || isSnake(cells[8]) ) {
            return BODY_DIR_NEGLECT;
        }
        return BODY_DIR_HORIZONTAL;
    }

    if ( isSnake(top) && isSnake(left) ) {
        return BODY_DIR_TOP_LEFT;
    }

    if ( isSnake(top) && isSnake(right) ) {
        return BODY_DIR_TOP_RIGHT;
    }

    if ( isSnake(bottom) && isSnake(left) ) {
        return BODY_DIR_BOTTOM_LEFT;
    }

    if ( isSnake(bottom) && isSnake(right) ) {
        return BODY_DIR_BOTTOM_RIGHT;
    }

     // return BODY_DIR_VERTICAL;
     return BODY_DIR_UNKNOWN;
}

I think this is the bottleneck in my app so I would like to know if there's anything you could suggest to improve the processing speed of this. Dirty hack is welcomed also as this is scripting and soon to be release.


texts:
This is my general database connection class. I am using this class to execute my queries through website.

What would your suggestions on how to improve performance be?

(Running MSSQL 2008 R2 SP1 - Microsoft Visual Studio 2010 SP1 , C# 4.0 - ASP.net 4.0)

Class:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.IO;

/// <summary>
/// Summary description for DbConnection
/// </summary>
public class DbConnection
{
    public static string srConnectionString = "server=localhost;database=myDB;uid=sa;pwd=MYPW;";

    public DbConnection()
    {

    }

    public static DataSet db_Select_Query(string strQuery)
    {
        DataSet dSet = new DataSet();

        try
        {
            using (SqlConnection connection = new SqlConnection(srConnectionString))
            {
                connection.Open();
                SqlDataAdapter DA = new SqlDataAdapter(strQuery, connection);
                DA.Fill(dSet);
            }
            return dSet;
        }

        catch (Exception)
        {
            using (SqlConnection connection = new SqlConnection(srConnectionString))
            {
                if (srConnectionString.IndexOf("select Id from tblAspErrors") != -1)
                {
                    connection.Open();
                    strQuery = strQuery.Replace("'", "''");
                    SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection);
                    command.ExecuteNonQuery();
                }
            }
            return dSet;
        }
    }

    public static void db_Update_Delete_Query(string strQuery)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(srConnectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(strQuery, connection);
                command.ExecuteNonQuery();
            }
        }
        catch (Exception)
        {
            strQuery = strQuery.Replace("'", "''");
            using (SqlConnection connection = new SqlConnection(srConnectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection);
                command.ExecuteNonQuery();
            }

        }
    }
}


texts: Find an equation that uses all 9 digits (1-9)

texts:
I used Python to write the following program:

"""
A desired equation includes a 4-digit integer multiplied with a single-digit integer
to give another 4-digit integer and all 9 digits(1-9) are used in the equation.
"""

import random

found=False

while not found:
    full_range=range(1,10)

    four_digit_num=""
    multiple=""
    for i in range(4):
        four_digit_num+=str(full_range.pop(random.randint(1,len(full_range)-1)))

    single_digit_num=full_range.pop(random.randint(1,len(full_range)-1))

    for i in range(4):
        multiple+=str(full_range.pop(random.randint(1,len(full_range)-1)))

    if int(four_digit_num)*single_digit_num==int(multiple):
        found=True

#output the equation
print "The desired equation is:"
print four_digit_num+"*"+str(single_digit_num)+"="+multiple

Is there any better way to perform this task?


texts: Was this shell script ready for open-source? (Random XKCD wallpaper)

texts:
I wrote the following little shell script and published it on GitHub. In the repo there's also a README file that explains how to use it in more detail.

This is the first time I open-sourced/published something I wrote, so I'm interested whether you think that this code is ready for the public.

Some pointers, but feel free to add your own thoughts:

Does it look professional? If not, what would need to be done?
Are the comments too much? Was it ok to publish it, although I know that under some circumstances it doesn't work (I wrote about that in the README)?

#    random xkcd wallpaper: gets a random xkcd comic from xkcd.com and sets it as the desktop background.

#!/bin/bash

# /random/comic redirects to random comic. Wget gets the index.html of the comic.
wget http://dynamic.xkcd.com/random/comic/

echo $(pwd)

#Searches the line in the index.html file that points to the url where the actual comic is placed.
#The image urls are of the form: http://imgs.xkcd.com/comics/.'name of comic'.(png | jpg)
url=$(cat index.html | grep -o -m 1 http://imgs.xkcd.com/comics/.*\.png)

#Assuming picture format is .png. Gets the name of the image file by only matching what comes after the last forward slash.
name_pic=$(echo $url | grep -o [^/]*\.png)
is_png=1

#Sets url and name_pic in the case of the picture being in .jpg format.
if [ -z "$url" ]
then
    url=$(cat index.html | grep -o -m 1 http://imgs.xkcd.com/comics/.*\.jpg)
    name_pic=$(echo $url | grep -o [^/]*\.jpg)
    is_png=0
fi

#Downloads the image and saves it under its appropriate name.
wget --output-document="$name_pic"  "$url"

#Sets the desktop background
gconftool-2 --set --type=string /desktop/gnome/background/picture_filename $(pwd)/"$name_pic"

#Cleans up
rm index.html

#For some reason, if the image is moved to fast (e.g without a wait) the background does not get set.
sleep 1

#The current wallpaper can always be found under "current_xkcd_wallpaper.png" or "current_xkcd_wallpaper.jpg". Also prevents cluttering the directory with images.
#If you want to keep all the pictures you downloaded, uncomment the following lines.

#Cleans up. Makes sure that there is only one current_xkcd_wallpaper image file.
#rm current_xkcd_wallpaper.*

rm current_xkcd_wallpaper.*

if [ $is_png = 1 ] ; then
    mv $(pwd)/"$name_pic" $(pwd)/current_xkcd_wallpaper.png
else
    mv $(pwd)/"$name_pic" $(pwd)/current_xkcd_wallpaper.jpg
fi


texts:
I have coded the Lucas-Lehmer primality test following Wikipedia's description. I used the mod 2^n - 1 suggested in the article but was wondering if there were any other improvements I could make. I am using the GMP library for arbitrary precision integers. The program asks an integer n as input, then checks every Mersenne number M(i) for all i less than n. n = 10000 takes around 25 seconds on my computer.

#include <gmp.h>
#include <stdio.h>

_Bool mersenne_prime(unsigned long exponent) {
    mpz_t sequence, number, temp;
    // Intialize variables
    mpz_init_set_ui(sequence, 4);
    mpz_init(temp);
    // Set number to 2^n - 1
    mpz_init_set_ui(number, 1);
    mpz_ui_pow_ui(number, 2, exponent);
    mpz_sub_ui(number, number, 1);
    // Repeat exponent-2 times
    for (unsigned long counter = exponent; --counter - 1;) {
        mpz_mul(sequence, sequence, sequence);
        // Modulus suggested by wikipedia
        while (mpz_cmp(sequence, number) > 0) {
            // Most significant bits of sequence
            mpz_div_2exp(temp, sequence, exponent);
            // Least significant bits of sequence
            mpz_mod_2exp(sequence, sequence, exponent);
            mpz_add(sequence, sequence, temp);
        }
        // Erratic case
        if (mpz_cmp(number, sequence) == 0) {
          mpz_set_ui(sequence, 0);
        }
        mpz_sub_ui(sequence, sequence, 2);
    }
    // sequence == 0 means prime
    _Bool result = mpz_sgn(sequence) == 0;
    // Clear variables
    mpz_clears(sequence, number, temp, NULL);
    return result;
}

int main() {
    mpz_t num;
    unsigned long limit;
    mpz_init_set_ui(num, 3);
    // Get limit
    scanf("%lu", &limit);
    printf("Searching for Mersenne primes...\nM2 is prime!\n");
    while (mpz_cmp_ui(num, limit) < 0) {
        unsigned long num_ui = mpz_get_ui(num);
        if (mersenne_prime(num_ui)) {
            printf("M%lu is prime!\n", num_ui);
        }
        mpz_nextprime(num, num);
    }
    // Clear num
    mpz_clear(num);
    return 0;
}


texts: Python - Get Unique frames of video containing object

texts:
I am analyzing videos from the popular social media platform, TikTok, and extracting the songs into a Spotify playlist. Here is a gif of one of these videos: https://i.imgur.com/I0dVoac.mp4. Full video: https://vm.tiktok.com/ZMJwqpTPq

Basically, after the video is downloaded, I get unique frames in 2 steps:

Get frames with a play button in them.

Get frames where the difference with the previous frame is significant.

My code thus far is:
import cv2
from skimage.metrics import structural_similarity  as ssim
import timeit

MATCHES = [
    {
        'img': cv2.imread('spotify_play.jpg', cv2.IMREAD_GRAYSCALE),
        'name': 'spotify',
        'bounds': [.8, .94]
    },
    {
        'img': cv2.imread('apple_play_2.jpg', cv2.IMREAD_GRAYSCALE),
        'name': 'apple',
        'bounds': [.7, .82]
    }
]

def time_method(func):
    def wrapper(*args):
        start = timeit.default_timer()
        val = func(*args)
        elapsed = timeit.default_timer() - start
        print(f'Elapsed time of {func.__name__}:', elapsed)
        return val
    return wrapper

@time_method
def get_music_frames(file, matches, min_sim=0.5):
    video = cv2.VideoCapture(file)
    phase2 = []
    types = []
    y = None
    while True:
        ret,frame = video.read()
        if ret:
            gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            _, threshed = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
            for i, match in enumerate(matches):
                matched_result = cv2.matchTemplate(match['img'], threshed , cv2.TM_SQDIFF_NORMED)
                c,_,loc,_ = cv2.minMaxLoc(matched_result)
                if c < min_sim:
                    if y is None:
                        y = loc[1]
                    phase2.append(frame[:y, :])
                    types.append(i)
                    break
        else:
            break
    video.release()
    if len(phase2) == 0:
        return [], None
    n = round(sum(types) / len(types))
    best_match = matches[n]
    m = best_match['bounds']
    final = []
    for my_frame in phase2:
        height, _,_ = my_frame.shape
        final.append(my_frame[int(height*m[0]):int(height*m[1]), :])
    return final, best_match
@time_method
def remove_duplicate_frames(frames, max_sim=0.97):
    pframe = frames[0]
    non_duplicate_frames = []
    for frame in frames[1:]:
        sim = ssim(frame, pframe, multichannel=True)
        if sim < max_sim:
            gray_frame = cv2.cvtColor(pframe, cv2.COLOR_BGR2GRAY)
            _, bw_frame = cv2.threshold(gray_frame, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
            non_duplicate_frames.append(255 - bw_frame)
        pframe = frame
    return non_duplicate_frames

if __name__ == '__main__':
    frames, best_type = get_music_frames('input.mp4', MATCHES)
    if len(frames) == 0:
        exit()
    frames = remove_duplicate_frames(frames)

My code runs really slowly:
retep@desktop:~/repos/tiktok-analyze-js$ python3 analyze.py
Elapsed time of get_binary_from: ...
Elapsed time of get_music_frames: 18.29
Elapsed time of remove_duplicate_frames: 2.16
Elapsed time of recognize_text_in_frames: ...

I am looking for some optimizations to lower the time to process below 20 seconds.


texts: Mixing business logic and presentation layer in enum type

texts:
Let's assume I have an enum type with currency:

public enum CurrencyType {

    USD("American Dollar", "USD"),
    EUR("Euro", "EUR"),
    JPY("Japan Yen", "JPY");

    private final String fullName;
    private final String shortName; // enum valirables can change in the future, so I do not use Currency.name()

    private CurrencyType(String fullName, String shortName) {
        this.fullName = fullName;
        this.shortName = shortName;
    }

    public String getFullName() {
        return this.fullName;
    }

    public String getFullNameLocalized(ResourceBundle bundle) {
        // returns the currency name using some ResourceBundle with localized strings
    }

    public String getShortName() {
        return this.shortName;
    }
}

Now, somewhere in the presentation layer I say:

CurrencyType curr = CurrencyType.EUR;
// ...
labelCurrencyTypeName.setText(curr.getFullNameLocalized(bundle));
labelCurrencyTypeSymbol.setText(curr.getShortName());

in order to see the "EUR" string in an appropriate place.

Everything is perfect, but such approach mixes the Model and View together, doesn't it? CurrencyType is widely used in business logic and this is it's main goal.

What other approach would you suggest? Or maybe my code is not so wrong as I expect?


texts: Vulkan and Opengl swapable rendering backend

texts:
I'm working on a multi render library. The point of it is to have a swapable backend at runtime to render the same item.

The renderer is given to the window (which is a wrapper over SDL2). Then the window is in charge of drawing a IDrawable, which is a virtual class implemented in a namespace for each backend.
The implementation of IDrawable in each namespace got the same tag as the backend, for preventing rendering a drawable with the wrong backend.

Here's the code. I would appreciate some reviews on the architecture; what's good and what's wrong.

Thanks!

#include <string>
#include <iostream>

enum Tag
{
  VK,
  GL
};

class IDrawable
{
    public:
        virtual void draw() = 0;
        virtual Tag getTag() const = 0;
};

namespace gl
{

class D : public IDrawable
{
    public:
        void draw()
        {
            std::cout << "Drawable gl::D\n";
        }

        Tag getTag() const { return tag; };
    private:
        Tag tag = Tag::GL;
};

}

namespace vk
{

class D : public IDrawable
{
    public:
        void draw()
        {
            std::cout << "Drawable vk::D\n";
        }

        Tag getTag() const { return tag; };
    private:
        Tag tag = Tag::VK;
};

}

class Backend
{
    public:
        virtual void render(IDrawable * d) = 0;
};

class Opengl : public Backend
{
    public:
        void render(IDrawable * d)
        {
            std::cout << "Backend gl\n";
            d->draw();
        }
        Tag getTag() { return tag; };
    private:
        Tag tag = Tag::GL;
};

class Vulkan : public Backend
{
    public:
        void render(IDrawable * d)
        {
            std::cout << "Backend vk\n";
            d->draw();
        }
        Tag getTag() { return tag; };
    private:
        Tag tag = Tag::VK;
};

template <typename T>
class Renderer
{
    static_assert(std::is_base_of<Backend, T>::value, "Backend not valid");
    public:
        void draw(IDrawable * d)
        {
            if(backend.getTag() == d->getTag())
            {
                backend.render(d);
            }
            else
            {
                std::cout << "Cannot render\n";
            }
        }

        T backend;
};

template <typename T>
class Window
{
    public:
        Window(Renderer<T> r) : rend(r) {}

        void draw(IDrawable * d)
        {
            rend.draw(d);
        }

    private:
        Renderer<T> rend;
};

int main()
{
    Renderer<Opengl> a;
    Renderer<Vulkan> b;

    Window w(a);
    Window k(b);

    gl::D d1;
    vk::D d2;

    w.draw(&d1);
    k.draw(&d2);
    w.draw(&d2); // Should fail

    return 0;
}

Live example


texts:
I made this utility function to check for parameters.
All it does is checking whether a given variable is an int, or a float/str that represent exactly an int (ie. no decimal part or NaN), and casting to that int (raising a ValueError exception on failure).
I'm not very experienced with Python (especially Python 3+), so I'm still learning and trying to improve my programming skills.
I'm open to any critics, improvements, and bad/good practices tips.
Also I'm trying to learn how to properly document Python code (my IDE is PyCharm and hints me to use reStructuredText docblocks, and default Python3 typing hints).
I'm using Python3.6 for the following code:
util.py
from typing import Union

def int_exact_cast(n: Union[int, float, str]) -> int:
    """
    Tries to cast parameter to int without losing decimal part or raise an exception
    :param Union[int, float] n: The value to be converted
    :type n: Union[int, float]
    :return: The converted int value
    :rtype: int
    :raises ValueError: raises ValueError exception if the parameter can't be casted exactly to int
    """

    t = type(n)

    if t is int:
        return n  # return immediately if is already int (optimization)

    if not (t is str or t is float):
        raise ValueError('Parameter must be an int, str or float')

    f = float(n)

    if not f.is_integer():  # not checking for math.nan because in that case is_integer() returns False
        raise ValueError('Parameter contains a decimal part')

    return int(f)


texts:
I have huge number of text files, each several hundred MB in size. Unfortunately, they are not all fully standardized in any one format. Plus there is a lot of legacy in here, and a lot of junk and garbled text. I wish to check all of these files to find rows with a valid email ID, and if it exists then print it to a file named the first-char of the email ID. Hence, multiple text files get parsed and organized into files named a-z and 0-9. In case the email address starts with a special character, then it will get written into a file called "_" underscore. The script also trims the rows to remove whitespaces; and replaces single and double quotes (this is an application requirement)

My script works fine. There are no errors or bugs in it. But it is incredibly slow. My question: is there a more efficient way to achieve this? Parsing 30 GB logs takes me about 12 hrs - way too much! Will grep/cut/sed/another be any faster?

Sample txt File

!bar@foo.com,address
#john@foo.com;address
john@foo.com;address µÖ
email1@foo.com;username;address
email2@foo.com;username
  email3@foo.com,username;address   [spaces at the start of the row]
 email4@foo.com|username|address   [tabs at the start of the row]

My Code:

awk -F'[,|;: \t]+' '{
    gsub(/^[ \t]+|[ \t]+$/, "")
    if (NF>1 && $1 ~ /^[[:alnum:]_.+-]+@[[:alnum:]_.-]+\.[[:alnum:]]+$/)
    {
        gsub(/"/, "DQUOTES")
        gsub("\047", "SQUOTES")
        r=gensub("[,|;: \t]+",":",1,$0)
        a=tolower(substr(r,1,1))
        if (a ~ /^[[:alnum:]]/)
            print r > a
        else
            print r > "_"
    }
    else
        print $0 > "ErrorFile"
}' *.txt


texts: What’s your opinion on a Throw() method?

texts:
Lately I seem to run into a situation very frequently where I want to write something like the following:

var x =
    condition1 ? value1 :
    condition2 ? value2 :
    condition3 ? value3 :
    condition4 ? value4 :
    throw new InvalidOperationException();

Suppose the conditions are not simply constants so I can’t use switch, but they are not complex enough expressions to warrant saying that ?: is too unreadable.

Of course the above construct doesn’t compile because throw is a statement, not an expression. Therefore, I considered writing a method that does exactly that:

/// <summary>Throws the specified exception.</summary>
/// <typeparam name="TResult">The type to return.</typeparam>
/// <param name="exception">The exception to throw.</param>
/// <returns>This method never returns a value. It always throws.</returns>
public static TResult Throw<TResult>(Exception exception)
{
    throw exception;
}

[...]

var x =
    condition1 ? value1 :
    condition2 ? value2 :
    condition3 ? value3 :
    condition4 ? value4 :
    Ut.Throw<MyType>(new InvalidOperationException());

Are there any problems with this approach that I’m not seeing?


texts: Zero-padding a number to have six digits

texts:
This is a switch statement in JavaScript. I have a feeling that it can be done in a shorter way.

switch(n.length){
  case 1:
    n = '00000' + n;
  break;
  case 2:
    n = '0000' + n;
  break;
  case 3:
    n = '000' + n;
  break;
  case 4:
    n = '00' + n;
  break;
  case 5:
    n = '0' + n;
  break;
}


texts:
I've just learned the OOP concept of abstraction, and I was wondering if I was implementing it correctly in my code and if you guys can point out any bad practices.

test1.java

package OOPConcepts;

import java.util.Scanner;
public class test1 {
    static public Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
        String fName, lName;
        int age;
        Student newPerson = new Student();
        input.close();
    }
}

Person.java

package OOPConcepts;

public class Person
{
    static private int pNumber = 0;
    private int pID;
    public int age;
    private String type;
    public String fName, lName;

    Person()
    {
        pNumber++;
        pID = pNumber;

        System.out.println("Enter first name:");
        String fName = test1.input.next();
        System.out.println("Enter last name:");
        String lName = test1.input.next();
        System.out.println("Enter age:");
        int age = test1.input.nextInt();
        type = "person";
        describe(fName, lName, age);

        System.out.println("Made a " + type);
    }
    public void setType(String type){
        this.type = type;
    }
    public String getType()
    {
        return this.type;
    }
    public void describe(String fName, String lName, int age)
    {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
        System.out.println("Name: " + this.fName + " " + this.lName + "|Age: " + this.age);
    }
}

Student.java

package OOPConcepts;

public class Student extends Person{
    static private int sNumber = 0;
    private int studentID;
    public String major;

    Student()
    {
        sNumber++;
        studentID = sNumber;
        setType("student");

        System.out.println("Who is also a " + getType());
        System.out.println("Enter major: ");
        String major = test1.input.next();
        this.major = major;
    }
    public void setStudentID(int idNumber)
    {
        this.studentID = idNumber;
    }
    public int getStudentID()
    {
        return this.studentID;
    }
}


texts: Binary tree (S-Expression) pretty printer

texts:
I'm just trying to create a binary tree, and a pretty printer for it:

#include <stdio.h>

typedef unsigned long Leaf;

struct NodeStruct {
    struct TreeStruct * left;
    struct TreeStruct * right;
};
typedef struct NodeStruct Node;

struct TreeStruct {
    char isNode;
    union {
        Node node;
        Leaf leaf;
    } value;
};
typedef struct TreeStruct Tree;

Tree node(Tree* left, Tree* right){
    Tree result;
    result.isNode = 1;
    result.value.node.left = left;
    result.value.node.right = right;
    return result;
};

Tree leaf(unsigned long x){
    Tree result;
    result.isNode = 0;
    result.value.leaf = x;
    return result;
};

void print(Tree* tree, int isRoot){
  if (!tree->isNode){
        printf("%lu",tree->value.leaf);
        return;
    };
    printf("(");
    print(tree->value.node.left,0);
    printf(" ");
    print(tree->value.node.right,0);
    printf(")");
};

int main(){
    Tree a = leaf(1);
    Tree b = leaf(2);
    Tree c = leaf(3);
    Tree d = leaf(4);
    Tree ab = node(&a,&b);
    Tree cd = node(&c,&d);
    Tree abcd = node(&ab,&cd);
    print(&abcd,1);
};

There are so many things that sound wrong to me, yet I don't know how I'm supposed to improve this in C. Ideas?

Also, what if I wanted to return the string instead of printing it?


texts: Marking a class as final or sealing a class

texts:
Which of these metaclasses should be preferred, and is there room for improvement?

Some people are not familiar with the philosophies that come with working in Python and have a desire embedded in them from other languages that allow them to make it impossible to inherit from and extend a class through subclassing. Python has no builtin in way of preventing this but can be supplemented with comments or other documentation that explains that a class should not be part of an inheritance tree. Alternatively, some programmers with backgrounds in other languages may require the use of a metaclass to prevent subclassing when appropriate.

Assuming a project's leader would not budge on the use of metaclasses for such a purpose but was open to alternate implementations, which of the following is better at following best practices targeted at Python? Both are rather simple, so another question may be difficult to answer: can either be improved?

First Metaclass

class SealedMeta(type):
    """SealedMeta(name, bases, dictionary) -> new sealed class"""
    __REGISTRY = ()

    def __new__(mcs, name, bases, dictionary):
        """Create a new class only if it is not related to a sealed class."""
        if any(issubclass(base, mcs.__REGISTRY) for base in bases):
            raise RuntimeError('no class may inherit from a sealed class')
        mcs.__REGISTRY += (super().__new__(mcs, name, bases, dictionary),)
        return mcs.__REGISTRY[-1]

Second Metaclass

class Final(type):
    """Final(name, bases, dictionary) -> new final class"""

    def __new__(mcs, name, bases, dictionary):
        """Create a new class if none of its bases are marked as final."""
        if any(isinstance(base, mcs) for base in bases):
            raise TypeError('no class may inherit from a final class')
        return super().__new__(mcs, name, bases, dictionary)


texts:
I attempted a coding exercise during an interview, defined & implemented here (readme for problem):

https://gitlab.com/vineet_rc/health-insurance-premium-quote-generator-2

It was initially a simple and single java class program.

public double calculatePremium(Person person) {
    // Added base premium
    double premium = 5000;

    // Increase premium depending on age
    if (person.getAge() >= 18) {
        premium *= 1.1;
    }
    if (person.getAge() >= 25) {
        premium *= 1.1;
    }
    if (person.getAge() >= 30) {
        premium *= 1.1;
    }
    if (person.getAge() >= 35) {
        premium *= 1.1;
    }
    if (person.getAge() >= 40) {
        // Add 20% per 5 years above 40
        int age = person.getAge() - 40;
        while (age >= 5) {
            premium *= 1.2;
            age -= 5;
        }
    }

    // Add gender specific adjustments
    if (person.getGender() == Gender.MALE) {
        premium *= 1.02;
    }

    // Increase 1% per health issue
    for (HealthIssues issue : person.getHealthIssues()) {
        premium *= 1.01;
    }

    Set<Habbits> habbitsList = person.getHabbits();
    // Decrease 3% per good habbit
    for (Habbits habbit : habbitsList) {
        if (Constants.goodHabbits.contains(habbit)) {
            premium *= 0.97;
        }
    }
    // Increase 3% per good habbit
    for (Habbits habbit : habbitsList) {
        if (Constants.badHabbits.contains(habbit)) {
            premium *= 1.03;
        }
    }

    return premium;
}

I only had three JUnits with different Personobjects initially. The reviewer mentioned if the JUnit failed, we wouldn't know exactly where it failed.

So I took cue & cut the various calculations & gave it its own method. Then called them in my original calculatePremium() method.

public double calculatePremium(Person person) {
    // Added base premium
    double premium = 5000;
    premium = this.applyAgeBasedCalcs(person, premium);
    premium = this.applyGenderBasedCalcs(person, premium);
    premium = this.applyHealthIssuesBasedCalcs(person, premium);
    premium = this.applyGoodHabbitsBasedCalcs(person, premium);
    premium = this.applyBadHabbitsBasedCalcs(person, premium);
    return premium;
}

And of course added JUnits for them (not an exhaustive set). So instead of testing only for the final answer, we're also testing if the individual calculating components are working fine or not.

Finally the reviewer mentioned that if he ever wanted to change the order or the number of apply* methods called (add new ones), but without changing this class every time, how would one do about it? He still may want to use this original version of the rules. I immediately explained the strategy pattern & upon request, implemented it.

I merely made an interface (PremiumCalculationStrategy) & a single class that implements it (NormalPremiumCalculationStrategy) for now.

public double calculatePremium(Person person) {
    // Added base premium
    double premium = 5000;
    premium = Rules.applyAgeBasedCalcs(person, premium);
    premium = Rules.applyGenderBasedCalcs(person, premium);
    premium = Rules.applyHealthIssuesBasedCalcs(person, premium);
    premium = Rules.applyGoodHabbitsBasedCalcs(person, premium);
    premium = Rules.applyBadHabbitsBasedCalcs(person, premium);
    return premium;
}

I made all the apply* methods static as I didn't see the need to instantiate a Rules object; there's no state & the method is functional.

Unfortunately, that wasn't well appreciated. He didn't like the static methods & said I broke all the OO principles. He suggested that I should make it more object-oriented. Additionally just because there's a class & interface, doesn't mean it's a strategy pattern.

I didn't understand the comments too well. Could someone review this & let me know of a good way to code this, or just why is my implementation so bad? What's a good way to make it more object-oriented, and what's the right usage of a strategy pattern?


texts: Checking whether a table has modified rows

texts:
The company I am with has a lot of old code migrated over from ALPHA Basic, written back in the 1980s. As development languages have evolved (should I say, "died off"?) the code has been migrated to newer languages.

The company also hires a lot of new graduates from a local college. Sometimes, the code is written in a textbook fashion. I see a lot of code that could be written differently.

Here is one piece of code that I have encountered in a project I maintain:

Public ReadOnly Property HasModifiedRows() As Boolean
    Get
        Dim dt As DataTable

        dt = Nothing
        Try
            dt = Me.GetTableObj.GetChanges(DataRowState.Modified)
            If dt IsNot Nothing Then
                Return True
            Else
                Return False
            End If
        Finally
            If dt IsNot Nothing Then
                dt.Dispose()
                dt = Nothing
            End If
        End Try
    End Get
End Property

The code looks deliberately spelled out, step for step. This could be to help our new developers understand what is going on, or it could be code that was migrated over from older languages that required all variables be defined at the top.

I do not know why, but seeing all of the unnecessary lines of code is like fingernails on a chalkboard.

My planned rewrite

I am constantly compelled to rewrite pieces of code like that above to this:

Public ReadOnly Property HasModifiedRows() As Boolean
    Get
        Using table As DataTable = GetTableObj.GetChanges(DataRowState.Modified)
            Return True
        End Using
        Return False
    End Get
End Property

Question and concerns

Is one design pattern better than another?
Is there a performance difference in the two?
Would my version with the using syntax have any unanticipated results?

As I understand the VB Using Statement, if an object enters a using block, it cannot be null and it will always dispose of itself whenever it goes out of scope. I could of course be wrong though. I do not know how to guarantee this in .Net.

Should I leave the old code alone?

If there is any benefit to rewriting it, I am certainly happier with the streamlined look.

I'd really like to get some opinions on if I am doing any good by changing the code. If I am doing harm, I certainly would like to know!


texts: Add one to a number represented as an array of digits

texts:
I submitted this problem for an interview, and I was wondering if I could have done better. My solution works, and I solved in about 12-15 minutes. I feel like I did a bad job with the code.  Please be honest.

Here is the question:

  Given a non-negative number represented as an array of digits, plus
  one to the number. Also, the numbers are stored such that the most
  significant digit is at the head of the list.

In particular, what stumped me was the fact that I'd get the right answer, but have the initial index (at 0) in sometimes empty with the answer on the other half, and couldn't figure out a quick half to shift all the elements to the left without using extra storage.

public int[] plusOne(int[] digits) {
    int[] toRet=new int[digits.length+1];
    int[] temp=null;

    for(int i=toRet.length-1; i>=0; i--){
        if(i-1>=0){
            toRet[i]=digits[i-1];
        }
    }
    for(int i=toRet.length-1; i>=0; i--){
        if(toRet[i]+1 == 10){
            toRet[i]=0;
        }
        else{
            toRet[i] = toRet[i]+1;
            break;
        }
    }
    if(toRet[0]==0){
        temp = new int[toRet.length-1];
        for(int i=1; i<toRet.length;i++){
            temp[i-1] = toRet[i];
        }
       return temp;
    }
    else{
        return toRet;
    }

}


texts: Increment each digit in a number to form a new number

texts:
Today I've found /r/dailyprogrammer and I've solved an easy challenge. I'm new to coding and I'm not sure if this is good way to solve this kind of problems. Could you, please, give me some hints? How to make my code more clear and readable? Thanks!

  Challange description:

  A number is input in computer then a new no should get printed by
  adding one to each of its digit. If you encounter a 9, insert a 10
  (don't carry over, just shift things around).

  For example, 998 becomes 10109.

  Bonus

  This challenge is trivial to do if you map it to a string to iterate
  over the input, operate, and then cast it back. Instead, try doing it
  without casting it as a string at any point, keep it numeric (int,
  float if you need it) only.

private static int Challange(int number)
        {
            int digits = (int)Math.Log10(number); //this is number of digits -1
            int result = 0;
            for (int i=0; i <= digits; i++)
            {
                int tens = (int)(Math.Pow(10, digits - i));
                int currentDigit = ((number / tens) % 10);

                if (currentDigit == 9) result *= 10;
                result += (currentDigit + 1) * tens;
            }
            return result;
        }


texts:
Print all the ways of arranging eight queens on an 8x8 board. Rules:
  Queens should not share the same row, column, of any diagonal.

Any comment on my solution?
I didn't write unit tests but I checked visually the solutions.

public class solution {

  public static void printMatrix(char[][] board) {
    // 8x8 board
    int n = board.length;
    System.out.println("------------------------------");
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        System.out.print(board[i][j] + "|");
      }
      System.out.println();
    }
    System.out.println("------------------------------");

  }

  public static void updateBoard(int row, int col, boolean[][] logicalBoard) {
    // Turn all the cases corresponding to the row, column and diagonals of the element added to
    // false
    // 8x8 board
    int n = logicalBoard.length;

    // update the row
    for (int j = 0; j < n; j++) {
      logicalBoard[row][j] = false;
    }

    // update the column
    for (int j = 0; j < n; j++) {
      logicalBoard[j][col] = false;
    }

    // update the diagonals
    int r = row;
    int c = col;
    while (r >= 0 && c >= 0) {
      logicalBoard[r][c] = false;
      r--;
      c--;
    }

    r = row;
    c = col;
    while (r < 8 && c < 8) {
      logicalBoard[r][c] = false;
      r++;
      c++;
    }

    r = row;
    c = col;
    while (r < 8 && c >= 0) {
      logicalBoard[r][c] = false;
      r++;
      c--;
    }

    r = row;
    c = col;
    while (r >= 0 && c < 8) {
      logicalBoard[r][c] = false;
      r--;
      c++;
    }
  }

  public static char[][] copyArray(char[][] original) {
    char[][] copy = new char[original.length][];
    for (int i = 0; i < original.length; i++) {
      copy[i] = original[i].clone();
    }
    return copy;
  }

  public static boolean[][] copyArray(boolean[][] original) {
    boolean[][] copy = new boolean[original.length][];
    for (int i = 0; i < original.length; i++) {
      copy[i] = original[i].clone();
    }
    return copy;
  }

  public static void arrangeQueens(char[][] board, boolean[][] logicalBoard, int rowNumber) {
    if (rowNumber == 8) {
      printMatrix(board);
      return;
    }

    int n = board.length;
    for (int column = 0; column < n; column++) {
      if (logicalBoard[rowNumber][column]) {
        char[][] newBoard = copyArray(board);
        boolean[][] newLogicalBoard = copyArray(logicalBoard);
        newBoard[rowNumber][column] = 'Q';
        newLogicalBoard[rowNumber][column] = false;
        updateBoard(rowNumber, column, newLogicalBoard);
        arrangeQueens(newBoard, newLogicalBoard, rowNumber + 1);
      }
    }
  }

  public static void arrangeQueens() {
    int N = 8;
    char[][] board = new char[8][8];
    boolean[][] logicalBoard = new boolean[8][8];
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
        board[i][j] = ' ';
        logicalBoard[i][j] = true;
      }
    }
    arrangeQueens(board, logicalBoard, 0);
  }

  public static void main(String[] args){
    arrangeQueens();
  }

}


texts: Cleaner way for coding a repetitive application of a function

texts:
I have this function definition which takes an r and applies the function f n times:

r => (1 to n).foldLeft(r)((rx, _) => f(rx))

So for n=3 this is equivalent to f(f(f(r)))

I don't like this solution, because it defines a Range from 1 to n which really isn't get used at all, which becomes obvious in the unused parameter _ in the fold left. This in turn forces me to give a separate name to rx which feels wrong to me.

Any idea how I can streamLine this code?


texts:
I recently heard about functional reactive programming and thought it was rather interesting. Therefore, I started out with writing a simple program which processes a list of tasks.

(In this example, the "tasks" are just some strings which need to be printed)

So because I have no idea how to do it "right" in frp and because I'm unexperienced in Haskell, I wanted to ask, whether someone wants to take a look at it and suggest some improvements.

(The code is heavily based on the Reactive Banana examples):

import Reactive.Banana
import Reactive.Banana.Frameworks

import Data.Maybe
import Data.Foldable

type Task = String

main :: IO ()
main = do
    let printTasks :: [Task]
        printTasks = ["Hi", "there!", "Hello", "FRP!"]

    eTrigger <- newAddHandler
    network <- setupNetwork eTrigger printTasks (taskHandler eTrigger)
    actuate network
    fire eTrigger ()

taskHandler :: EventSource () -> Task -> IO()
taskHandler eTrigger task = do
  print task
  fire eTrigger ()

{-----------------------------------------------------------------------------
    Event sources
------------------------------------------------------------------------------}
-- Event Sources - allows you to register event handlers
-- Your GUI framework should provide something like this for you
type EventSource a = (AddHandler a, a -> IO ())

addHandler :: EventSource a -> AddHandler a
addHandler = fst

fire :: EventSource a -> a -> IO ()
fire = snd

{-
    Helpers
-}

tryTail = drop 1
tryFst = listToMaybe
tryDo = traverse_

{-----------------------------------------------------------------------------
    Program logic
------------------------------------------------------------------------------}
-- Set up the program logic in terms of events and behaviors.
setupNetwork :: EventSource () -> [Task] -> (Task -> IO()) -> IO EventNetwork
setupNetwork eSource printTasks taskHandler = compile $ do
    eTrigger <- fromAddHandler (addHandler eSource)

    bTasks <- accumB ("":printTasks) $ tryTail <$ eTrigger
    let bTask = tryFst <$> bTasks

    eTasksChange <- changes bTask

    reactimate' $ fmap (tryDo taskHandler) <$> eTasksChange

The library: https://wiki.haskell.org/Reactive-banana