texts: Convert sum from monthly to quarterly values

texts:
I'm attempting to aggregate multiple columns of monthly data into quarterly chunks. Currently, I'm applying a rolling sum to the columns and then selecting only every third row to 'delete' or hide the rows.

I get the feeling that not only is there a far simpler approach, but there is a more Pythonic/Pandorable way of doing this.

import pandas as pd

data = pd.DataFrame({'parent_id': [1, 1, 1, 1, 1, 1, -99999, -99999, -99999],
                     'id': [123, 123, 123, 123, 123, 123, 123, 123, 123],
                     'data_1': [10, 20, 30, 40, 50, 60, 0, 0, 0],
                     'data_2': [10, 20, 30, 40, 50, 60, 0, 0, 0],
                     'period': [0, 1, 2, 3, 4, 5, 6, 7, 8],
                     'date': ['2017-06-30', '2017-07-31', '2017-08-31',
                              '2017-09-30', '2017-10-31', '2017-11-30',
                              '2017-12-31', '2018-01-31', '2018-02-28'],
                     'quarter': [0, 0, 0, 1, 1, 1, 2, 2, 2]})

def convert_to_quarterly(df, date):
    """Aggregates 3 months of data to a quarterly value."""
    columns = ['data_1', 'data_2']
    dates = pd.to_datetime(df['date'])
    quarter_end_dates = map(lambda offset: (date + pd.DateOffset(months=offset)).to_period('M').to_timestamp('M'), np.arange(0, 40, 3))
    df_grouped = df.groupby('id')
    #df[columns] = df_grouped[columns].apply(pd.rolling_sum, window=3, min_periods=1)
    return df.loc[df[dates.isin(quarter_end_dates)].index]

convert_to_quarterly(data, date=pd.to_datetime('2017-06-30'))

Before:

After:


texts: Calculation of lexicographic permutations

texts:
Just for fun, I studied the generation of lexicographic permutations and came across the following algorithm which I transcribed into Common Lisp, as good as I can, being a hobbyist:

(defun lexicographic-permutation% (order n)
  "Returns the Nth permutation of integers from 0 upto order."
  (let* ((range (loop :for i :upto order :collect i))
         (len (1+ order))
         (permutation (make-array len :initial-contents range)))
    (loop :while (< count n)
          :for count :from 1
          :for i = order
          :for j = len
          :do
          (loop :while (>= (aref permutation (1- i))
                           (aref permutation i))
                    :do (decf i))
          (loop :while (<= (aref permutation (1- j))
                           (aref permutation (1- i)))
                :do (decf j))
          (rotatef (aref permutation (1- i))
                   (aref permutation (1- j)))
          (incf i)
          (setf j len)
          (loop :while (< i j)
                :do (rotatef (aref permutation (1- i))
                             (aref permutation (1- j)))
                    (incf i)
                    (decf j))
          :finally (return permutation))))

While it is working and fast I am unsure about the explicit side-effects using setf and incf and the structure of the loops. I know that Common Lisp is not a strict functional language and allows several paradigmas which is considered to be an advantage. But I was asking myself if the algorithm could be written in a clearer idiom in CL.

I was thinking about packing the rotatef-pattern in an extra function which could be inlined. But this is not really what I am worried about, s. above. Furthermore the usage of loop itself is fine for me, because I like its DSL.


texts:
I'm remaking an old program of mine in Clojure. It involves "Beings" (generic entities capable of attacking and breeding) let loose in a confined space.

I've noticed a pattern of taking a record, creating a modified version of one of its fields, then "overwriting" the field.

It generally seems to look like:

(defn map-pts [p1 p2 f]
  (let [[x1 y1] p1
        [x2 y2] p2]
    [(f x1 x2) (f y1 y2)]))

(defn add-pts [p1 p2]
  (map-pts p1 p2 +))

(defrecord Being [position, health])

(defn hurt [being damage]
  (let [newHealth (- (:health being) damage)]           ;<<<
    (assoc being :health newHealth)))                   ;<<<

(defn move-by2 [being x y]
  (let [new-position (add-pts (:position being) [x y])] ; <<<
    (assoc being :position new-position)))              ; <<<

(I'm only including the first 2 functions so it's complete).

I decided to write a function to try and limit the boilerplate.

(defn update-with [m k k1->k2]
  (let [oldValue (get m k)]
    (assoc m k (k1->k2 oldValue))))

which can be used like:

(defn hurt2 [being damage]
  (update-with being :health
                 #(- % damage)))

(defn move-by [being x y]
  (g/update-with being :position
                 #(add-pts % [x y])))

which I find to be significantly cleaner.

What I want comments on:

Am I thinking about this is the right way? Is this something I should be worrying about, or is this an xy problem?
Is k1->k2 an appropriate name? It seems like a very self-documenting way of indicating what type of function is needed, but is also "Hungarian", which I know is frowned upon.
This seems like something that would be included in the langage given its simplicity. Does this function already exist?

An example of how it will be used (non-functioning code, since some components aren't yet defined):

(def beings ['(all the beings in the world)])

(map (fn [being]
       (do
         (if (is-contacting-other? being beings)
           (hurt being 20)                        ; <<---
           being))))

In reality, I'll be giving the job of calling hurt to a helper function attack that will decide how much damage to do. This same loop will also handle other things, so it will be a little more complex. This is just a stripped-down example.


texts:
I want to generate a sequence using Linq that goes from 10 to 100 with a step size of 10. The sequence also must contain a custom value (in the correct order).

This is what I have now, and I'm wondering if there is a smarter way of doing it using Linq expressions.

var pageSize = 25; //number that must be in sequnce if not already, can be anything.
var items = Enumerable.Range(10, 100)     //Generate range
           .Where(x => x % 10 == 0)       //Take every 10th item
           .Concat(new[] { pageSize })    //Add the custom number
           .Distinct()                    //If the custom number was already in there, remove it
           .OrderBy(x => x);              //Sort the sequence

Result:

10
20
25
30
40
50
60
70
80
90
100


texts: Is this non-recursive mergesort efficient and a good way to simulate the recursive version?

texts:
My teacher assigned us to do the recursive version of mergesort, yet I heard that the non-recursive version (bottom up) is a bit tougher, so I decided to this one as well. My main concerns are:

Considering the way I coded it, does it still have the same efficiency?
Did I do this in an acceptable way? If not, why?

Main:

    Random rand = new Random();
    ArrayList<Integer> array = new ArrayList<Integer>();
    for (int i = 0; i < 100; i++){
        array.add(rand.nextInt(20));
    }
    System.out.println("Original:");
    for (int num: array){
        System.out.print(" " + num);
    }
    Algorithm algo = new Algorithm(array);
    algo.print();

Code:

ArrayList<Integer> ar = new ArrayList<Integer>();
int loBound = 0, hiBound = 1;
public Algorithm(ArrayList<Integer> initAr){
    ar = initAr;
    partition();
}
public void partition(){
    if (ar.size() > 1){
        int partitionSize = 1;
        int arraySize = ar.size();

        if (ar.size() % 2 != 0) // if the size is odd make it even so loop doesn't terminate early without sorting all values
            arraySize++;

        while (arraySize / 2 >= partitionSize){
            while (true){
                ArrayList<Integer> left = new ArrayList<Integer>();
                ArrayList<Integer> right = new ArrayList<Integer>();
                // Variables which will be sent to 'update' method as parameters. Tells method which indexes to update (in-between low and high)
                int loInd = loBound, hiInd;
                for (int i = loBound; i < hiBound; i++){
                    left.add(ar.get(i));
                }
                calcBounds(partitionSize);
                for (int j = loBound; j < hiBound; j++){
                    right.add(ar.get(j));
                }
                hiInd = hiBound;
                if (right.size() != partitionSize){
                    update(left, right, loInd, hiInd);
                    break;
                }
                update(left, right, loInd, hiInd);
                calcBounds(partitionSize);
            }
            partitionSize*=2;
            loBound = 0;
            hiBound = partitionSize;
        }
    }
}
// calculates the indexes from which I will extract from the original array
private void calcBounds(int partitionSize){
    if (ar.size() - hiBound > partitionSize){
        loBound = hiBound;
        hiBound = loBound + partitionSize;
    }else {
        loBound = hiBound;
        hiBound = ar.size();
    }
}
// updates original ArrayList after sorting 'left' and 'right'
private void update(ArrayList<Integer> left, ArrayList<Integer> right, int loInd, int hiInd){
    // sort
    ArrayList<Integer> result = new ArrayList<Integer>();
    int lIndex = 0, rIndex = 0, resIndex = 0;
    while (lIndex < left.size() || rIndex < right.size()){
        if (lIndex < left.size() && rIndex < right.size()){
            if (left.get(lIndex) <= right.get(rIndex)){
                result.add(resIndex, left.get(lIndex));
                resIndex++;
                lIndex++;
            }else {
                result.add(resIndex, right.get(rIndex));
                resIndex++;
                rIndex++;
            }
        }else if (lIndex < left.size()){
            result.add(resIndex, left.get(lIndex));
            resIndex++;
            lIndex++;
        }else if (rIndex < right.size()){
            result.add(resIndex, right.get(rIndex));
            resIndex++;
            rIndex++;
        }
    }
    // update original ArrayList using result ArrayList
    int count = 0;
    for (int i = loInd; i < hiInd; i ++){
        ar.set(i, result.get(count));
        count++;
    }
}

void print(){
    System.out.println();
    System.out.println("Sorted:");
    for (int num: ar){
        System.out.print(" " + num);
    }
}


texts: Project Euler 34 # Digit Factorials in Python

texts:
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.

from time import time

def fact(n):
    """returns factorial of n."""
    total = 1
    for number in range(2, n + 1):
        total *= number
    return total

def fact_curious(n, factorials={1:1, 2:2}):
    """Assumes n is the range to check for curious numbers.
    generates curious numbers within n range."""
    for number in range(3, n):
        try:
            if sum(factorials[int(digit)] for digit in str(number)) == number:
                yield number
        except KeyError:
            for digit in str(number):
                factorials[int(digit)] = fact(int(digit))
            if sum(factorials[int(digit)] for digit in str(number)) == number:
                yield number

if __name__ == '__main__':
    start_time1 = time()
    print(sum(fact_curious(100000)))
    print(f'Time: {time() - start_time1}')


texts:
How can I make the following PHP code better, more efficient, shorter, elegant, etc?  While it already works, I am still learning PHP and want to improve upon my current code:

<?php

$query = 'psoriasis';

$eSearchQueryParameters = array(
    'db' => 'pubmed',
    'term' => $query,
    'retmode' => 'xml',
    'retstart' => '0',
    'retmax' => '500',
    'usehistory' => 'y',
);

$eSearchQueryResults = simplexml_load_file('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?' . http_build_query($eSearchQueryParameters));

$eFetchQueryParameters = array(
    'db' => 'pubmed',
    'retmax' => '500',
    'query_key' => (string) $eSearchQueryResults->QueryKey,
    'WebEnv' => (string) $eSearchQueryResults->WebEnv,
);

$eFetchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' . http_build_query($eFetchQueryParameters);
$matches = array();
preg_match_all('/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/', file_get_contents($eFetchURL), $matches);

foreach ($matches[0] as $key => $value) {
    echo $value . "<br />";
}

?>


texts: Find all possible sumation numbers to a specified sum

texts:
This is a problem that I had in mind for a loong time and today I decided to give it a go, the basic idea is you enter a number/sum and the program outputs all the possible ways this sum can be formed let's say we have 3 as input the output will be (1, 1, 1),(1, 2) I don't think that the code is really efficient so any tips are appreciated.

    static void Main(string[] args)
    {
        int sum = int.Parse(Console.ReadLine());
        List<List<int>> subsets = GetSubsets(sum);
        for (int i = 0; i < subsets.Count; i++)
        {
            Console.WriteLine(string.Join(",", subsets[i]));
        }
        Console.ReadKey();
    }

    private static List<List<int>> GetSubsets(int sum)
    {
        List<List<int>> subsets = new List<List<int>>();
        int[] allNumbers = new int[sum - 1];
        List<int> baseSubset = PopulateWith(1, allNumbers.Length + 1);
        int baseNumberIndex = 0;
        int additiveNumberIndex = 1;
        for (int i = 0; i < allNumbers.Length; i++)
        {
            allNumbers[i] = i + 1;
        }
        if (sum > 1)
        {
            // if 1 is entered as a sum we dont want to return 1 as result because that's not a sum of numbers it's just 1.
            subsets.Add(baseSubset);
        }
        while (baseNumberIndex < allNumbers.Length && additiveNumberIndex < allNumbers.Length)
        {
            List<int> currentSubset = PopulateWith(allNumbers[baseNumberIndex], (int)Math.Round((double)sum / allNumbers[baseNumberIndex]));
            int currentSum = currentSubset.Sum();
            while (true)
            {
                if (currentSum + allNumbers[additiveNumberIndex] > sum)
                {
                    currentSubset.Remove(allNumbers[baseNumberIndex]);
                }
                else
                {
                    currentSubset.Add(allNumbers[additiveNumberIndex]);
                }
                currentSum = currentSubset.Sum();
                if (currentSum == sum && !subsets.Any(seq => seq.SequenceEqual(currentSubset)))
                {
                    subsets.Add(currentSubset.ToList());
                }
                if (currentSum + allNumbers[additiveNumberIndex] > sum && !currentSubset.Contains(allNumbers[baseNumberIndex]))
                {
                    break;
                }
            }
            additiveNumberIndex++;
            if (additiveNumberIndex == allNumbers.Length)
            {
                baseNumberIndex++;
                additiveNumberIndex = baseNumberIndex + 1;
            }
        }
        return subsets;
    }

    private static List<int> PopulateWith(int number, int size)
    {
        List<int> collection = new List<int>();
        for (int i = 0; i < size; i++)
        {
            collection.Add(number);
        }
        return collection;
    }


texts:
I have been building an API in Go, which I want to link to a Postgres SQL table. I have always used NoSQL previously but thought it would be good to try a SQL database.
Here are my structs
type Activity struct {
    Activity string `json:"activity"`
    Payload Payload `json:"payload"`
}

type Payload  struct {
    UserID   string `json:"userId"`
    Duration int    `json:"duration"`
    Type     string `json:"type"`
    Date     int    `json:"date"`
}

Based on the above I thought it would be good to have a table for payload which was made via the following query.
CREATE TABLE payload (
    userid SERIAL PRIMARY KEY,
    duration INT,
    type TEXT,
    date INT
);

and then created the activity table like the following:
CREATE TABLE activity (
    activity TEXT PRIMARY KEY
    SELECT userid, duration, type, date
    FROM payload;
);


texts: Set Label content and make it disappear after 5 seconds

texts:
Let's say I have a label and a button. If I click the button, the label is set to some text, say "hello, world!", and after 5 seconds, it should disappear. Easy enough, right? I have the following implementation:

private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
  Label = "hello, world!";
  await Task.Delay(5_000);
  Label = string.Empty;
}

Now let's say I have the additional requirement that the button should remain responsive on each subsequent button click, and now the label text should remain hello, world! for the next 5 seconds i.e. the label text should remain for 5 seconds since the last time the button was clicked. The problem with the previous code is that if I had clicked the button 2.5 seconds ago and click it again now, the label text will disappear after 2.5 seconds. My idea to solve this was to maintain a list of tasks and add the delay task and await the task list before clearing the label. This is the implementation:

private static readonly List<Task> TaskList = new List<Task>();
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
  Label = "hello, world!";
  TaskList.Add(Task.Delay(5_000));
  await Task.WhenAll(TaskList);
  if (TaskList.TrueForAll(t => t.IsCompleted))
  {
    TaskList.RemoveAll(t => t.IsCompleted);
    Label = string.Empty;
  }
}

Implementation with a cancellation token:

private static CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
  Label = "hello, world!";
  _cancellationTokenSource.Cancel();
  _cancellationTokenSource = new CancellationTokenSource();
  try
  {
    await Task.Delay(5_000, _cancellationTokenSource.Token);
    Label = string.Empty;
  } catch (TaskCanceledException) { }
}

As far as I know, these implementation works, but I don't know much about asynchronous programming so I don't know how to be absolutely sure it works.

Questions:
How would you implement this? Is there a better way to implement this? I originally figured that Task.WhenAll() would take care of waiting for all tasks to complete, but this does not seem to be the case. What am I getting wrong?


texts:
I'm wondering if my approach to creating a filtered array (filteredLaunches) from an array of data (launches) is an anti-pattern, or not? Is there a better way to go about it?

Here is the code:

const initialState = {
  launches: [],
  filteredLaunches: []
};

export default function(state = initialState, action) {

  switch (action.type) {

    case 'getLaunches':
      return Object.assign({}, state, {
        launches: action.launches
      });

    case 'filterLaunches':

      let filteredLaunches = [];

      for (let i = 0; i < state.launches.length; i++) {
        if (action.location === state.launches[i].location.countryCode)
          filteredLaunches.push(state.launches[i]);
      }

      return Object.assign({}, state, {
        filteredLaunches: filteredLaunches
      });

    default:
      return state;
  }
};


texts:
Given a text, this program will output a Brainfuck program, that when executed will print the text back.

  Writing Brainfuck in this style to print a sentence is pretty straightforward. Iterate over the sentence and do the following per character:

  Calculate the difference between the current character and the previous
  Write either as many + or - as the difference between characters. + if current character is higher than previous character, - if lower than previous character
  Write . to print current character

Hello, World!

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
+++++++++++++++++++++++++++++.
+++++++.
.
+++.
-------------------------------------------------------------------.
------------.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++.
+++.
------.
--------.
-------------------------------------------------------------------.

The code

def brainturing_printer_generator(text)
  ords = text.chars.map(&:ord)
  ("+" * ords.first + ".\n") + ords
    .zip(ords[1..-1])
    .take(ords.size - 1)
    .map {|prev, curr| (curr > prev ? "+" : "-") * (curr - prev).abs}
    .join(".\n") + ".\n"
end

print brainturing_printer_generator("Hello, World!")


texts: Meta-programming template for collection statistics

texts:
I find that I often want to calculate summary statistics from collections of data and decided to create a template to do that.  I'm interested in a general review, but I also have some specific questions.

Is the use of the lambda "too clever?"
Is std::accumulate OK?  Specifically, I'm thinking of the potential for overflow for large collections of small data types.
Is the template missing anything?
Should I be using something such as std::enable_if to assure that the Iter type is actually an iterator?

The code to be reviewed is in stats.h but stats.cpp shows how it can be used.

stats.h

#ifndef STATS_H
#define STATS_H
#include <cmath>
#include <numeric>
#include <iterator>

template <typename T, typename Iter>
struct Statistics {
    Statistics(Iter start, Iter end, bool sample=true) :
        n(std::distance(start, end)),
        sum(std::accumulate(start, end, 0)),
        mean(sum / n),
        variance([&start, &end, sample, this]()->T {
                T sumsq = 0;
                for (auto it=start; it != end; ++it) {
                    sumsq += (*it-mean)*(*it-mean);
                }
                return sumsq/(n- (sample ? 1 : 0));
            }()
        ),
        sdev(sqrt(variance))
    {
    }
    unsigned n;
    T sum;
    T mean;
    T variance;
    T sdev;
};
#endif //STATS_H

stats.cpp

#include <iostream>
#include <vector>
#include <list>
#include "stats.h"

template <typename T>
std::ostream &print(std::ostream &out, const T &stats) {
    out << "n = " << stats.n << '\n';
    out << "sum = " << stats.sum << '\n';
    out << "mean = " << stats.mean << '\n';
    out << "var = " << stats.variance << '\n';
    out << "sdev = " << stats.sdev << '\n';
    return out;
}

int main()
{
    std::vector<int> sample{9, 2, 5, 4, 12, 7};
    Statistics<float, decltype(sample.cbegin())> stats(sample.cbegin(), sample.cend());
    print(std::cout, stats);

    std::list<float> sample2{2.0, 4.0, 5.0, 7.0, 9.0, 12.0};
    Statistics<double, decltype(sample2.cbegin())> stats2(sample2.cbegin(), sample2.cend());
    print(std::cout, stats2);
}

Sample output

n = 6
sum = 39
mean = 6.5
var = 13.1
sdev = 3.61939
n = 6
sum = 39
mean = 6.5
var = 13.1
sdev = 3.61939


texts:
My current student accommodation uses a manual paper and pen system for checking if students have mail so I made this simple Python script to help mitigate the problem of manually searching through spreadsheets just to see if you have mail or not, which I have been asked to demo soon. It's quite basic but I figured I should probably get it code reviewed since it may get real world usage.

GitHub

import json
import os

if not os.path.isfile('parcels.json'):
    open('parcels.json', 'w').write(json.dumps({}))
parcels = json.loads(open('parcels.json').read())

def add(student_id, new_letters, new_parcels):
    if student_id in parcels:
        parcels[student_id][0] += new_letters
        parcels[student_id][1] += new_parcels
    else:
        parcels[student_id] = [new_letters, new_parcels]

def collect(student_id):
    if student_id in parcels:
        parcel_info = 'Letter: ' + str(parcels[student_id][0]) + ' Parcel: ' + str(parcels[student_id][1])
        del parcels[student_id]
        return parcel_info
    else:
        return 'Letter: 0 Parcel: 0'

print('1. Add\n2. Collect')
option = input('Option: ')
student_id = input('Student ID: ')

if len(student_id) != 7:
    print('Invalid input! (student ID must be 7 digits long)')
    raise SystemExit(1)
try:
    if int(student_id) < 0:
        print('Invalid input! (student ID must be a non-negative integer)')
        raise SystemExit(1)
except ValueError:
    print('Invalid input! (student ID must be an integer)')
    raise SystemExit(1)

if option == '1':
    try:
        new_letters = int(input('Letters: '))
        new_parcels = int(input('Parcels: '))
    except ValueError:
        print('Invalid input! (only integers allowed)')
        raise SystemExit(1)

    if new_letters < 0 or new_parcels < 0:
        print('Invalid input! (only non-negative integers allowed)')
        raise SystemExit(1)

    add(student_id, new_letters, new_parcels)
elif option == '2':
    print(collect(student_id))
else:
    print('Invalid option!')

open('parcels.json', 'w').write(json.dumps(parcels))


texts:
I made a triple-type container, that is, a single type that can store a value, under one of the three types used. It's somewhat similar to Boost::Variant.

The header file (multitype.hpp):

#ifndef MULTITYPE_HPP
#define MULTITYPE_HPP

#include <iostream>
#include <cstdlib>
#include <typeinfo>

typedef void* vp_t; // Void pointer (can contain every type)

template <typename _A,typename _B> struct is_same_type  { const static bool value = false; };
template <typename _A> struct is_same_type<_A,_A>       { const static bool value = true;  };

template <class A,class B,class C>
class TripleType
{
    protected:
        enum ct_t { _tA, _tB, _tC, _init_ }; // Type flags
        struct abc_t
        {
            A __a;         // A container
            B __b;         // B container
            C __c;         // C container
            ct_t _e; // Which type is the current one?
        };
    private:
        abc_t val;
    public:
        TripleType()
        {
            (this->val)._e = _init_;
        }
        template <class T> TripleType(T x)
        {
            vp_t yv; yv = &x;
            bool is_A = is_same_type<T,A>::value;
            bool is_B = is_same_type<T,B>::value;
            bool is_C = is_same_type<T,C>::value;
            if      (is_A) { A *t = static_cast<A*>(yv); val.__a = *t; val._e = _tA; }
            else if (is_B) { B *t = static_cast<B*>(yv); val.__b = *t; val._e = _tB; }
            else if (is_C) { C *t = static_cast<C*>(yv); val.__c = *t; val._e = _tC; }
        }
        template <class T> TripleType& operator=(T rhs)
        {
            vp_t yv = &rhs;
            bool is_A = is_same_type<T,A>::value;
            bool is_B = is_same_type<T,B>::value;
            bool is_C = is_same_type<T,C>::value;
            if      (is_A) { A *t = static_cast<A*>(yv); (this->val).__a = *t; (this->val)._e = _tA; }
            else if (is_B) { B *t = static_cast<B*>(yv); (this->val).__b = *t; (this->val)._e = _tB; }
            else if (is_C) { C *t = static_cast<C*>(yv); (this->val).__c = *t; (this->val)._e = _tC; }
            return *this;
        }
        template <class T> T get()
        {
            vp_t yv;
            bool is_A = is_same_type<T,A>::value;
            bool is_B = is_same_type<T,B>::value;
            bool is_C = is_same_type<T,C>::value;
            if      (is_A) yv = &(val.__a);
            else if (is_B) yv = &(val.__b);
            else if (is_C) yv = &(val.__c);
            T *t = static_cast<T*>(yv);
            return *t;
        }
        const std::type_info& current_type()
        {
            if      ((this->val)._e == _tA)
                return typeid(A);
            else if ((this->val)._e == _tB)
                return typeid(B);
            else if ((this->val)._e == _tC)
                return typeid(C);
        }
};

#endif

Here is an usage example:

#include <iostream>
#include <cstdlib>
#include <string>
#include "multitype.hpp" // The header file where I wrote the mentioned container

using namespace std;

int main()
{
    srand(time(NULL));
    TripleType<int,string,float> test;
    test = rand();
    cout << test.get<int>() << endl;
    test = string("TripleType test");
    cout << test.get<string>() << endl;
    test = float(1.6108);
    cout << test.get<float>() << endl;
    test = 2016;
    cout << test.get<int>() << endl;
    test = string("Bye.");
    cout << test.get<string>() << endl;
}

Any improvements, suggestions, etc. are welcome.


texts: Find the starting indices of all occurrences of the pattern in the string - KMP algorithm follow-up

texts:
The task

was initially solved here, but was too buggy:

  Given a string and a pattern, find the starting indices of all
  occurrences of the pattern in the string. For example, given the
  string "abracadabra" and the pattern "abr", you should return [0, 7].

My solution

Tried to solve it using KMP-algorithm:

function findStartingIndex(T, pattern) {
  if (pattern.length > T.length) { return []; }

  let next = 0;
  const res = [];

  const check = i => {
    for (let j = 1; j < pattern.length; j++) {
      if (next <= i && T[i + j] === pattern[0]) { next = i + j - 1; }
      if (T[i + j] !== pattern[j]) { return false; }
    }
    if (next <= i) { next = i + pattern.length - 1; }
    return true;
  };

  for (let i = 0; i < T.length; i++) {
    if (i + pattern.length > T.length) { return res; }
    if (T[i] === pattern[0] && check(i)) { res.push(i); }
    i = next;
  }
  return res;
}


texts: Creating remote directories in a bash script via ssh (with error trapping)

texts:
I'd like to create directories on a remote VM, but only if they do not exist. What's more, if creating the directory results in an error (exit status != 0) I'd like the script to exit as well, or at least print an error. Is there a more succinct way to do this than what I have below?

UPDATE: Just to clarify, I want to test -d first so mkdir -p won't produce output about the directory already existing.

#!/bin/bash

mydirs=(/var/www/files /var/www/photos /var/www/info)
for d in ${mydirs[@]}; do
   ssh remotehost "test -d $d"
   res=$?
   test $res -ne 0 && { ssh remotehost "mkdir -p $d"; res=$?; }
   test $res -ne 0 && { echo "error during mkdir on remote"; exit 1; }
done


texts: ActiveRecord selection, modified by optional parameters

texts:
I have an action method in my Rails controller which filters an ActiveRecord model depending on the submitted GET parameters.
Rubocop complains that Assignment Branch Condition Size is too high: 20.62/15.

Is there a way to improve the following code?

@measurements = Measurement.all
@measurements = @measurements.where(sensor_id: params[:sensor_id].split(',')) if params[:sensor_id].present?
@measurements = @measurements.last_per_sensor(params[:last_per_sensor]) if params[:last_per_sensor].present?
@measurements = @measurements.last(params[:last]) if params[:last].present?


texts: C++ object pool using C memory pool as base

texts:
I started out with this question on Stack Overflow. I have since then gotten an official answer from the mbed developers that the MemoryPool that I was asking about only issued raw C malloc/free type of memory.

Now, I'm thinking about how to create a C++ allocator using the existing MemoryPool. I'm using Google Mock to assist in my development on my desktop machine. I have the following code working with hi-perf dependency injection.

#include <new>
#include <utility>

template <typename T, template <typename O> class Pool>
struct ObjectAllocator {

    template <typename... Args>
    T* alloc(Args&&... args) {
        auto alloc = static_cast<void*>(pool.alloc());
        return alloc ? new(alloc) T(std::forward<Args>(args)...) : nullptr;
    }

    void free(T* object) {
        object->~T();
        pool.free(object);
    }

    Pool<T> pool;
};

Now, I'm wondering if it's really this simple. I'll be compiling for a 32-bit ARM platform with ARM-GCC6. The real memory pool guarantees 4-byte alignment so I believe any object would be safe.

Is there anything that I'm overlooking in this implementation, in terms of whether there are any edge cases that would present problems or need particular attention?

I don't intend to create array types with this implementation.


texts: Sass code for displaying two simple search forms

texts:
Sass code for creating a basic search box. Resulting CSS used for two that are different widths.

The goals is to define sass that generates CSS that is easily re-usable as well as concise and efficient and to keep the initial definitions as DRY as possible.

Review:

Coding style
Re-usability
DRY principles

SASS:

$container-width:940px;
$search-container-padding:54px;
$form-width:$container-width - ($search-container-padding * 2);
$form-height:47px;
$button-width:118px;

$search-container-background:#e9e9e9;
$form-background:#fff;
$input-border:1px solid #dadadc;
$focus-border:1px solid #052546;
$input-br:4px;
$input-inset:15px;

/*
    input width, sets the width of an imput and adds polyfill placeholder correctly
*/
@mixin input-width($width)
{
    .search-input
    {
        width:$width;
    }
    .search-placeholder
    {
        left:$form-width - $width - $button-width + $input-inset;
    }
}

.search-container
{
    box-sizing:border-box;

    width:$container-width;

    background-color:$search-container-background;

    padding:30px $search-container-padding 0;
}
.case-search-container
{
    padding-bottom:20px;
}
.book-search-container
{
    height:124px;
}

.search-form
{
    box-sizing:padding-box;

    width:$form-width;
    height:$form-height;

    position:relative;

    background-color:$form-background;

    border:5px solid $form-background;
    border-radius:6px;

    input[type=submit],
    button[type=submit]
    {
        width:$button-width;
        height:$form-height;

        position:absolute;
        top:0;
        right:0;

        background:image-url("structure/button-sprite.png") 0px 0px no-repeat;
        cursor:pointer;

        border:0px;

        color:#fff;
        font-weight:bold;
        text-transform:uppercase;

        &:hover{
            background-position:0px 0 - $form-height;
        }
    }

    .text
    {
        input
        {
            box-sizing:border-box;

            height:$form-height;

            position:absolute;
            top:0;
            right:$button-width;

            border-top:$input-border;
            border-bottom:$input-border;
            border-left:$input-border;
            border-radius:$input-br 0 0 $input-br;
            margin:0;
            padding:10px $input-inset;

            &:focus
            {
                outline:none;
                border:$focus-border;
            }

        }
    }

    .search-placeholder
    {
        position:absolute;
        top:13px;
        z-index:10;

        font-size:15px;
    }
}

/* specific width over-rides and label placement relative to this */
.book-search-form
{
    @include input-width(714px);
}
.case-search-form
{
    @include input-width(455px);
}

HTML:

    <form class='search-form'>

            <input class='search-input' type='text' ... />

            <input type='submit' ... />

    </form>

    <form class='search-form'>

            <input class='search-input' type='text' ... />

            <input class='submit' ... />

    </form>


texts:
For some memory masking operations I need a bitwise-rotation functionality for unsigned integral types. I came across solutions based on the wiki article, but have not found a variation for a function for bitwise-rotation within an "arbitrary" field of bits. Therefore, I have extended the solution of John Regehr, and now I want some feedback from you. I would also appreciate any advice on using mechanisms provided by the C++ core language up to C++14 (without the use of the std namespace).

#include <iostream>
#include <vector>
#include <bitset>

uint64_t CircShift (uint64_t x, uint8_t n, uint8_t bitwidth)
{
  return ((x<<n)&((1<<bitwidth)-1)) | (x>>(bitwidth-n));
}

int main()
{
    uint64_t var=0b000110100110;
    var=CircShift(var,2,9);
    std::cout<<std::bitset<12>(var);

}


texts: Updating a JavaFX ListView after service update

texts:
I wrote a JavaFX program that contains a list of notes, each having a title and a content.

This is the controller code:

public class MainPresenter implements Initializable
{
    @FXML
    private ListView<Note> listView;

    @FXML
    private TextField titleField;
    @FXML
    public TextArea contentField;
    @FXML
    public Button saveButton;

    @Inject
    private NoteService noteService;

    @Override
    public void initialize( URL location, ResourceBundle resources )
    {
        listView.setCellFactory( param -> new NoteListCell() );
        listView.setItems( FXCollections.observableArrayList( noteService.getNotes() ) );
        listView.getSelectionModel().selectedItemProperty().addListener( new NoteListViewSelectionChangeListener() );

        selectFirstItemIfPossible();

        saveButton.setOnAction( event -> {

            // Save the updated note with the service
            Note note = new Note( listView.getSelectionModel().getSelectedItem().getId(),
                                  titleField.getText(),
                                  contentField.getText() );
            noteService.updateNode( note );

            // Update the view
            int selectedIndex = listView.getSelectionModel().getSelectedIndex();
            listView.setItems( FXCollections.observableArrayList( noteService.getNotes() ) );
            listView.getSelectionModel().select( selectedIndex );

        } );
    }

    private void selectFirstItemIfPossible()
    {
        if (listView.getItems().size() > 0)
        {
            listView.getSelectionModel().select( 0 );
        }
    }

    private static class NoteListCell extends ListCell<Note>
    {
        @Override
        protected void updateItem( Note item, boolean empty )
        {
            super.updateItem( item, empty );
            if (item != null)
            {
                setText( item.getTitle() );
            }
        }
    }

    private class NoteListViewSelectionChangeListener implements ChangeListener<Note>
    {
        @Override
        public void changed( ObservableValue<? extends Note> observable, Note oldValue, Note newValue )
        {
            if( newValue != null )
            {
                titleField.setText( newValue.getTitle() );
                contentField.setText( newValue.getContent() );
            }
        }
    }
}

I am mainly looking for feedback on the code that gets run when you click on the save button:

saveButton.setOnAction( event -> {

            // Save the updated note with the service
            Note note = new Note( listView.getSelectionModel().getSelectedItem().getId(),
                                  titleField.getText(),
                                  contentField.getText() );
            noteService.updateNode( note );

            // Update the view
            int selectedIndex = listView.getSelectionModel().getSelectedIndex();
            listView.setItems( FXCollections.observableArrayList( noteService.getNotes() ) );
            listView.getSelectionModel().select( selectedIndex );

        } );

I now need to re-fetch all notes from the noteService again to be able to update the list view. I guess there is a better way to do it?


texts:
Any suggestions?

#include<iostream>

using namespace std;

class node
{
        friend class linked;

        private:
                int data;

        public:
                node *link;
                node()
                {
                        data=0;
                        link=NULL;

                }

};
class linked
{
        public:
                node *start=NULL;
                node *ptr;
                node *temp=NULL;

                void append(int item);
                void traverse();

};

void linked::append(int item)
{
        ptr = new node();
        ptr->data=item;
        if(start==NULL)
        {
                start=ptr;
                ptr->link=NULL;
                temp=start;

        }
        else
        {
                while(temp->link!=NULL)
                {
                     temp=temp->link;

                }
                temp->link=ptr;
                ptr->link=NULL;

         }

}
void linked::traverse()
{
        node *trav=start;
        while(trav!=NULL)
        {
                cout<<trav->data<<endl;
                trav=trav->link;
        }

}
int  main()
{
        int i;

        linked box;

        for(i=0;i<10;i++)
        {
           box.append(i);

        }

        box.traverse();
}


texts: Finding a delimiting character in a text file

texts:
I am writing a program that is capable of reading a matrix supplied from a text file. One intended feature of this program is that it should be capable of detecting various delimiters in the text file.

So, for example, these inputs should be interpreted equally:

1,2,3,4
5,6,7,8
9,10,11,12

1:2:3:4
5:6:7:8
9:10:11:12

My code for detecting the delimiting character is as follows:

#include <stdio.h>
#include <limits.h>

static int isNumeric(unsigned char c)
{
    switch(c) {
    case '.':
    case '0' ... '9':
        return 1;
    default:
        return 0;
    }
}

unsigned char findDelimeter(FILE * f)
{
    rewind(f);
    int c;
    unsigned char delimeter = '\0';
    long long int frequencies[UCHAR_MAX] = { 0 };
    long long int maxFrequency = 0;
    while ((c = fgetc(f)) != EOF) {
        frequencies[c]++;
    }
    for (c = 0; c < UCHAR_MAX; c++) {
        if (frequencies[c] > maxFrequency && !(isNumeric(c) || c == '\n')) {
            maxFrequency = frequencies[c];
            delimeter = c;
        }
    }
    return delimeter;
}

I have a few concerns about this code:

Are the large data types, like long long int necessary in the findDelimeter function? Would it be better to use the types defined in stdint.h, like uint64_t? My intention was to support very large files.
How can I deal with the situation where an arbitrary number of spaces follow a delimiting character?

Regarding the last point, I would also like my code to be able to deal with text files that may use a space or a non-space delimiter followed by an arbitrary number of spaces. For example, the following inputs should be interpreted equally:

1 2 3 4
5 6 7 8
9 10 11 12

1,   2,  3,     4
5,6,  7,      8
9,    10, 11,12

Currently, it detects the delimiter as the most frequent, non-numeric character. So in the last example, it would detect the space character as the delimiter since it is the most common non-numeric character, and it would mistakenly include the comma as part of the number when interpreting it. One solution that I thought of was modifying the findDelimeter function to return a string (er, character array), but I anticipate that would not be able to deal with an arbitrary number of spaces.

Also, as usual, I very much appreciate any stylistic comments or potential bugs.


texts: Convert light-years to other representations

texts:
the code is very messy, long and I am looking how to shorten it and/or simplify it. There are a lot of repeated variables, for example; 'hourToDay' and then 'hourToDay1', 'hourToDay2' and so forth. Can you help me find a better way to make this program more efficient?

P.S - I am a new coder and wanting to improve my ability, any suggestions would be grand :)

long lightYear = 6000000000000L;
int hoursInDay = 24;
int daysInYear = 365;
int yearsInCentury = 100;
int yearsInMillenium = 1000;

Scanner lightYearInput = new Scanner(System.in);
System.out.println("Enter light year's you'd like to convert" );

long light = lightYearInput.nextLong();
long totalLightYear = (long) (lightYear * light);

// Different vehicle variables with speed.

double car  = 277.87; //mph koenigseggAgeraRS
double MiG25 = 1919.42; //mph
double parkerSpaceProbe = 213240; //mph

// car conversion
long hourConversion = (long)(totalLightYear / car );
System.out.println("Driving the fastest car in space, would take you " + hourConversion + " hours to travel " + light + " light years."); //hours

long hourToDay = hourConversion / hoursInDay;
System.out.println(hourConversion + " hours is equivalent to " + hourToDay + " days."); //hours to days

long dayToYear = hourToDay / daysInYear;
System.out.println(hourToDay +" is equivalent to " + dayToYear + " years."); //days to years

long yearToCentury = dayToYear / yearsInCentury;
System.out.println(dayToYear +" is equivalent to " + yearToCentury + " Centuries."); //years to centuries

long yearToMillenium = yearToCentury / yearsInMillenium;
System.out.println(yearToCentury +" is equivalent to " + yearToMillenium + " millenium.\n"); // centuries to millenium

//MiG25 Conversion

System.out.println("PLANE");
long hourPlaneConversion = (long)(totalLightYear / MiG25 );
System.out.println("Driving the fastest plane in space, would take you " + hourPlaneConversion + " hours to travel " + light + " light years."); //hours

long hourToDay1 = hourPlaneConversion / hoursInDay;
System.out.println(hourPlaneConversion + " hours is equivalent to " + hourToDay1 + " days."); //hours to days

long dayToYear1 = hourToDay1 / daysInYear;
System.out.println(hourToDay1 +" is equivalent to " + dayToYear1 + " years."); //days to years

long yearToCentury1 = dayToYear1 / yearsInCentury;
System.out.println(dayToYear1 +" is equivalent to " + yearToCentury1 + " Centuries."); //years to centuries

long yearToMillenium1 = yearToCentury1 / yearsInMillenium;
System.out.println(yearToCentury1 +" is equivalent to " + yearToMillenium1 + " millenium.\n"); // centuries to millenium

The output works correctly (unless my maths / code is incorrect), so the program runs fine. I'm just simply looking to make my code more efficient. I'm sure you can see that I need to improve my ability, hopefully I can get some supportive guidance here.


texts:
The rules:

The points rolled on each player’s dice are added to their score.
If the total is an even number, an additional 10 points are added to their score.
If the total is an odd number, 5 points are subtracted from their score.
If they roll a double, they get to roll one extra die and get the number of points rolled added to their score.
The score of a player cannot go below 0 at any point.
The person with the highest score at the end of the 5 rounds wins.
If  both  players  have  the  same  score  at  the  end  of  the  5  rounds,  they  each  roll  1  die  and  whoever gets the highest score wins (this repeats until someone wins)

import pickle
import random
import time

print("")
print("welcome to the dice game")
print("")

with open('users.pickle', 'rb') as f:
    users = pickle.load(f)

print(users)

def login():

    logged_in = False

    username = input('please enter username: ')

    while not logged_in:

        if username in users:
            password = input("enter password: ")
            if password == users[username]:
                print("access granted")
                logged_in = True

        else:
            print("access denied")
            exit()

    return username

print("  ")

rounds = 0

def roll():
    die1 = random.randint(1, 7)
    die2 = random.randint(1, 7)
    change = 10 if (die1 + die2) % 2 == 0 else -5
    points = die1 + die2 + change
    if die1 == die2:
        points += random.randint(1, 6)
    return points

def game():
    player1_points = 0
    player2_points = 0
    for i in range(1, 6):
        player1_points += roll()
        print(f'After this round user1 you now have: {player1_points} Points')
        # time.sleep(1)
        player2_points += roll()
        print(f'After this round user2 you now have: {player2_points} Points')

    player1_tiebreaker = 0
    player2_tiebreaker = 0
    if player1_points == player2_tiebreaker:
        while player1_tiebreaker == player2_tiebreaker:
            player1_tiebreaker = random.randint(1, 6)
            player2_tiebreaker = random.randint(1, 6)

    player2_win = (player2_points + player2_tiebreaker)
    player1_win = (player1_points + player1_tiebreaker) \

    return (player1_points, player1_win), (player2_points, player2_win)

def add_winner(winner):

    with open('Winner.txt', 'a') as i:
        i.write(','.join(map(str, winner)))
        i.write('\n')

def get_leaderboard():
    with open('Leaderboard.txt', 'r+') as g:
        return [line.replace('\n', '') for line in g.readlines()]

def update_leaderboard(leaderboard, winner):
    for idx, item in enumerate(leaderboard):
        if item.split(',')[1] == winner[1] and int(item.split(',')[0]) < int(winner[0]):
            leaderboard[idx] = '{}, {}'.format(winner[0], winner[1])
        else:
            pass
    leaderboard.sort(reverse=True)

def save_leaderboard(leaderboard):
    with open('Leaderboard.txt', 'r+') as h:
        for item in leaderboard:
            h.write(f'{item}\n')

def main():
    user1 = login()
    user2 = login()

    (player1, player1_win), (player2, player2_win) = game()

    if player1_win:
        winner = [player1, user1]
    else:
        winner = [player2, user2]

    print("Well done: ", winner[1], "you won with", winner[0], "Points")

    add_winner(winner)
    leaderboard = get_leaderboard()
    update_leaderboard(leaderboard, winner)
    save_leaderboard(leaderboard)

if __name__ == '__main__':
    main()


texts: Inheritance and small number of parameters

texts:
Uncle Bob in his Clean Code says:

  So all the same rules apply. Functions that take variable arguments
  can be monads, dyads, or even triads. But it would be a mistake to
  give them more arguments than that.

void monad(Integer... args); void
dyad(String name, Integer... args);
void triad(String name, int count, Integer... args);

So Uncle Bob suggests that no more than 3 arguments should a function get, right?

But what about CTOR arguments in class inheritance hierarchy? What if each class in hierarchy adds a new field and you should initialize them in CTOR. See an example below:

class Person
{
private:
    std::string m_name;
    int m_age;

public:
    Person(const std::string& name, const int age);
    std::string getName() const { return m_name; }
    int getAge() const { return m_age; }
    ~Person();
};

#include "Person.h"
class Student : public Person
{
private:
    std::string m_university;
    int m_grade;

public:
    Student(const std::string& name, const int age, const std::string& university, const int grade);
    std::string getUniversity() const { return m_university; }
    int getGrade() const { return m_grade; }
    ~Student();
};

See how student gets 4 arguments, while Person gets only 2 and Student adds two more. So how we should handle this?


texts:
How can I make this more readable?

public class RssFeed
{

    string url = "http://www.pwop.com/feed.aspx?show=dotnetrocks&filetype=master";

    public string responseBody;

    private string DATE_FORMAT = "ddd, dd MMM yyyy HH:mm:ss \\E\\D\\T";

    public Story[] Getstories()
    {
        getContent();
        var stories = Parse(responseBody);
        return GetMostRecent5(stories, new StoryComparer());
    }

    public void getContent()
    {
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        WebResponse response = req.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        responseBody = sr.ReadToEnd();
    }

    static Story[] Parse(string content)
    {
        var items = new List<string>();
        int start = 0;
        while (true)
        {

            var nextItemStart = content.IndexOf("<item>", start);
            var nextItemEnd = content.IndexOf("</item>", nextItemStart);
            if (nextItemStart < 0 || nextItemEnd < 0) break;

            String nextItem = content.Substring(nextItemStart, nextItemEnd + 7 - nextItemStart);
            items.Add(nextItem);
            start = nextItemEnd;
        }

        var stories = new List<Story>();
        for (byte i = 0; i < items.Count; i++)
        {
            stories.Add(new Story() {
                title = Regex.Match(items[i], "(?<=<title>).*(?=</title>)").Value,
                link = Regex.Match(items[i], "(?<=<link>).*(?=</link>)").Value,
                date = Regex.Match(items[i], "(?<=<pubDate>).*(?=</pubdate>)").Value
            });
        }

        return stories.ToArray();
    }

    private static T[] GetMostRecent5<T>(T[] stories, IComparer<T> comparer)
    {
        List<T> recentStories = stories.Take(5).ToList();

        recentStories.Sort(comparer);

        var recentStoriesArray = new T[5];
        for (int i = 0; i <= 5; i++)
        {
            recentStoriesArray[i] = recentStories[i];
        }
        return recentStoriesArray;
    }

    public class Story
    {
        public string title;
        public string link;
        public string date;

        public override bool Equals(object obj)
        {
            return this.Equals(obj as Story);
        }

        public bool Equals(Story story)
        {
            return this.link == story.link;
        }
    }

    private class StoryComparer : IComparer<Story>
    {
        public int Compare(Story x, Story y)
        {
            if (x.Equals(y))
                return 0;
            //redundant else
            else
                return x.date.CompareTo(y.date);
        }
    }
}


texts: Attach list of files and email using secure connection

texts:
Can I use this function to reliably attach a list of excel files to an email and create a secure connection to transmit said email? My python programming is self taught and I put this function together with a lot of google searches. (This function works, I use it, but I would like to have someone with more experience look it through, if possible)

Where can I improve my code? (Am I using the correct modules?)

import datetime
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders

sMDY = datetime.date.today().strftime('%m/%d/%y')
lpath = 'C:/Path/to/my/excel/files/'
flist = ['excelfile_1.xlsx', 'excelfile_2.xlsx']

def EMAIL_FILES(flist):
    uname = 'username'
    pword = 'password'

    emailfrom = 'sender@domain.com'
    emailto = [
        'recipient_1@domain.com',
        'recipient_2@domain.com',
        ]

    body = ["The information transmitted is ..."]
    subject = ('Subject with date %s' % sMDY)

    msg = MIMEMultipart()
    msg['From'] = emailfrom
    msg['To'] = ', '.join(emailto)
    msg['Subject'] = subject

    msg.attach(MIMEText(''.join(body)))

    ### ATTACH FILES
    for item in flist:
        part = MIMEBase('application', "octet-stream")

        part.set_payload(open(lpath + item, "rb").read())

        Encoders.encode_base64(part)

        part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % item)
        msg.attach(part)

    ### SECURE CONNECTION
    server = smtplib.SMTP('smtp.domain.com:25')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(uname, pword)

    server.sendmail(emailfrom, emailto, msg.as_string())
    server.quit()


texts:
I am willing to get a linear output of a product in a ring Z/nZ

For that I have successfully implemented a code that does a Product in a modulo
However, it is not optimized to output the steps smoothly:

/* Product of n1 x n2 x n3 modulo M */

var numbers=[n1,n2,n3];
var modulo= M;

var AProd=1;
var BProd=numbers[0];

var accu=0;

var nProd=true;
var iProd=0;
var kProd=0;

var tritemp = 0;

function ProductModulo() {

 if (AProd == 1 || iProd == 0) {
     nProd = false;
 }

 if (nProd && tritemp == 0) {
     if (accu > 1) {
         tritemp = accu;
     } else {
         tritemp = AProd;
     }
 }

 if (nProd && 10 * tritemp <= accu) {
     accu = 10 * tritemp;
     nProd = false;
     tritemp = 0;

 }

 if (nProd) {
     accu += tritemp; //arbitrary
 }

 if (AProd == 1) {
     kProd = BProd.toString().length;
 } else if (!nProd) {

     if (tritemp == 0) {
         tritemp = accu + Number(AProd.toString()[iProd]) * Number(BProd.toString()[kProd]) * Math.pow(10, BProd.toString().length - 1 - kProd);

     }

     accu += 50; //arbitrary

     if (accu >= tritemp) {
         accu = tritemp;
         tritemp = 0;
         kProd++;
     }
 }

 if (kProd == BProd.toString().length) {

     accu = accu % modulo;

     iProd++;
     kProd = 0;
     nProd = true;
     tritemp = 0;

 }

 if (iProd == AProd.toString().length) {

     if (AProd == 1) {
         AProd = BProd;
     } else {
         AProd = accu;
     }

     numbers.splice(0, 1);
     iProd = 0;

     if (numbers.length > 0) {
         BProd = numbers[0];
         accu = 0;
     }
 }

 if (numbers.length == 0) {
     //display result accu, calculation is done
     console.log("Final Result: " + accu);

 } else {
     // (could display accu)
     ProductModulo();
 }

}

EDIT Here is a test page to see it in action

The code works as follow:

step 1: We take the current number in accumulator and multiply by 10
step 2: We take the first digit (of AProd) and multiply by Bprod
step 3: we add result of step 2 to result of step 1 and modulo M of it
step 4: Same as Step 1, 2 and 3 with the next digit of AProd

...
When all Aprods digits have been done we do the same between the result and n3

So, this code works but the problem is I would like a more linear way of visualizing the whole process. For instance I already show all the steps of additions instead of outputing the result directly.

Is there a smooth way, of increasing the accu, and is it possible to work on n1 and n2 and n3 at the same time instead of doing, (n1*n2) and then *n3?

Note: I am only interested with numbers positive and co-prime with the modulo


texts: Parsing NuGet packages.config with Parallel.ForEach

texts:
Below is a file parser for old style nuget package configuration files. The Parallel.ForEach is probably overkill; in most cases its fast enough without. However, when using the parallel loop, can I avoid the need for the lock / shared list?

class Program
{
    private static readonly object _lock = new Object();
    private static readonly List<Package> _packages = new List<Package>();

    static void Main(string[] args)
    {
        string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), "packages.config", SearchOption.AllDirectories);

        Parallel.ForEach(files, GetPackagesForFile);

        IEnumerable<IGrouping<string, Package>> idGroups =
            _packages.GroupBy(p => p.Id).OrderBy(g => g.Key);

        foreach (IGrouping<string, Package> idGroup in idGroups)
        {
            IEnumerable<IGrouping<string, Package>> versionGroups = idGroup.GroupBy(p => p.Version);
            Console.WriteLine($"{idGroup.Key} ({versionGroups.Count()})");

            foreach (IGrouping<string, Package> versionGroup in versionGroups)
                Console.WriteLine($"\t{versionGroup.Key}");
        }
    }

    private static void GetPackagesForFile(string filepath)
    {
        var filePackages = XDocument.Load(filepath).Root.Elements("package").Select(GetPackageFromElement);
        lock(_lock) _packages.AddRange(filePackages);
    }

    private static Package GetPackageFromElement(XElement element) =>
        new Package(
            element.Attribute("id").Value,
            element.Attribute("version").Value,
            element.Attribute("targetFramework").Value);
}


texts:
This helper class is supposed to validate the user input from a text based wifi login form.

The entire process is basically this:

I use the create_voucher function of this API passing voucher_duration to set the amount of time for which the voucher is going to be valid and $this->clean['name']." ".$this->clean['surname'] as a note so I can later identify which device belongs to which user.

The code returned by create_voucher is then sent to the passed e-mail-adress using php-mailer so the user can login and use the wifi.

I am particularly unhappy with my error handling and would like to know if you see any obvious ways to break the code or inject malicious code.

class sanitizer
{
    public $clean;
    private $post=null;
    private $reg_email ='/^\S+@\S+\.\S+$/';        //Just some basic checking
    private $reg_name = '/^[\'\p{L} -]+[\n]?$/im'; //Allowing some wierd names
    private $reg_number='/^[[:digit:]]*$/im';      //A single integer no fuzz

    public function __construct($post){
         $this->post=$post;
     }

    private function sanitize($key, $regex){
       if (preg_match($regex, $this->post[$key])) {
           $this->clean[$key]= $this->post[$key];
       } else {
           $this->clean[$key]=null;
       }
   }

    public function clean_up(){
        if (isset($this->post['smt_sent'])) {
            if ($this->post['smt_sent']==1) {
                $this->sanitize('name', $this->reg_name);
                $this->sanitize('surname', $this->reg_name);
                $this->sanitize('voucher_duration', $this->reg_number);
                if ($this->post['voucher_duration'] > 0 && ($this->post['voucher_duration']/60 > 48)) {
                    $this->clean['duration']=null;
                }
                $this->sanitize('email_own', $this->reg_email);
                $this->clean['smt_received']=1;

                $this->clean['error'] = false; //No errors yet

                foreach ($this->clean as $field) { //Loop trough each field
                    if (!isset($field)) {
                        $this->clean['error'] = true; //Yup there are errors
                    }
                }
                return $this->clean;
            }
        }
    }
}


texts: Separating data from string representation of objects, with added extras

texts:
Given a string representation of data, I want to extract the information into its corresponding object.
However,
If the string has "|" separators then these should be considered options and need to be picked at random.
If the string data has numbers shown as a range "1-10" then a random value should be chosen between the range. It should also preserve the numerical datatype i.e int or float
I.e
"(1-3,1,1)" returns either (1, 1, 1), (2, 1, 1) or (3, 1, 1)
"(0.2-0.4,1,1)" returns either (0.2, 1, 1), (0.3, 1, 1) or (0.4, 1, 1)
"foo|bar|foobar" returns either "foo", "bar" or "foobar"
"[1-2,1,2]|foo|bar|[1,8-10,99]" could return :
"foo","bar", [1, 1, 2], [2, 1, 2], [1, 8, 99], [1, 9, 99] or [1, 10, 99]
This is what I have and it works well. But I cant help think it could be achieved in a more concise way. Let me know what I could have done better.
import re
import random
import ast

def randomize_by_pipe(st_value):
    """
    Used to split strings with the pipe character and randomly choose and option.

    :param: st_value - (str)

    """
    if not st_value is None:
        st_arr = st_value.split("|")
        random.shuffle(st_arr)
        return st_arr[0]
    else:
        return st_value

def randomise_range(text):
    if text is None:
        return text
    else:
        matches = re.findall("\d*\.*\d*-{1}\d*\.*\d*",text)

        for match in matches:
            startingPos = 0
            position = text.find(match, startingPos)
            while True:
                position = text.find(match, startingPos)
                if position > -1:
                    txt = text[position:position+len(match)]
                    txt = rand_no_from_string(txt)

                    new_text = text[0:position+len(match)].replace(match,str(txt))
                    text = new_text + text[position+len(match):]
                else:
                    break

        try:
            return ast.literal_eval(text)
        except ValueError:
            return text

def rand_no_from_string(txt):

    is_int = False
    txt_arr = txt.split("-")
    num_arr = [float(x) for x in txt_arr]
    if int(num_arr[0]) == num_arr[0]:
        mul = 1
        is_int = True
    else:
        #new section to deal with the decimals
        mul = 10 ** len(str(num_arr[0]).split(".")[1])
        num_arr = [x*mul for x in num_arr]

    if num_arr[0] > num_arr[1]:
        num_arr[1], num_arr[0] = num_arr[0], num_arr[1]

    val = random.randint(num_arr[0],num_arr[1])/mul
    return int(val) if is_int else val

Run with:
text="(108-100,0.25-0.75,100)|Foo|Bar|[123,234,234-250]"
randomise_range(randomize_by_pipe(text))


texts: Scala Codility GenomicRangeQuery performance

texts:
I solved Codility's GenomicRangeQuery challenge in Scala. We are given a long DNA sequence (up to 100000 bases), where A, C, G, T are assigned values 1, 2, 3, 4, respectively. There are up to 50000 queries of the form (pi, qi), for each of which we should return the smallest value in the DNA string between positions pi and qi (inclusive, and zero-based).

I came up with the following solutions, both of which got 100% correctness but 0% performance. I'd like to know what can I do to improve the performance of these functions.

Answer #1

def solution(s: String, p: Array[Int], q: Array[Int]): Array[Int] = {
  for (i <- p.indices.toArray) yield {
    val gen = s.substring(p(i), q(i) + 1)
    gen match {
      case _ if gen.contains('A') => 1
      case _ if gen.contains('C') => 2
      case _ if gen.contains('G') => 3
      case _ if gen.contains('T') => 4
    }
  }
}

Answer #2

def solution(s: String, p: Array[Int], q: Array[Int]): Array[Int] = {
  val weights =
    for (c <- s.toCharArray) yield c match {
      case 'A' => 1
      case 'C' => 2
      case 'G' => 3
      case 'T' => 4
    }

  for (i <- p.indices.toArray) yield weights.slilce(p(i), q(i) + 1).min
}


texts: Conditional validation for credit card payment information on form submission

texts:
This is the piece of code I'd like to refactor. Basically, when the credit card option is selected, then do I want the credit card number, zip code, and Cvv inputs to be validated.

validateForm=(e)=> {
  Array.from(inputElements).forEach(element=> {
    let value=element.value;
    let input=element;
    if (input===name) {
      errorMessage(isValidName, input, value, e)
    } else if (element===email) {
      errorMessage(isValidEmail, input, value, e);
    } else if (element===creditNumber) {
      if (creditOptionChecked()) {
        errorMessage(isValidCreditCard, input, value, e);
      }
    } else if (element===zip) {
      if (creditOptionChecked()) {
        errorMessage(isValidZipCode, input, value, e);
      }
    } else if (element===cvv) {
      if (creditOptionChecked()) {
        errorMessage(isValidCvv, input, value, e);
      }
    } else if (element==fieldSetActivity) {
      validateCheckboxes(e)
    }
  });
}

form.addEventListener('submit', (e)=> {
  validateForm(e)
  console.log("hello")
})

I've been at this for a couple hours, but I'm still a bit new to be able to implement something that is modular. Here is a link to my JS fiddle, so you can see the rest of the javascript code: https://jsfiddle.net/apasric4/4xfL9utv/2/


texts: Sending a C++ array to Python/NumPy and back

texts:
I am going to send a C++ array to a Python function as NumPy array and get back another NumPy array. After consulting with NumPy documentation and some other threads and tweaking the code, the code is finally working but I would like to know if this code is written optimally considering the:

Unnecessary copying of the array between C++ and Numpy (Python).
Correct dereferencing of the variables.
Easy straight-forward approach.

C++ code:

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

#include "stdafx.h"

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "Python.h"
#include "numpy/arrayobject.h"
#include<iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    import_array()

    // Build the 2D array
    PyObject *pArgs, *pReturn, *pModule, *pFunc;
    PyArrayObject *np_ret, *np_arg;
    const int SIZE{ 10 };
    npy_intp dims[2]{SIZE, SIZE};
    const int ND{ 2 };
    long double(*c_arr)[SIZE]{ new long double[SIZE][SIZE] };
    long double* c_out;
    for (int i{}; i < SIZE; i++)
        for (int j{}; j < SIZE; j++)
            c_arr[i][j] = i * SIZE + j;

    np_arg = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, dims, NPY_LONGDOUBLE,
        reinterpret_cast<void*>(c_arr)));

    // Calling array_tutorial from mymodule
    PyObject *pName = PyUnicode_FromString("mymodule");
    pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    if (!pModule){
        cout << "mymodule can not be imported" << endl;
        Py_DECREF(np_arg);
        delete[] c_arr;
        return 1;
    }
    pFunc = PyObject_GetAttrString(pModule, "array_tutorial");
    if (!pFunc || !PyCallable_Check(pFunc)){
        Py_DECREF(pModule);
        Py_XDECREF(pFunc);
        Py_DECREF(np_arg);
        delete[] c_arr;
        cout << "array_tutorial is null or not callable" << endl;
        return 1;
    }
    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, reinterpret_cast<PyObject*>(np_arg));
    pReturn = PyObject_CallObject(pFunc, pArgs);
    np_ret = reinterpret_cast<PyArrayObject*>(pReturn);
    if (PyArray_NDIM(np_ret) != ND - 1){ // row[0] is returned
        cout << "Function returned with wrong dimension" << endl;
        Py_DECREF(pFunc);
        Py_DECREF(pModule);
        Py_DECREF(np_arg);
        Py_DECREF(np_ret);
        delete[] c_arr;
        return 1;
    }
    int len{ PyArray_SHAPE(np_ret)[0] };
    c_out = reinterpret_cast<long double*>(PyArray_DATA(np_ret));
    cout << "Printing output array" << endl;
    for (int i{}; i < len; i++)
        cout << c_out[i] << ' ';
    cout << endl;

    // Finalizing
    Py_DECREF(pFunc);
    Py_DECREF(pModule);
    Py_DECREF(np_arg);
    Py_DECREF(np_ret);
    delete[] c_arr;
    Py_Finalize();
    return 0;
}

Python Code:

def array_tutorial(a):
    print("a.shape={}, a.dtype={}".format(a.shape, a.dtype))
    print(a)
    a *= 2
    return a[-1]


texts:
Looking to improve building UI in pure ES6.

This is the pattern I have adopted and has worked fairly well. This code increments the count, sets a data attribute to toggle the button, and issues a POST to the server with the vote payload object.

import axios from "axios";

class Vote {
  constructor(el) {
    this.el       = el;
    this.url      = this.el.dataset.url;
    this.id       = this.el.dataset.id;
    this.count    = this.el.dataset.count;
    this.count_el = this.el.querySelector('span.count')
    this.setClickHandlers();
  }

  setClickHandlers() {
    this.el.addEventListener("click", ()=> {
      this.postVote();
      this.toggle();
      this.toggleCount();
    })
  }

  postVote() {
    axios({
      url: this.url,
      method: 'post',
      data: { "idea":
        {"id": this.id}
      }
    })
    .then((data) => {
      console.log(`${data}: Posted vote`);
    })
    .catch((data) => {
      console.log(data);
    })
  }

  toggle() {
    if (this.el.dataset.toggled == "true") {
      this.el.dataset.toggled = "false"
    } else {
      this.el.dataset.toggled = "true"
    }
  }

  toggleCount() {
    var current = parseInt(this.count_el.innerHTML);
    if (this.el.dataset.toggled == "true") {
      this.count_el.innerHTML = ++current;
    } else {
      this.count_el.innerHTML = --current;
    }
  }

}

document.addEventListener("turbolinks:load", ()=> {
  let votes = document.querySelectorAll('[data-vote]');
  if (votes.length) {
    votes.forEach((el) => {
      new Vote(el);
    })
  }
});


texts: Count occurrences of a given number in a list

texts:
I have written a solution to find the occurrence of a common number in a n lists. I am just concerned if this is the best solution? Please suggest the best way to do it.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CommonNumberFinder
{

    final static List<Number> list1 = Arrays.asList(new Number[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    final static List<Number> list2 = Arrays
            .asList(new Number[] { 3, 5, 1, 6, 2, 6, 3, 3, 6, 1, 5, 7, 2, 6, 2, 5, 2, 6, 8, 2 });

    public static void main(String[] args)
    {
        findCountOfNumber(Arrays.asList(new List[] { list1, list2 }), 6);
    }

    private static void findCountOfNumber(final List<List<Number>> lists, final Number num)
    {
        int count = 0;
        for (List<Number> list : lists)
        {
            if (!list.contains(num))
            {
                System.err.printf("Number %d is not common", num);
                return;
            }
        }
        for (List<Number> list : lists)
        {
            for (Number number : list)
            {
                if (number == num)
                    count++;
            }
            System.out.println("List have-" + count);
            count = 0;
        }

    }
}


texts: Get closest Entity from the Player on a 2D battlefield

texts:
I am building a little game in using Unity, and recently made an algorithm to get the closest Entity to the player on the battlefield. I made a working sample in RexTester (it is not the real code, but the algorithm is exactly the same).

I am interested in the GetCloserEntityFromPlayer function. Basically, it loops through all the entities and find the closest one. The function is defined as below:

public static Entity GetCloserEntityFromPlayer(){
    List<Entity> temp = new List<Entity>();
    temp.AddRange(allies);
    temp.AddRange(enemies);

    //assume the first is the closest, and compare to the others
    Entity aux = temp[0];
    int distance = Math.Abs((aux.X + aux.Y) - (player.X + player.Y));

    for(int i = 1; i < temp.Count; i++)
    {
        //in my game, the distance is the absolute difference
        //between the sum of both Entities x and y values
        int temp_distance = Math.Abs((temp[i].X + temp[i].Y) - (player.X + player.Y));
        if(temp_distance < distance)
        {
            aux = temp[i];
        }
    }
    return aux;
}

When the Entity number starts growing, the game seems to get a little slow, with FPS dropping. I was thinking of maintaining the Entities list ordered, so I would help the branch predictor.


texts:
Working on an exercise from Functional Programming in Scala, I implemented a Traverse instance for Option:

override def traverse[G[_],A,B](oa: Option[A])(f: A => G[B])(implicit G: Applicative[G]):
    G[Option[B]] =
  oa match {
    case None => G.unit(None)
    case _ => {
              val a: A = oa.get
              val x: G[B] = f(a)
              G.map(x)(Some(_))
            }
  }

Is this idiomatic? Besides condensing the case _'s 3 lines to 1, perhaps there's a more concise way to write this method?


texts: Vigenere encryption assignment for CS50 C course

texts:
My third week on cs50 and looking for some feedback on the general tidyness and style of my code. I took a look at other peoples code after I was done with this and I guess I could've implemented some functions(?) of my own but I noticed he used things that I haven't learned yet.
E.g: Vigenere Cipher in C

Please criticize! :)

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

int i, c;
char* key;

int main(int argc, string argv[])
{
    int int_A = (int) 'A';
    int int_a = (int) 'a';

    // validate the command line argument's parameters
    if (argc != 2)
    {
        printf("Please use a single alphabetic command line argument\n");
        return 1;
    }
    else if (argc == 2)
    {
        for (int z = 0, n = strlen(argv[1]); z < n; z++)
        {
            if (isalpha(argv[1][z]) == false)
            {
                printf("Please use a single alphabetic command line argument\n");
                return 1;
            }
        }
    }

    // get users plaintext
    printf("Plaintext: ");
    char* plaintext = get_string();

    // foo bar mitzva
        key = argv[1];
    int key_len = strlen(argv[1]);
    int key_i[key_len];
    for (i = 0; i < key_len; i++)
    {
        if (isupper(key[i]))
        {
            key_i[i] = (argv[1][i] - int_A);
        }
        if (islower(key[i]))
        {
            key_i[i] = (argv[1][i] - int_a);
        }

    // set i back to 0 for the next loop
    i = 0;
    // iterate over characters in plaintext and shift plaintext character by key

    printf("ciphertext: ");
    for (int j = 0, n = strlen(plaintext); j < n; j++)
    {
        int pt = (int) plaintext[j];
        if (isalpha(plaintext[j]))
        {
            if (isupper(plaintext[j]))
            {
                printf("%c", (((pt - int_A) + key_i[i % key_len]) % 26) + int_A);
            }
            if (islower(plaintext[j]))
            {
                printf("%c", (((pt - int_a) + key_i[i % key_len]) % 26) + int_a);
            }
        }
        else
        {
            printf("%c", plaintext[j]);
        }
        if (isalpha(plaintext[j]))
        {
            i += 1;
        }

    }
    printf("\n");
    return 0;
}


texts:
To first understand how MiTM works I've made a few MiTM scripts, but this time I wanted to defend myself against such attacks. I'm unsure if my idea even works. The code seems to be working but I make a few assumptions and I'm not sure if those are correct.

Assumptions

When I do a traceroute the IP of the Attacker is in the route.
When I trace the route, and there is not a router device in my route it means an attacker(laptop) is listening on my connection
When I the attacker does an ARP-Spoof, the ARP-table has duplicate values.

Code issues

I have this long python -c "command" it feels a bit silly to do in bash

Any review is welcome!

Plus I would be happy if anyone has additional information on how to prevent MiTM attacks.

#!/bin/bash

route_checker() {
    private_route=$(python -c 'import re; import subprocess; from ipaddress import IPv4Address; print([ip for ip in re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", subprocess.Popen(["traceroute", "-n", "8.8.8.8"], stdout=subprocess.PIPE).communicate()[0]) if IPv4Address(bytearray(ip)).is_private])' | tr --delete []\')
    echo "Your private route = $private_route"
    echo "Checking the safety of route: $private_route"

    echo ""
    echo "Starting nmap scan"
    OLD_IFS=$IFS
    IFS=', ' read -ra IP <<< "$private_route"
    for ip in "${IP[@]}"; do
    echo "Checking ip adress $ip:"
    os_scan=$(nmap -A -T4 "$ip")
    if [[ "$os_scan" =~ "broadband router" ]]
    then
        echo "[*] Warning! No router found."
    else
        echo "[*] Safe! A router was found."
    fi
    done
    IFS=$OLD_IFS
}

arp_checker() {
    if [[ $(arp -an | awk '{print $4}' | sort | uniq -c | grep -v ' 1 ') ]]
    then
    echo "[*] Warning! You are being spoofed"
    else
    echo "[*] Safe! Did not find any duplicate ARP values"
    fi
}

main() {
    echo "@Ludisposed"
    echo ""
    echo "Checking for ARP spoofing"
    arp_checker

    echo ""
    echo "Checking if we have a safe private route"
    route_checker
}

main


texts:
I wrote the following function to implement counting sort:

def CountSort( Arr, Max ):
    counter, retVal = [0] * (Max + 1), []
    for _ in Arr:
        counter[_] += 1
    for i in xrange( Max + 1 ):
        retVal += [i] * counter[i]
    return retVal

NOTE

The function takes the array of integer/list of integer as its first argument, and the maximum value it stores as the second. The only restriction is that the data in array should be distributed for \$0 \le x \le Max\$.

I'm not happy with it since I have to maintain two lists in memory now, namely Arr and retVal. I could, obviously, use the following:

    # indentation preserved
    pos = 0
    for i in xrange( Max + 1 ):
        while counter[i] > 0:
            Arr[pos] = i
            pos += 1
            counter[i] -= 1

but it won't be as pythonic as the first one. An alternate approach is to delete the input Arr, and recreate it:

    # indentation preserved
    del Arr
    Arr = []
    for i in xrange( Max + 1 ):
        Arr += [i] * counter[i]

but this is not dissimilar to the second approach.

I'm open to suggestions on improvement of the first (or any of the latter).


texts:
This is my attempt to build a simple simulation of a direct mapped cache, I'm new to C and trying to learn some low level concepts. I had some difficulties with the design, because I'm used to program in a object-oriented style.

#include <stdio.h>

int create_mask(int num_of_bits, int pos) {
    return (1 << num_of_bits)-1 << pos;
}

int get_window_bits(int num, int window_size, int pos) {
    return (create_mask(window_size, pos) & num) >> pos;
}

int is_valid(char cache[4][4], int set, int tag) {
    return cache[set][0] && (cache[set][1] == tag);
}

void load_to_cache(int address, char memory[8][2], char cache[4][4], int set, int tag, int offset) {
    int memory_index = get_window_bits(address, 3, 1);

    cache[set][0] = 1;
    cache[set][1] = tag;
    cache[set][2] = memory[memory_index][0];
    cache[set][3] = memory[memory_index][1];
}

int fetch_from_cache(int address, char cache[4][4], char memory[8][2]) {
    int set = get_window_bits(address, 2, 1);
    int offset = get_window_bits(address, 1, 0);
    int tag = get_window_bits(address, 1, 3);

    if (!is_valid(cache, set, tag)) {
        printf("cache miss\n");
        load_to_cache(address, memory, cache, set, tag, offset);
    } else {
        printf("cache hit\n");
    }

    return cache[set][2+offset];
}

int main() {

    /* init memory - 8 blocks of 2 bytes */
    char memory[8][2] = {{'A','B'},
                        {'C','D'},
                        {'E','F'},
                        {'G','H'},
                        {'I','J'},
                        {'K','L'},
                        {'M','N'},
                        {'O','P'}};

    /* init cache - 4 lines of 2 bytes storage*/
    char cache[4][4] = {{0,0,0,0},
                        {0,0,0,0},
                        {0,0,0,0},
                        {0,0,0,0}};

    fetch_from_cache(0, cache, memory);
    fetch_from_cache(1, cache, memory);

    return 0;
}

Structure:

The program consists of a 2d array that represents the memory, it's size is 16 bytes:

char memory[8][2] = {{'A','B'},
                    {'C','D'},
                    {'E','F'},
                    {'G','H'},
                    {'I','J'},
                    {'K','L'},
                    {'M','N'},
                    {'O','P'}};

another array which represents the cache of 4 lines, each line can store 2 bytes
the first byte of the line is for the valid bit, the second is for the tag, and the rest are for the data.

char cache[4][4] = {{0,0,0,0},
                    {0,0,0,0},
                    {0,0,0,0},
                    {0,0,0,0}};

The function get_window_bits is used to extract the tag, set and offset of a memory address.

int get_window_bits(int num, int window_size, int pos) {
    return (create_mask(window_size, pos) & num) >> pos;
}

I hope everything else is clear.


texts: Is this Python pathfinder efficient enough?

texts:
I'd like to see if my code follows common practice, or is already efficient or fast enough.

from random import randint
w=[[2,0,0,0,0],[0,0,2,0,0],[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,0]] #1 represent Mr.Pacman, #2 represent food.
for y in xrange(len(w)): #Finding the coordinate of Mr.Pacman
    for x in xrange(len(w[0])):
        if (w[y])[x]==1:
            hor=x
            ver=y
            break

horbound=len(w[0])
verbound=len(w)
def letsCout(xCurrent,yCurrent,xTarget,yTarget,xBoundary,yBoundary,checkedSquare):
    if (xCurrent+1==xTarget and yCurrent==yTarget) or (xCurrent-1==xTarget and yCurrent==yTarget) or (xCurrent==xTarget and yCurrent+1==yTarget) or (xCurrent==xTarget and yCurrent-1==yTarget):
        return 1
    else:
        battle=[9999,9999,9999,9999]
        d=[]
        d.extend(checkedSquare)
        d.append([xCurrent,yCurrent])
        if xCurrent-1>-1 and [xCurrent-1,yCurrent] not in d: #going left
                battle[0]=letsCout(xCurrent-1,yCurrent,xTarget,yTarget,xBoundary,yBoundary,d)+1
        if xCurrent+1<xBoundary and [xCurrent+1,yCurrent] not in d: #going righ
                battle[1]=letsCout(xCurrent+1,yCurrent,xTarget,yTarget,xBoundary,yBoundary,d)+1
        if yCurrent-1>-1 and [xCurrent,yCurrent-1] not in d: #going up
                battle[2]=letsCout(xCurrent,yCurrent-1,xTarget,yTarget,xBoundary,yBoundary,d)+1
        if yCurrent+1<yBoundary and [xCurrent,yCurrent+1] not in d: #going down
                battle[3]=letsCout(xCurrent,yCurrent+1,xTarget,yTarget,xBoundary,yBoundary,d)+1
        battle.sort()
        return battle[0]
#
happy=[9999,9999,9999,9999]
for y in xrange(len(w)): #Checking the coordinate of a food. If multiple food exist, the method will find the food with the smallest cost.
    for x in xrange(len(w[0])):
        if (w[y])[x]==2:
            if hor-1>-1: #going left
                if (w[ver])[hor-1]==2:
                    happy[0]=1
                else:
                    candidate=[happy[0],letsCout(hor-1,ver,x,y,horbound,verbound,[[hor,ver]])+1]
                    candidate.sort()
                    happy[0]=candidate[0]
            if hor+1<horbound: #going right
                if (w[ver])[hor+1]==2:
                    happy[1]=1
                else:
                    candidate=[happy[1],letsCout(hor+1,ver,x,y,horbound,verbound,[[hor,ver]])+1]
                    candidate.sort()
                    happy[1]=candidate[0]
            if ver-1>-1: #going up
                if (w[ver-1])[hor]==2:
                    happy[2]=1
                else:
                    candidate=[happy[2],letsCout(hor,ver-1,x,y,horbound,verbound,[[hor,ver]])+1]
                    candidate.sort()
                    happy[2]=candidate[0]
            if ver+1<verbound: #going down
                if (w[ver+1])[hor]==2:
                    happy[3]=1
                else:
                    candidate=[happy[3],letsCout(hor,ver+1,x,y,horbound,verbound,[[hor,ver]])+1]
                    candidate.sort()
                    happy[3]=candidate[0]

wow=["left","right","up","down"]
while True: #The decision. The lowest cost direction for next move will be picked. If there is tie for lowest cost, I want to pick it randomly
    poop=randint(0,3)
    for x in xrange(4):
        if happy[poop]>happy[x]+1:
            break
    else:
        print wow[poop]
        break

I honestly see this project as a dynamic programming task.  Is this code good enough?


texts:
I'm learning sorting algorithms and wrote my own implementation of Insertion Sort. Is it optimal? Is there anything that can be done better?
#include <iostream>
#include <vector>
#include <algorithm>
#include <vector>

void display(std::vector<int> arr)
{
  for (int i = 0; i < arr.size(); ++i)
    {
      std::cout << arr[i] << ' ';
    }
  std::cout << std::endl;
}

std::vector<int>& insertionSort(std::vector<int>& arr)
{
  int i = 1;
  while (i < arr.size())
    {
      int j = i;
      while ((j > 0) && (arr[j-1] > arr[j]))
    {
      std::swap(arr[j-1],arr[j]);
      --j;
    }
      ++i;
    }
  return arr;
}

int main()
{
  std::vector<int> arr{1,4,3,5,6,2};
  display(insertionSort(arr));
  return 0;
}


texts:
I wrote a quick prefix tree implementation. I know it may be far from perfect, but I need to make sure that I got the basics right.

My main concerns are:

Have I settled for the correct data structures?
Is this a scalable solution? What sort of problems can I run into if this is a huge tree?

public class PrefixTree {
//isLeaf would point out the end of a word in the tree
boolean isLeaf;
HashMap<Character, PrefixTree> map;

public PrefixTree() {
    map=new HashMap<Character, PrefixTree>();
    isLeaf=false;
}

//insert a new word into the tree
public void put(String s) {
    if(s.length()==0) {
        //if the word ends here, we need to point it out using the isLeaf
        //boolean field, and the insertion job is done, so return
        isLeaf=true;
        return;
    }
    //if the first character of the string doesn't exits
    //we create a new node for the and insert it into the map
    if(!map.containsKey(s.charAt(0))) {
        map.put(s.charAt(0), new PrefixTree());
    }
    //now this newly create node or if it already existed
    //would contain the rest of the substring
    map.get(s.charAt(0)).put(s.substring(1));
}

//tree travelsal to examine the contents of the tree
public void travelTree(String perm) {
    if(isLeaf) {
        System.out.println(perm);
    }
    if(map.size()==0) return;
    for(Character c:map.keySet()) {
        map.get(c).travelTree(perm+c);
    }
}

//this overloaded function is used as a helper function with the getSuggestions
//functions
//doesn't need to be called on from the root
public void travelTree(String perm, List<String> sl) {
    if(isLeaf) {
        sl.add(perm);
    }
    if(map.size()==0) return;
    for(Character c:map.keySet()) {
        map.get(c).travelTree(perm+c, sl);
    }
}

public List<String> getSuggestions(String q) {
    //I am passing along this List object into the nested recursive calls
    //from here onwards, is this a better approach than having every
    //recursive function call create an arraylist object and append the
    //return items and finally return the final list
    List<String> suggestions=new ArrayList<String>();
    getSuggestions(q, "", suggestions);
    return suggestions;
}

public void getSuggestions(String q, String perm, List<String> sl) {
    if(q.length()==0) {
        travelTree(perm, sl);
        //we don't return as we need to go into further depth for more
        //suggestions
    }
    if(map.size()==0) return;
    if(q.length()>0 && map.containsKey(q.charAt(0))) {
        //make sure we call getSuggestions on specific node instead of
        //current instance's getSuggestions
        map.get(q.charAt(0)).getSuggestions(q.substring(1), perm+q.charAt(0), sl);
    }
}
}


texts:
This is my first step into Fortran. The program aims to provide a simple way of calculating numbers. Just looking for improvements in general.

program Calc
    real :: a, b, additionAnswer, subtractionAnswer, multiplicationAnswer, divisionAnswer
    print *, "George Gibson's Calc"
    print *, "Type the first number: "
    read *, a
    print *, "Type the second number: "
    read *, b
    additionAnswer = a + b
    subtractionAnswer = a - b
    multiplicationAnswer = a * b
    divisionAnswer = a / b
    print *, a, " + ", b, " = ", additionAnswer
    print *, a, " - ", b, " = ", subtractionAnswer
    print *, a, " * ", b, " = ", multiplicationAnswer
    print *, a, " / ", b, " = ", divisionAnswer
    read *
end program Calc


texts: Naïve Prime Factorization in Clojure Pt. 2

texts:
After my last review request, I decided to try and make a "tree" visualization, and thought that I could benefit from making find-prime-factors lazily produce prime factors so the visualization can be updated in real time as factors are found.

This is what I ended up with. I was actually surprised how easy it was to adapt the loop to a recursive lazy-seq solution. The non-return accumulators were added as parameters to a recursive function, and the lazy return list was created via the typical (lazy-seq (cons ... ...)). It actually performs identically to the previous strict version too when evaluation is forced using vec.

If anyone sees anything here that can be commented on, I'd like to know.

(doseq [p (lazily-find-prime-factors 99930610001)]
  (println p
           (int (/ (System/currentTimeMillis) 1000))))
163 1544998649
191 1544998692
3209797 1544998692

Same as in the last review:

(ns irrelevant.prime-factorization.prime-factorization)

(defn is-factor-of? [n multiple]
  (zero? (rem n multiple)))

(defn prime? [n]
  (or (= n 2) ; TODO: Eww
      (->> (range 2 (inc (Math/sqrt ^double n)))
           (some #(is-factor-of? n %))
           (not))))

(defn primes []
  (->> (range)
       (drop 2) ; Lower bound of 2 for the range
       (filter prime?)))

(defn smallest-factor-of? [n possible-multiples]
  (some #(when (is-factor-of? n %) %)
        possible-multiples))

Updated:

(defn lazily-find-prime-factors [n]
  (letfn [(rec [remaining remaining-primes]
            (when-let [small-prime (and (> remaining 1)
                                        (smallest-factor-of? remaining remaining-primes))]
              (lazy-seq
                (cons small-prime
                      (rec (long (/ remaining small-prime))
                           (drop-while #(not= % small-prime) remaining-primes))))))]
    (rec n (primes))))


texts: Check if registered then unregister or simply unregister

texts:
I am trying to figure out which of these two calls are more efficient:

Check if listener is registered before calling unregister.

if(EventBus.getDefault().isRegistered(this))
{
     EventBus.getDefault().unregister(this);
}

Or calling unregister without the check.

EventBus.getDefault().unregister(this);

Information for context:

I am using EventBus 2.4. The underlying implementation of these two methods is as follows:

public synchronized boolean isRegistered(Object subscriber) {
    return typesBySubscriber.containsKey(subscriber);
}

public synchronized void unregister(Object subscriber) {
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

I ran both codes 1000 times and saw no difference. I am thinking that simply calling unregister() is optimal.


texts:
In physics class we are doing an investigation thing. Some of the numbers might seem plucked out of thin air but they aren't. The maths is right(I think) I just want some feedback on the code.

import datetime
import random
import time
import math

player_1 = input("Player one: ")
speed = int(input("Speed in km/h: "))
speed_ms = ((speed)/3.6)
conditions = input("Wet or dry conditions? (all lowercase)")

if conditions == "wet":
    friction_coefficient = 0.4
else:
    friction_coefficient = 0.6

time.sleep(0.5)
print("Get ready..")
time.sleep(random.randint(1,12))
then = datetime.datetime.now()
t = input("GO!! ")
now = datetime.datetime.now()
diff = then-now
reaction_time = round(abs(diff.total_seconds()), 2)

Rt = (math.sqrt((reaction_time*98)/490))
print('Your final reaction time was: ', (Rt), '!\n')

Rd = (Rt * speed_ms)
print('Your final reaction distance was: ', (Rd), '!\n')

Bd = (((speed_ms)**2) / 19.6 * (friction_coefficient))
print('Your final breaking distance was: ', (Bd), '!\n')

Sd = ((Rd)+(Bd))

############################################################################

print("\n\n---===========FINAL STOPPING DISTANCE===========---")
print('--------------', (Sd), 'meters', '------------')


texts:
I wrote basic Python code for the summation of n primes. It works but I wanted to find out how I could improve it and what shortcuts I missed.

    """ So this program is designed to add up the first 'b' primes
    ==> Prime number is defined as a number only divisible by itself or 1"""

def is_prime(a):
    """ This function determines if a number is prime"""

    pri = True
    n = 2
    while n < a:
        if a % n == 0:
            pri = False
        n += 1
    return pri

def addition_of_primes(b):
    """ This function will find the first b primes.
        It stores each one in a list and then we take
        the sum of that list"""

    primes = []
    candidate = 2
    while len(primes) < b:
        if is_prime(candidate):
            primes.append(candidate)
        candidate += 1
    return sum(primes)

print addition_of_primes(1000)


texts: Change type of property in derived class

texts:
I'm using manually implemented properties to handle sharing code between forms intended to edit a base object, and those intended to edit a derived version.  My current setup works as long as everyone accesses the property and not the base object; but after spending an hour or so tracking down a bug that was due to manipulating _editDataObject in DataObjectEditForm in an application using DataObjectEx and DataObjectExEditForm I'm wondering if there's a way to enforce this more strongly than just adding a do not use comment on _editDataObject.

For contractual reasons the simple option of creating a single form that is aware of both DataObject and DataObjectEx isn't permissible.

public class DataObject
{
    //data members go here
}

public class DataObjectEx : DataObject
{
    public DataObjectEx(DataObject dataObject)
    {
         //create DataObjectEx containing all of dataObject's state.
    }

    //additional data members go here
}

public class DataOjectEditForm : Form
{
    ///<Summary>
    ///Do not use.  Will break app if EditDataObject property is overridden.
    ///</Summary>
    private _editDataObject;

    protected virtual EditDataObject
    {
        get { return _editDataObject; }
        set { _editDataObject = value; }
    }

    //Do stuff only dependent on DataObject
}

public class DataOjectExEditForm : DataObjectEditForm
{
    private _editDataObjectEx;

    protected override EditDataObject
    {
        get { return _editDataObjectEx; }
        set
        {
            if (value == null)
               _editDataObjectEx = null;
            else _editDataObjectEx = value as DataObjectEx ?? new DataObjectEx(value);
        }
    }

    //Add stuff dependent on the additions in DataObjectEx
}