texts: What is a good way to structure mark-up generating code and avoid the example mess?

texts:
Here are two methods of code that only vary in one place. Specifically, the first method calls GetReleaseYear(), and the second calls GetReleaseDate().

This is one example of a one-line difference in multiple methods, and each time the difference might be on a different line or couple of lines. One possible design I've considered is passing in a list of strings to a function, but this is cumbersome because the lists would still need to be prepared, and the generated HTML still has to be somewhat content-aware.

private string A()
    {
        string title = GetTitle();
        string mediaType = GetMediaType();
        string description = GetDescription();
        string releaseYear = GetReleaseYear();
        string contributors = GetContributors();
        string image = GetImage();
        string genres = GetGenres();
        string ratings = GetRatings();

        string top = string.Format("{0}This is a {1}{2}.

",
                title, mediaType, string.IsNullOrEmpty(releaseYear) ? string.Empty
                : " released in " + releaseYear);

        StringBuilder metadata = new StringBuilder();
        metadata.AppendLine(contributors + "
");
        metadata.AppendLine(genres + "

");
        metadata.AppendLine(ratings + "

");
        metadata.AppendLine(description);

        return string.Format("{0}

{1}	{2}

", top, metadata.ToString(), image);
    }

 private string B()
    {
        string title = GetTitle();
        string mediaType = GetMediaType();
        string description = GetDescription();
        string releaseDate = GetReleaseDate();
        string contributors = GetContributors();
        string image = GetImage();
        string genres = GetGenres();
        string ratings = GetRatings();

        string top = string.Format("{0}This is a {1}{2}.

",
                title, mediaType, string.IsNullOrEmpty(releaseDate) ? string.Empty
                : " released in " + releaseDate);

        StringBuilder metadata = new StringBuilder();
        metadata.AppendLine(contributors + "
");
        metadata.AppendLine(genres + "

");
        metadata.AppendLine(ratings + "

");
        metadata.AppendLine(description);

        return string.Format("{0}

{1}	{2}

", top, metadata.ToString(), image);
    }


texts: Merging the vector-group to get the common vector

texts:
Given that I have a set of vectors(or called vector-group), like \$\{\mathbf U_1,\mathbf U_2,\cdots,\mathbf U_n\}\$. Below is a simple instance U1, U2, U3

U1 = {0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 0.8};
U2 = {0.21, 0.25, 0.3, 0.6, 0.7, 0.8};
U3 = {0.25, 0.3, 0.7, 0.8};

Now I would like to calculate their common vector , i.e., a vector that contains all of the elements of U1, U2, U3 and has the least length. In addtion, containing all of the elements of U1 means containing
{0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 0.8}, rather than {0.25, 0.5, 0.75, 0.8}.

My firend Richard Xu gives me the following algorithm

i   j   k   min_val
1   1   1   0.21    j++
1   2   1   0.25    i++ j++ k++
2   3   2   0.25    i++
3   3   2   0.3     j++ k++
3   4   3   0.5     i++
4   4   3   0.5     i++
5   4   3   0.6     j++
5   5   3   0.7     j++ k++
5   6   4   0.75    i++
6   6   4   0.75    i++
7   6   4   0.8     i++ j++ k++
//===>common vector
U = {0.21, 0.25, 0.25, 0.3, 0.5, 0.5, 0.6, 0.7, 0.75, 0.75, 0.8}

C function for two vectors

#define min_two(a, b) (a) > (b) ? (b) :(a)

//count denotes the length of common vector of U1, U2
int two_vec_common(double *U1, double *U2, int len1, int len2, double *temp) {
    int i, j;
    double min_val;
    int count = 0;
    i = j = 0;
    while (i < len1 || j < len2) {
        min_val = min_two(U1[i], U2[j]);
        temp[count++] = min_val;
        if(U1[i] == min_val) i++;
        if(U2[j] == min_val) j++;
    }
    return count;
}

C function for three vectors

double min_three(double x, double y, double z) {
    if (x <= y && x <= z) return x;
    if (y <= x && y <= z) return y;
    if (z <= x && z <= y) return z;
}
/*count denotes the length of common vector of U1, U2, U3
  len1, len2, len3 denote the length of vector U1, U2, U3, respectively
  the pointer variable temp stores the values of common vector*/
int three_vec_common(double *U1, double *U2, double *U3, int len1, int len2, int len3, double *temp) {
    int i, j, k;
    double min_val;
    int count = 0;
    i = j = k = 0;
    while (i < len1 || j < len2 || k < len3) {
        min_val = min_three(U1[i], U2[j], U3[k]);
        temp[count++] = min_val;
        if(U1[i] == min_val) i++;
        if(U2[j] == min_val) j++;
        if(U3[k] == min_val) k++;
    }
    return count;
}

Although the algorithm is easy to implement, I don't knot how to write a unified function to calculate the common vector of \$\{\mathbf U_1,\mathbf U_2,\cdots,\mathbf U_n\}\$


texts:
I believe that building a simple calculator is one of the most popular tasks for beginners. There are several conditions, however, in this case:

Delegates should be used
The user types a string that should be parsed as a math expression with just two numbers and one of the four operators (+, -, *, /)
My first idea of using the Compute method of DataTable was, predictably, rejected

I know that there is one serious flaw in the current version of the program. The input string is not validated. Apart from that, what are your recommendations and suggestions with regards to my code?

GitHub

using System;
namespace CalculatorDelegate
{
    class Program

    {
        private static double Item1 { get; set; }
        private static double Item2 { get; set; }
        private static string Action { get; set; }
        private delegate double Del(double a, double b);

        private static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine(ParseInput());
            }
        }

        private static double ParseInput()
        {
            Console.WriteLine("Enter a mathematical expression, please");
            var userInput = Console.ReadLine();
            var userInputLength = userInput.Length;
            Del handler;

            for (var i = 1; i < userInputLength; i++)
            {

                if ( userInput[i].Equals('+') || userInput[i].Equals('-') ||
                    userInput[i].Equals('*') | userInput[i].Equals('/'))
                {
                        Action = Convert.ToString(userInput[i]);
                        double.TryParse(userInput.Substring(0, i), out var tempItem1);
                        double.TryParse(userInput.Substring(i + 1, userInputLength - i - 1), out var tempItem2);

                        Item1 = tempItem1;
                        Item2 = tempItem2;

                        if (Action.Equals("/") && Item2 == 0)
                        {
                            Console.WriteLine("You can't divide by zero");
                            return 0;
                        }

                        break;
                }
            }

            switch (Action)
            {
                case "+":
                    handler = GetSum;
                    break;

                case "-":
                    handler = GetDiff;
                    break;

                case "*":
                    handler = GetMult;
                    break;

                case "/":
                    handler = GetDiv;
                    break;

                default:
                    return 0;
            }

            return handler(Item1, Item2);
        }

        private static double GetSum(double a, double b)
        {
            return a + b;
        }

        private static double GetDiff(double a, double b)
        {
            return a - b;
        }

        private static double GetMult(double a, double b)
        {
            return a * b;
        }

        private static double GetDiv(double a, double b)
        {
            return a / b;
        }

    }
}


texts: Prime factoring function using recursion

texts:
As a programming exercise, I decided to make a prime factoring function using recursion:

    static bool isPrime(int n)
    {
        if (n < 2)
            return false;
        if (n % 2 == 0)
            return (n == 2);
        int root = (int)Math.Sqrt((double)n);
        for (int i = 3; i <= root; i += 2)
            if (n % i == 0) return false;
        return true;
    }

    static bool iseven(int n)
    {
        return n % 2 == 0;
    }

    static int[] prfact(int n, int curr, List<int> nums)
    {
        if (nums.All(x => isPrime(x)) && isPrime(curr))
        {
            nums.Add(curr);
            return nums.ToArray();
        }
        else if (iseven(curr))
        {
            nums.Add(2);
            return prfact(n, curr / 2, nums);
        }
        else if (!iseven(curr))
        {
            int div = 3;
            while (curr % div != 0 || !isPrime(div))
                div += 2;

            nums.Add(div);
            return prfact(n, curr / div, nums);
        }
        else
            return null;
    }

    static int[] factor(int n)
    {
        return prfact(n, n, new List<int>());
    }

How efficient is it and how can it be improved?


texts: Testing whether a number is nearly a multiple of 10

texts:
I'm going through a basic python exercise, stumbled upon this query.

  Given a non-negative number "num", return True if num is within 2 of a multiple of 10.

Here's the my solution:

def near_ten(num):
  return (num % 10) in range(8, 10) or (num % 10) in range(0, 3)

It shows "All Correct", but I'm feeling like my code is bit digressive as I have hard-coded the "numbers within 2 of a multiple of 10".

Can one please review this line if its the right approach?


texts: ValueAnimator for IOS - Did I butcher it up?

texts:
I am trying to make an IOS tool similar to Android's ValueAnimator... more or less

This is useful for situations where you simply want a value to "animate" over time, but rather than necessarily attaching that value to some view property, it is available to use as you wish.  Imagine applying it to an audio filter, for example.

It works like a Timer/NSTimer except that is passes a value back to the selector which behaves differently depending on the arguments sent to the initializer.

Concerns:

Is there a way to tidy up the numerous functions into something like a dictionary? (I'm not that advanced at Swift)

Is there a way of accomplishing the same functionality -- passing a "listener" function in on initialization which will be called back with the animated value as an argument -- but without using a selector? ... I ask because of the nasty "MyNSDoubleObject" workaround.

Any other improvements... this is my first question on here.

Code:

import Foundation

// this class is a work-around for the fact that we can't pass a raw value (int, double, etc.) through a selector -- must be object
class MyNSDoubleObject: NSObject {
    var val: Double

    init(val: Double) {
        self.val = val
    }
}

class ValueAnimator : NSObject {

    // args
    private let sampleRate: Int
    private let functionType: FunctionType
    private let selector: Selector
    private let target: AnyObject

    // computed from args
    private let maxIterations: Int
    private let timeInterval: Double
    private var X_currentRepIndex: Int = 0 // domain
    private var F_of_X = MyNSDoubleObject(val: 0.0) // range

    // other
    private var timer = Timer()

    enum FunctionType {
        case SINE_WAVE_FROM_0_TO_1_TO_0
        case SINE_WAVE_FROM_0_TO_1
        case SINE_WAVE_FROM_1_TO_0
    }

    // Public functions
    init(durationInSeconds: Int, sampleRate: Int, functionType: FunctionType, selector: Selector, target: AnyObject) {
        self.sampleRate = sampleRate
        self.maxIterations = durationInSeconds * sampleRate
        self.timeInterval = 1.0/Double(sampleRate)
        self.functionType = functionType
        self.selector = selector
        self.target = target
    }

    func start() {
        timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: (#selector(timerCallback)), userInfo: nil, repeats: true)
    }

    // "Private" functions
    @objc func timerCallback() {

        switch functionType {
        case .SINE_WAVE_FROM_0_TO_1_TO_0:
            F_of_X.val = sine010(x: X_currentRepIndex)
        case .SINE_WAVE_FROM_0_TO_1:
            F_of_X.val = sine01(x: X_currentRepIndex)
        case .SINE_WAVE_FROM_1_TO_0:
            F_of_X.val = sine10(x: X_currentRepIndex)
        }

        X_currentRepIndex += 1

        _ = target.perform(selector, with: F_of_X)

        if X_currentRepIndex == (maxIterations+1) {
            timer.invalidate()
        }
    }

    private func sine010(x: Int) -> Double {
        return (-cos(2*Double.pi * (Double(x)/Double(maxIterations)))+1)/2
    }

    private func sine01(x: Int) -> Double {
        return (-cos(Double.pi * (Double(x)/Double(maxIterations)))+1)/2
    }

    private func sine10(x: Int) -> Double {
        return (cos(Double.pi * (Double(x)/Double(maxIterations)))+1)/2
    }

}


texts:
I'm still learning about domain driven design, and I have created my first entity class User.

Is this fully compliant with the DDD principles?  Particularly my setters because I have business rules in them.  Any other suggestions would be highly appreciated as well.

namespace Models\Entities;

class User
{
    private $id;
    private $firstName;
    private $lastName;
    private $email;
    private $password;
    private $registerDate;

    public function setId($id)
    {
        if (!$this->id) {
            if (is_int($id) && $id >= 1) {
                $this->id = $id;

                return $this;
            }

            throw new \InvalidArgumentException('ID must be a positive integer.');
        }

        throw new \InvalidArgumentException('ID has already been set.');
    }

    public function getId()
    {
        return $this->id;
    }

    public function setFirstName($firstName)
    {
        if (is_string($firstName) && !empty($firstName) && ctype_alpha($firstName)) {
            $length = $this->stringLength($firstName);

            if ($length >= 1 && $length <= 35) {
                $this->firstName = $firstName;

                return $this;
            }
        }

        throw new \InvalidArgumentException('First name must be an alpha string inclusively between 1 and 35 characters.');
    }

    public function getFirstName()
    {
        return $this->firstName;
    }

    public function setLastName($lastName)
    {
        if (is_string($lastName) && !empty($lastName) && ctype_alpha($lastName)) {
            $length = $this->stringLength($lastName);

            if ($length >= 1 && $length <= 35) {
                $this->lastName = $lastName;

                return $this;
            }
        }

        throw new \InvalidArgumentException('Last name must be an alpha string inclusively between 1 and 35 characters.');
    }

    public function getLastName()
    {
        return $this->lastName;
    }

    public function getFullName()
    {
        return $this->firstName . ' ' . $this->lastName;
    }

    public function setEmail($email)
    {
        if (is_string($email) && !empty($email)) {
            $sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);
            $isValid   = filter_var($sanitized, FILTER_VALIDATE_EMAIL);
            $isValid   = $isValid ? $this->stringLength($email) <= 254 : false;

            if ($email === $sanitized && $isValid) {
                $this->email = $email;

                return $this;
            }
        }

        throw new \InvalidArgumentException('Email must be a string in this format: "[local]@[domain].[ext]".');
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function setPassword($password)
    {
        if (is_string($password) && !empty($password)) {
            $length = $this->stringLength($password);

            if ($length >= 6 && $length <= 60) {
                $this->password = $password;

                return $this;
            }
        }

        throw new \InvalidArgumentException('Password must be a string inclusively between 6 and 60 characters.');
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setRegisterDate($date)
    {
        if (is_int($date) && !empty($date)) {
            // TO DO: date validation unix timestamp is_int

            $this->registerDate = $date;

            return $this;
        }

        throw new \InvalidArgumentException('Register date must be an integer and valid unix timestamp.');
    }

    public function getRegisterDate()
    {
        return $this->registerDate;
    }

    private function stringLength($input)
    {
        $encoding = mb_detect_encoding($input);
        $length   = mb_strlen($input, $encoding);

        return $length;
    }
}


texts: Can I adjust this code which displays a table to run faster?

texts:
this.displayData = function () {
    var i;
    var $thead = $(thead);
    var $tbody = $(tbody);
    var numberOfFields = columnDataFields.length;
    var numberOfRows = data.length;

    // Variables to keep track of even and odd rows.
    var evenRowClass = 'EvenBar';
    var oddRowClass = 'OddBar';
    var t = false;

    $tbody.html('');

    // Find the widths of the column headers and apply the same widths here.
    // However, only do this if the colWidths are thus far undefined.
    if (!colWidths) {
        colWidths = [];
        var headers = $thead.find('td');
        var colWdith;
        for (i = 0; i < headers.length; i++) {
            colwidth = $(headers[i]).outerWidth();
            colWidths.push(colwidth);
            $(headers[i]).css('width', colwidth); // This statement is necessary for cross-browser compatibility. (The problem is with discrepencies in "computed" CSS.)
        }
    }
    for (x in data) {
        var entry = data[x];
        var row = ['
');
        for (i = 0; i < numberOfFields; i++) {
            row.push('');
            row.push(entry[columnDataFields[i]]);
            row.push('	');
        }
        row.push('
');

        $tbody.append(row.join(''));
        t = !t;
    }

    // If a callback function was set, invoke it.
    if (typeof displayCallback === 'function')
        displayCallback();
} // end displayData


texts:
I'm going through some of the problems over on exercism and we were asked to write a program that finds the nth prime. I know Ruby has a Prime class that handles that but the exercise doesn't allow us to use that.

My code works fine but it's very, VERY slow when testing very large numbers (e.g.: the 10,001st prime number). I'm not entirely sure of this is because of inefficient math or bad code.

  def nth(nth_prime)
    raise ArgumentError, 'Invalid Input' if nth_prime == 0

    list_of_primes = []
    results = []

    (1..2000).each do |i|
      (2..(i-1)).each do |j|
        results << i%j
      end
      list_of_primes << i unless results.include? 0
      results.clear
    end

    list_of_primes[nth_prime]
  end

Note: I've limited it to listing the primes from 2 to 2000 for now because that's fast enough for testing purposes. I've also deliberately included 1 in  list_of_primes because the tests (written and provided by exercism.io) test that asking for the 1st prime will give you the number 2 so I needed 2 to be at list_of_primes[1].


texts: Displaying days of the week for all of 2015

texts:
This program is supposed to determine the day of the week for 2015. Could someone tell me how I could shorten my code?

#include <stdio.h>
#include <conio.h>

void findDay(int , int);

int main(void)
{
int jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec;

for(jan=1; jan<=31; ++jan)
{
    printf(" 01/%d/2015 is", jan);
    findDay(jan, 0);
}
for(feb=1; feb<=28; ++feb)
{
    printf("02/%d/2015 is", feb);
    findDay(feb, 3);
}
for(mar=1; mar<=31; ++mar)
{
    printf("03/%d/2015 is", mar);
    findDay(mar, 3);
}
for(apr=1; apr<=30; ++apr)
{
    printf("04/%d/2015 is", apr);
    findDay(apr, 6);
}
for(may=1; may<=31; ++may)
{
    printf("05/%d/2015 is", may);
    findDay(may, 1);
}
for(jun=1; jun<=30; ++jun)
{
    printf("06/%d/2015 is", jun);
    findDay(jun, 4);
}
for(jul=1; jul<=31; ++jul)
{
    printf("07/%d/2015 is", jul);
    findDay(jul, 6);
}
for(aug=1; aug<=31; ++aug)
{
    printf("08/%d/2015 is", aug);
    findDay(aug, 2);
}
for(sep=1; sep<=30; ++sep)
{
    printf("09/%d/2015 is", sep);
    findDay(sep, 5);
}
for(oct=1; oct<=31; ++oct)
{
    printf("10/%d/2015 is", oct);
    findDay(oct, 0);
}
for(nov=1; nov<=30; ++nov)
{
    printf("11/%d/2015 is", nov);
    findDay(nov, 3);
}
for(dec=1; dec<=31; ++dec)
{
    printf("12/%d/2015 is", dec);
    findDay(dec, 5);
}

getch();
return 0;
}
void findDay(int dow, int num)
{
int x;
x=(6+15+3+dow+num)%7;//a formula to calculate the day of the week

switch (x)
{
case 0:
printf(" Sunday\n");
break;
case 1:
printf(" Monday\n");
break;
case 2:
printf(" Tuesday\n");
break;
case 3:
printf(" Wednesday\n");
break;
case 4:
printf(" Thursday\n");
break;
case 5:
printf(" Friday\n");
break;
case 6:
printf(" Saturday\n");
break;
default:
printf("Invalid Input");

}

}


texts: Replacing a sequence of real numbers with another sequence

texts:
I have a simple task:

  Given a sequence of real numbers, replace all of its members larger
  than Z by Z and count the number of replacements.

I solved this task using Scala, but my code looks like imperative-style code. I want to make my code more functional. How can I rewrite my program so it becomes functional-style code?

def main(args : Array[String]) {
    println("Enter Z number: ")
    val z = readDouble();

    println("Enter the length of sequence: ")
    val lenght = readInt();

    var seq: List[Double] = List();

    // Filling sequence
    for (i <- 1 to lenght) {
      println("Enter sequence item № " + i)
      val item = readDouble();
      seq = item :: seq;
    }

    // number of replacements
    var substituteCount = 0;
    //replacing all numbers larger Z by Z
    seq = seq.map(x => {if (x > z){substituteCount+= 1; z} else x})

    println("Replacement count: " + substituteCount)
    println("New sequence: " + seq.reverse.mkString(" "))
}


texts:
It's a pretty simple script really, i just want to know if there is a way to improve it.

#!/bin/env sh

set -o nounset
set -o errexit

if [[ "$#" -ne 3 ]] && [[ "$#" -ne 2 ]];
then
    echo "Usage: ./project.sh [NAME] [GENERATOR] [MAKEFILES]"
    exit 1
fi

mkdir $HOME/Dev/$1
mkdir $HOME/Dev/$1/src/
mkdir $HOME/Dev/$1/build/
cp $HOME/ProjectSetup/CMakeLists.txt $HOME/Dev/$1/

sed -i "s/set(CMAKE_PROJECT_NAME placeholder/set(CMAKE_PROJECT_NAME $1/" $HOME/Dev/$1/CMakeLists.txt

git init $HOME/Dev/$1/
cat > $HOME/Dev/$1/.gitignore << EOL
build/
compile_commands.json
.vscode/
EOL

touch $HOME/Dev/$1/src/main.cpp
cat > $HOME/Dev/$1/src/main.cpp << EOL

int main(int argc, const char* argv[])
{

    return 0;
}
EOL

if [[ "$#" -eq 3 ]];
then
    cmake -G "$2 - $3" -S $HOME/Dev/$1 -B $HOME/Dev/$1/build/ -DCMAKE_EXPORT_COMPILE_COMMANDS=1
else
    cmake -G "$2" -S $HOME/Dev/$1 -B $HOME/Dev/$1/build/ -DCMAKE_EXPORT_COMPILE_COMMANDS=1
fi
ln -s $HOME/Dev/$1/build/compile_commands.json $HOME/Dev/$1/

```


texts: Write a class for Team which should have function to prints players details

texts:
I have written it using aggregation but i feel its not the best way we can do this. Please suggest is there any other way to do this. I think we can also built this without using player class, just store players details in nested list or dict. Please suggest what is the best way.

class Player(object):
    def __init__(self, name, age, skills, style=None):
        self.name = name
        self.age = age
        self.skills = skills
        self.style = style

    def get_player(self):
        print(self.name,self.age,self.skills,self.style)

class Team(object):
    def __init__(self, name):
        self.name = name
        self._players = []

    def add_player(self, obj):
        if isinstance(obj, Player):
            self._players.append(obj)
        else:
            print("Please provide player object")

    def get_players(self):
        for player in self._players:
            player.get_player()

if __name__ == "__main__":

    p1 = Player("Mahendra", 46, "Wicket Kipper", "Right-Hand Batsman")
    p2 = Player("Sachin", 35, "Batsman", "Right-Hand Batsman")
    p3 = Player("Saurabh", 44, "Batsman", "Left-Hand Batsman")
    p4 = Player("Zahir", 38, "Bauwller", "Medium Pace Bauwller")
    p5 = Player("Yuvraj", 43, "All rounder")

    t = Team("India")
    t.add_player(p1)
    t.add_player(p2)
    t.add_player(p3)
    t.add_player(p4)
    t.add_player(p5)

    t.get_players()


texts:
I'm looking for a very simple (at first sight) CommandBus, which will handle some ICommand publication. The CommandBus implementation will find the appropriate IHandler to Execute the Command and then Notify some possible IObservers.

My first step is to make it work, I've chosen to use a synchronous dependency injection pattern which I may extends in the future, maybe using a real ServiceBus with some asynchronous capability.

Here is the abstract definition:

public interface ICommandBus
{
    TResult Publish<TCommand, TResult>(TCommand command)
        where TResult : ICommandResult
        where TCommand : ICommand<TResult>;
}

public interface ICommand<T>
    where T : ICommandResult
{
    int Id_User { get; }
}

public interface ICommandResult
{
    bool Success { get; }

    Exception Error { get; }

    ICollection<ValidationRule> BrokenRules { get; }
}

public interface ICommandHandler<TCommand, TResult>
    where TCommand : ICommand<TResult>
    where TResult : ICommandResult
{
    TResult Execute(TCommand command);
}

public interface ICommandObserver<TCommand, TResult>
    where TCommand : ICommand<TResult>
    where TResult : ICommandResult
{
    void Trigger(TCommand command, TResult result);
}

And here is the CommandBus implementation (using Structuremap as the DI)

public class CommandBus : ICommandBus
{
    private readonly IContainer m_container;

    public CommandBus(IContainer container)
    {
        m_container = container;
    }

    public TResult Publish<TCommand, TResult>(TCommand command)
        where TResult : ICommandResult
        where TCommand : ICommand<TResult>
    {
        using (MiniProfiler.Current.Step("CommandBus.Publish"))
        {
            var handler = m_container.GetInstance<ICommandHandler<TCommand, TResult>>();
            var observers = m_container.GetAllInstances<ICommandObserver<TCommand, TResult>>();

            var result = handler.Execute(command);

            foreach (var observer in observers)
                observer.Trigger(command, result);

            return result;
        }
    }
}

How to use:

public class CreateItemCommand: ICommand<CreateItemResult>
{
    public string Name { get; private set; }
}
public class CreateItemResult: ICommandResult
{
    public bool Success { get; private set; }
}

var command = new CreateItemCommand();
var result = commandBus.Publish<CreateItemCommand, CreateItemResult>(command);

What do you think about this pattern? Do you think it will be easy to upgrade? I'm afraid it can be an obvious bottleneck in my application...

Edit: I just want to past a link to my question about this pattern, in order to simplify all the Generics...


texts: Console application to search for files that contain a match for a regex

texts:
I created a small console application to recursively search a folder and all subfolders for files that contain a match for a regex.

The command line arguments are the path you're looking to search followed by the regex (in .NET regex format).

I break this up into two threads: the main thread loops through the files and puts file data (their content, path, and name) on a concurrent queue. The second thread processes the queue, looking for regex matches.

Would using a Parallel.ForEach loop be better here? The main issue I had with this is that the queue is being modified while we're looping over it, but a Parallel.ForEach loop assumes that you already have a complete collection. The two possibilities I came up with this:

Just read the content of the files, and then do a Parallel.ForEach loop to do the regex.
Process it on the background thread like I'm doing until we're done reading the file contents, then do a Parallel.ForEach loop over any remaining items once we're done.

What I have here works but is slower than I'd like. I'd definitely like feedback on the multithreading I'm doing here, especially if one of the possibilities I mentioned above would be better than what I'm doing (or if there's another possibility that I don't mention above).

namespace SearchByRegex
{
class Program
{
    // I should probably just move this out to its own file
    private class FilePair
    {
        public string Content { get; set; }

        public string FilePath { get; set; }

        public string FileName { get; set; }
    }

    private static ConcurrentQueue<FilePair> fileInformation = new ConcurrentQueue<FilePair>();

    static void Main(string[] args)
    {
        Console.WriteLine("Working...");

        // Command lines are a path followed by the regular expression
        var regex = new Regex(args[1], RegexOptions.Multiline);

        // Process
        Thread thread = new Thread(PrintInformationOnMatches);
        thread.Start(regex);

        SearchDirectory(args[0]);

        while (fileInformation.Any())
        {
            Thread.Sleep(1000);
        }

        thread.Abort();

        Console.WriteLine("Press any key to exit");
        Console.ReadLine();
    }

    /// <summary>
    /// Print information on all files whose content matches the <paramref name="regex"/>
    /// </summary>
    /// <param name="regex">Regex we're looking for</param>
    private static void PrintInformationOnMatches(object regex)
    {
        var castRegex = (Regex)regex;
        while (true)
        {
            // Process the entire queue
            while (fileInformation.Any())
            {
                FilePair pair;
                fileInformation.TryDequeue(out pair);

                if (castRegex.IsMatch(pair.Content))
                {
                    Console.WriteLine($"File name: {pair.FileName}. Path: {pair.FilePath}.");
                }
            }

            // Wait for more stuff on the queue
            Thread.Sleep(1000);
        }
    }

    /// <summary>
    /// Get the contents of the file and put them on the queue
    /// </summary>
    /// <param name="path">Path we are recursively searching</param>
    private static void SearchDirectory(string path)
    {
        string[] files = Directory.GetFiles(path);

        //Console.WriteLine("Path: " + path);
        foreach (string file in files)
        {
            fileInformation.Enqueue(new FilePair { Content = File.ReadAllText(file), FilePath = path, FileName = file });
        }

        foreach (string directory in Directory.GetDirectories(path))
        {
            SearchDirectory(directory);
        }
    }
}
}


texts: Map markers on a canvas that pop up boxes when clicked

texts:
Here's a working version of my code - http://jsfiddle.net/sambenson/g3qsa/#base
How can this be improved upon?

$(function(){
    var box = {},
        island = {},
        canvas = {};

    box.el = $('#box');
    canvas.el = $('#arrow');

    function go(el){
        if(box.el.css('visibility') == 'hidden'){
            reset_name();
            $('.island').addClass('inactive');

            box.top = box.el.offset().top;
            box.corner = {};
            box.corner.left = box.el.offset().left;
            box.corner.right = box.corner.left + box.el.width();

            island.el = el;
            island.top = island.el.offset().top;
            island.left = island.el.offset().left;

            island.el.removeClass('inactive').addClass('active');

            canvas.width = island.left - box.corner.left;
            canvas.height = island.top - box.top;

            canvas.el.css({
                top: box.top,
                left: box.corner.left
            }).attr({
                width: canvas.width,
                height: canvas.height
            });

            var context = canvas.el[0].getContext('2d');

            context.beginPath();
            context.moveTo(0, 0);
            context.lineTo(box.el.width(), 0);
            context.lineTo(canvas.width, canvas.height);
            context.closePath();

            context.fillStyle = "#eaeaea";
            context.fill();

            box.el.css('visibility', 'visible');
            canvas.el.show();
        }
        else {
            close();
        }
    }

    function reset_name(){
        $('#name_holder').text('').css({
            top: -9999,
            left: -9999
        })
    }

    function close(){
        $('.island').removeClass('inactive active');
        box.el.css('visibility', 'hidden');
        canvas.el[0].width = canvas.el[0].width;
        canvas.el.hide();
    }

    $('.island').hover(function(){
        if(box.el.css('visibility') == 'hidden'){
            var t = $(this),
                name = t.text(),
                holder = $('#name_holder');
                top = t.offset().top - 60;
                left = t.offset().left - 50;

            holder.css({
                top: top,
                left: left
            }).text(name);
        }
    }, function(){ reset_name(); })
    .click(function(){ go($(this)); })

    $('.close').click(function(){
       close();
    })

})

Could it be made faster?
Could it be made more efficient?


texts:
Can someone take a look over my bootstrap file and see if you believe it's doing too much or the logic could be better.

<?php

    /*
    * ------------------------------------
    * Autoloader for classes/files
    * ------------------------------------
    */

    function __autoload($class) {
        if(file_exists($file = str_replace("\\","/",str_replace("baremvc\\","",$class)).".php")){
            require_once $file;
        }else{
            throw new Exception($file);
        }
    }

    /*
    * ------------------------------------
    * Get commonly used namespaces
    * ------------------------------------
    */

    use \baremvc\core\library\exception as ex;
    use \baremvc\core\configuration as config;

    /*
    * ------------------------------------
    * Enable session if set in the configuration file
    * ------------------------------------
    */

    !config::enable_sessions ?: session_start();

    /*
    * ------------------------------------
    * Enable debug information if set in the configuration file
    * ------------------------------------
    */

    error_reporting(config::debug_level);
    ini_set('display_errors', intval(config::debug_enabled));

    /*
    * ------------------------------------
    * Try and load the specified class/method
    * ------------------------------------
    */

    $router = new \baremvc\core\library\router;
    $url_object = $router->parse_request_url(@$_SERVER['REDIRECT_URL']);
    try{
        $namespace = "\\baremvc\\controllers\\{$url_object->Controller}";
        $class = new $namespace;
        if(method_exists($class,$url_object->Method)){
            if(!empty($url_object->Get)){
                call_user_func_array(array($class, $url_object->Method), $url_object->Get);
            }else{
                call_user_func(array($class, $url_object->Method));
            }
        }else{
            throw new Exception($url_object->Method);
        }
    }catch(Exception $e){
        echo ex::show_404($e->getMessage());
    }

parse_request_url takes the requested url (e.g. domain.com/this/is/my/request) and checks to see if a controller exists with that name (can be in directories or file).


texts:
Alright, so first, the reason I'm posting this is because I've seen so many tutorials that conflict with each other, and I would like to get this all straightened out. (Ignore the lack of shaders/mvp matrices/etc.)

Here is my simple example code:
You can view it on pastebin here to make it easier to read.

#pragma once

#include <string>
#include <vector>
#include <glm.hpp>

#include "Logger.h"

#include "GL.h"

namespace engine {

    using Index = unsigned int;

    struct Vertex {
        glm::vec3  position;
        glm::vec2  texcoord;
    };

    struct Mesh {
        std::vector<Vertex> vertices;
        std::vector<Index> indices;
    };

    struct MeshRenderer {
        GLsizei count;
        GLuint vao;

        ~MeshRenderer() {
            // Is this the only call needed to clean up a vao?
            glDeleteVertexArrays(1, &vao);
        }
    };

    class Engine {
        Logger logger;
        MeshRenderer mr;

    public:
        Engine() :
            logger{"Engine"} {

            glEnable(GL_CULL_FACE);
            glCullFace(GL_BACK);

            glClearColor(0, 0, 0, 0);

            Mesh mesh;

            mesh.vertices.push_back({{ 0.5f,  0.5f, 0.0f}, {0.5f,  0.5f}});
            mesh.indices.push_back(0);

            mesh.vertices.push_back({{-0.5f,  0.5f, 0.0f}, {-0.5f,  0.5f}});
            mesh.indices.push_back(1);

            mesh.vertices.push_back({{-0.5f, -0.5f, 0.0f}, {-0.5f, -0.5f}});
            mesh.indices.push_back(2);

            mr.count = mesh.indices.size();

            // Only needed temp while binding to vao.
            GLuint vbo, ibo;

            glGenVertexArrays(1, &mr.vao); // Vertex  Array  Object
            glGenBuffers(1, &vbo); // Vertex  Buffer Object (temp)
            glGenBuffers(1, &ibo); // Element Buffer Object (temp)

            glBindVertexArray(mr.vao);

            glBindBuffer(GL_ARRAY_BUFFER, vbo);
            glBufferData(GL_ARRAY_BUFFER, mesh.vertices.size() * sizeof(Vertex), mesh.vertices.data(), GL_STATIC_DRAW);

            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
            glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh.indices.size() * sizeof(Index), mesh.indices.data(), GL_STATIC_DRAW);

            glEnableVertexAttribArray(0);
            glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, position)));

            glEnableVertexAttribArray(1);
            glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, texcoord)));

            glBindVertexArray(0);

            // Is there any reason not to clean these up now that they have been bound to the vao?
            glDeleteBuffers(1, &vbo);
            glDeleteBuffers(1, &ibo);
        }

        void onLoop(double time) {
            glClear(GL_COLOR_BUFFER_BIT);

            glBindVertexArray(mr.vao);
            glDrawElements(GL_TRIANGLES, mr.count, GL_UNSIGNED_INT, nullptr);
        }
    };
}

Basically, I want to know:

Is the VAO setup/initialization shown done correctly, or am I missing any steps or have I done anything sub optimally?
The way I delete the VAO (glDeleteVertexArrays(1, &vao);) is that the only call I need to do to fully delete it?
Is it safe/good practice to delete the VBO and IBO where I do (or should I save these in until the VAO is deleted)?
(Bonus points) What would be the best way to go about updating an existing mesh? For instance if I'm rendering a grid of tiles, but I want to update the texture UVs on specific vertices, what would be the best approach for something like this? (In the past I'd rebuild the mesh manually, and make a new VAO and pass it in again. Is there a way to just add/update/delete specific vertices and/or vertex attributes?)


texts: Re-implementation of `std::tuple` for MCUs

texts:
Background
I'm writing code for an 8-bit MCU with very limited RAM (1KiB) and program flash space (64KiB). I have a C++14 capable compiler with no standard library implementation available. This is a good enough excuse for me to do some recreational template programming. :)
In the project where I intend to use this I need to be able to create a densely packed, complex, configurable tuple of varying types and values. And I need this data structure to be stored in program space, so I need it to be usable as constexpr.
About the code
In the code below I have used uint8_t for the size type because the MCU has 8-bit words and an int (which has to be 16 bits to be standard compliant) thus is "extended precision" for my MCU and incurs speed and program size overhead. And frankly, with 1K of ram I'm not expecting to make tuples with more than 255 elements.
The code is put into a single file for your reviewing pleasure and uses std::forward which is technically not available on my target, but I intend to re-implement it as the next step. This code is written for PC first to be able to debug and test it.
I'm happy for any comments on suggestions on the code, but please bear in mind the target architecture.
tuple_test.cpp
#include <iostream>
#include <type_traits>

//#define PACKED_TUPLES

#ifdef PACKED_TUPLES
#define ATTRIBUTE_PACKED __attribute__((__packed__))
#else
#define ATTRIBUTE_PACKED
#endif

namespace xtd {
  namespace detail {

    template <typename...>
    struct ATTRIBUTE_PACKED pack;

    // Helper class to get a value from a pack.
    // This is required as template functions cannot be
    // partially specialised.
    template <int, typename...>
    struct pack_get;

    template <typename... types>
    struct pack_get<0, types...> {
      static auto get(const pack<types...>& pack) { return pack.value; }
    };

    template <int i, typename first_type, typename second_type, typename... types>
    struct pack_get<i, first_type, second_type, types...> {
      static auto get(const pack<first_type, second_type, types...>& pack) {
        return pack_get<i - 1, second_type, types...>::get(pack.next);
      }
    };

    template <typename type>
    struct ATTRIBUTE_PACKED pack<type> {
      constexpr static int size() { return 1; }

      constexpr pack() = default;
      constexpr pack(type arg) : value(arg) {}

    private:
      const type value;

      template <int, typename...>
      friend struct pack_get;
    };

    template <typename type, typename... types>
    struct ATTRIBUTE_PACKED pack<type, types...> {
      using next_pack = pack<types...>;

      constexpr pack() = default;
      constexpr pack(const type& arg, types&&... args)
          : value(arg), next(std::forward<types>(args)...) {}

      constexpr static int size() { return 1 + next_pack::size(); }

    private:
      const type value;
      const next_pack next;

      template <int, typename...>
      friend struct pack_get;
    };
  }  // namespace detail

  template <typename... types>
  using tuple = detail::pack<types...>;

  template <int i, typename... types>
  auto get(const tuple<types...>& tuple) {
    return detail::pack_get<i, types...>().get(tuple);
  }

  template <typename... types>
  constexpr auto make_tuple(types&&... args) {
    return tuple<types...>(std::forward<types>(args)...);
  }
}  // namespace xtd

extern constexpr auto p = xtd::make_tuple(3, 3.14, "fooo");

int main(int, char**) {
  std::cout << sizeof(p) << std::endl;
  std::cout << p.size() << std::endl;
  auto x = xtd::get<2>(p);
  std::cout << x << std::endl;
}


texts:
I have written code in Kotlin with the objective of computing Pi in few enough lines so that it looks good on a t-shirt.

Can be cut and paste into http://try.kotlinlang.org under "My Programs" and run from browser - I just tested it with version 1.2.41 and it's working.

import kotlin.math.*
import java.math.BigInteger

fun main(args: Array<String>) {
  val r = (4*(4*arccot(5) - arccot(239))).toString()
  println("314 digits of Pi ${r[0]}.${r.substring(1).dropLast(5)}")
}

fun arccot(x:BigInteger):BigInteger {
  var precision = 10.toBigInteger().pow(319) / x
  var total = precision
  var divisor = 1.toBigInteger()

  while(precision.abs() >= divisor) {
    precision = -precision / x.pow(2)
    divisor += 2
    total += precision / divisor
  }
  return total
}

fun arccot(x:Int) = arccot(x.toBigInteger())
operator fun Int.times(x: BigInteger) = this.toBigInteger() * x
operator fun BigInteger.plus(x: Int) = this + x.toBigInteger()

Currently it's longer than I'd like. I would like to shorten without making it less understandable. My vision is to have code that is readable enough it wouldn't be out of place in a production code base.

To give an idea, here's the significantly shorter Python version (which has been printed on a t-shirt and in my opinion looks good and is short enough but also quite readable). Can be run in browser here: https://repl.it/@sek/314-Digits - (there's also a link from there to the t-shirt if you are curious how that looks - the length in question isn't only the number of lines but also the width of the longest line as that determines the font size that can be used)

def pi():
  r = 4*(4*arccot(5) - arccot(239))
  return str(r)[0]+'.'+str(r)[1:-5]

def arccot(x):
  total = power = 10**319 // x
  divisor = 1
  while abs(power) >= divisor:
    power = -power // x**2
    divisor += 2
    total += power // divisor
  return total

print("314 digits of Pi " + pi())


texts: Counting the occurrences of bank account numbers for SPOJ challenge

texts:
I am solving a problem on SPOJ and am currently unsatisfied with my submission time, given that my fastest time is 0.28s (which ranks me 123/5037) and the leading submission is 0.04s.

The problem is pretty simple: Given a list of bank account numbers, print the bank account number along with the frequency at which it is repeated.

  Input

  t [the number of tests <= 5]
  n [the number of accounts<= 100 000]

  [list of accounts]
  [empty line]
  [next test cases]

  Output

  [sorted list of accounts with the number of repeated accounts]
  [empty line]
  [other results]

Example:

Input:
2
6
03 10103538 2222 1233 6160 0142
03 10103538 2222 1233 6160 0141
30 10103538 2222 1233 6160 0141
30 10103538 2222 1233 6160 0142
30 10103538 2222 1233 6160 0141
30 10103538 2222 1233 6160 0142

5
30 10103538 2222 1233 6160 0144
30 10103538 2222 1233 6160 0142
30 10103538 2222 1233 6160 0145
30 10103538 2222 1233 6160 0146
30 10103538 2222 1233 6160 0143

Output:
03 10103538 2222 1233 6160 0141 1
03 10103538 2222 1233 6160 0142 1
30 10103538 2222 1233 6160 0141 2
30 10103538 2222 1233 6160 0142 2

30 10103538 2222 1233 6160 0142 1
30 10103538 2222 1233 6160 0143 1
30 10103538 2222 1233 6160 0144 1
30 10103538 2222 1233 6160 0145 1
30 10103538 2222 1233 6160 0146 1

In order to solve this, I am using a map where the key is the bank account and the value is the frequency of repetition. However, I am first loading the bank accounts into a vector, and I am pretty sure this is one area where I am losing efficiency. I have tried to avoid using the vector, but my efficiency is greatly reduced.

What are some things that I can do to either improve my algorithm, or perhaps increase my I/O speed?

#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(NULL);
  int t;
  std::cin >> t;
  while (t--) {
    int n, i;
    std::cin >> n;
    std::cin.ignore();
    std::vector<std::string> accounts(n);
    for (i = 0; i < n; ++i) {
      std::getline(std::cin, accounts[i]);
    }
    std::cout << "\n";
    std::map<std::string, int> count;
    for (i = 0; i < accounts.size(); ++i) {
      auto map_it(count.find(accounts[i]));
      if (map_it != count.end()) {
        map_it->second++;
      } else {
        count[accounts[i]] = 1;
      }
    }
    for (auto it = count.begin(); it != count.end(); ++it) {
      std::cout << it->first << it->second << "\n";
    }
    if (t != 0) {
      std::string blank;
      std::getline(std::cin, blank);
    }
  }
  return 0;
}


texts: Signal output on Raspberry Pi that acts as input for FPGA

texts:
Problem

I'm writing a verilog program that does the trapezoidal integration method (where a review is also welcome, wink wink). But turns out you need input for these kind of things, so in the overly complicated setup I'm doing, I'm writing a python program on a Raspberry Pi to output inputs for the FPGA which then outputs to a d to a which outputs to an oscilloscope which is where you all go, "Thank goodness I'm not that programmer" and I go half mad.

The main requirements for the code is that it output each bit of the input for the FPGA at a separate pin, as serial data is slower, and that the output be two's complement (i.e., the signals are signed integers, so the bits given to the FPGA must also be signed).

Approach

My code can be broken up into three phases: signal generation, signal conversion, and signal output.

Signal generation

Right now, I'm just using a simple square wave. This is done using

x = 0
signal = 1
while x <= 25:
    if x % 2 == 0:
        signal*=-1
    signals.append(signal)
    x+=1

Signal conversion

This iterates over signals and applies twos_comp() to each. twos_comp() converts the integer to its binary representation (carefully slicing off all the unneeded nonsense) and then if the original value was greater than zero, just returns that. Otherwise, the number is inverted using the invert() function, and then has one added to it, and is returned. Type conversions are rife, and this whole thing is rather hack-y.

This assumes 8 bit numbers.

Signal output

Using RPi.GPIO, a clock pin (which is mapped to the FPGA's clock) is setup and a set of 8 pins is setup for the signal. Again, parallel not serial. For each item in the new list generated by twos_comp(), the program waits for the clock's rising edge (I know this is somewhat frowned upon, but the output needs to be synced to the clock and the clock is also pretty fast, so it's not like it's going to be waiting for a while (50 mega hertz, can be faster). Then, for each item in the 8-bit number, it's outputted to the appropriate pin.

Concerns/reviewing

Any and all comments are welcome in this review, with speed comments (especially in the latter part of the program) extra welcome as I want it to be able to keep up with the FPGA clock. (Speed in the first part obviously isn't as necessary as it all can be done before the FPGA starts up. I also don't know if RPi.GPIO will be able to output the bits fast enough.) As I mentioned earlier, the invert() and twos_comp() functions are...kinda hacky.

Thanks!

Code

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
x = 21
while x <= 28: #signal pins
    GPIO.setup(x, GPIO.OUT)
    x+=1
GPIO.setup(5, GPIO.IN) #clock

signals = []
bit_signals = []

def invert(bit_val):
    new_val = []
    for i in bit_val:
        new_val.append(str(int(not(int(i)))))
    return ''.join(new_val)

def twos_comp(val):
    bin_val = format(val, '09b')[-8:]
    if val < 0:
        return format(int(invert(bin_val),2) + int('1', 2), '08b')
    else:
        return bin_val

x = 0
signal = 1
while x <= 25:
    if x % 2 == 0:
        signal*=-1
    signals.append(signal)
    x+=1

for i in signals:
    bit_signals.append(twos_comp(i))

for i in bit_signals:
    GPIO.wait_for_edge(5, GPIO.RISING)
    counter = 21
    for k in str(i):
        GPIO.output(counter, k) #k will be 0 or 1 which is accepted input
        counter += 1

GPIO.cleanup()


texts: Is the new version of this code more difficult to read and understand than the original? How can it be improved?

texts:
I was asked to do a code review for the following block of code. It implemented a bug fix to prevent some values being added to some drop down lists depending on the user's domain, in an ASP.NET WebForms app. The three lines adding items to the lists were from the pre-bug-fix code (not part of the fix), so I didn't review it.

        //Only add corporate AD domain if the user is a member of it.
        string domainName = "";
        if (Thread.CurrentPrincipal == null)
        {
            //"Missing the thread identity";
        }
        else if (Thread.CurrentPrincipal.Identity.Name.IndexOf("\\") < 0)
        {
            //"No domain detected leave domain name blank.";
        }
        else
        {
            domainName = Utils.GetUserDomain(Thread.CurrentPrincipal).ToUpper();
        }

        if (domainName == Config.AppSettings.Domain.ToUpper())
        {
              domainUserDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
              domainOfficeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
              domainTypeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
        }

I reviewed the code and suggested changing the code to the following:

        //Only add corporate AD domain if the user is a member of it.
        var currentPrincipal = Thread.CurrentPrincipal;
        var hasDomain = currentPrincipal != null && currentPrincipal.Identity.Name.Contains("\\");
        var domainName = hasDomain ? Utils.GetUserDomain(currentPrincipal) : null;

        if (string.Equals(domainName, Config.AppSettings.Domain, StringComparison.OrdinalIgnoreCase))
        {
              domainUserDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
              domainOfficeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
              domainTypeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
        }

When the original developer saw the changes, he agreed with some of it (change of IndexOf to Contains, and ToUpper to String.Equals for case insensitive search), but not all of it. His main complaint was that the new code was more difficult to read and understand, and that the if blocks were clearer than the ternary operator. We weren't able to come to a point of agreement.

Could you please review both the original and new code and suggest improvements to either. Also, please point out any problems in the new code, especially where you think it is worse than the original code.


texts: Project Euler # 56 Powerful digit sum in Python

texts:
A googol (\$10^{100}\$) is a massive number: one followed by one-hundred zeros; \$100^{100}\$ is almost unimaginably
large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.

Considering natural numbers of the form, \$a^b\$, where \$a, b < 100\$, what is the maximum digital sum?

def get_powers(n):
    """Assumes n a range, generates all numbers to the power of all numbers within the range."""
    for num in range(n):
        for power in range(n):
            yield num ** power

def get_digit_sum(n):
    """Assumes n a number, returns sum of digits."""
    return sum(int(digit) for digit in str(n))

def get_maximum(n):
    """Assumes n a range, gets all a ** b within range, returns max sum digits."""
    return max((get_digit_sum(num) for num in get_powers(n)))

if __name__ == '__main__':
    print(get_maximum(100))


texts:
Currently, I'm working on gamification platform and I have the following rules for achieving a new level:

Level 0: When user registers
Level 1: When user confirms account
Level 2: When user completes a quiz
Level 3: When user completes a mission and publish more than 5 comments in the blog
Level 4: When user completes more than two missions and completes a campaign (campaign means donating money for something)
Level 5: Raised at least $50 in campaigns and complete at least two campaigns

Now, I have the following database where I'll keep a track of each user action (e.g. complete_quiz, complete_mission, etc.):

Achievements

id (int)
event (varchar)
amount (int) # used when event has specific value, e.g. money for complete_campaign event
user_id (int)
date_created (int)

When the user make any action (e.g. complete_mission), I'll insert the action in the table above and will call the following method to check if user has new level unlocked:

public function checkIfAchievmentUnlocksNewLevel($userObj)
{
    $currentLevel = $userObj->level;

    $nextLevel = ++$currentLevel

    $isLevelUnlocked = false;

    switch($nextLevel)
    {
        case 0:
        case 1:
            // Each registered user will have these levels by default.
        break;
        case 2:
            $completedQuiz = $this->db->select("SELECT " . $this->fieldsList . " FROM " . $this->table . " WHERE event = :event AND user_id = :user_id ", array(':event' => 'complete_quiz', ':user_id' => $userObj->id));
            $isLevelUnlocked = count($completedQuiz) ? true : false;
        break;
        case 3:
            $completedMissions = $this->db->select("SELECT " . $this->fieldsList . " FROM " . $this->table . " WHERE event = :event AND user_id = :user_id", array(':event' => 'complete_mission', ':user_id' => $userObj->id));
            $wildwireComments = $this->db->select("SELECT " . $this->fieldsList ." FROM " . $this->table . " WHERE event = :event AND user_id = :user_id", array(':event' => 'wildwire_comment', ':user_id' => $userObj->id));
            $isLevelUnlocked = (count($completedMissions) && count($wildwireComments) >= 5) ? true : false;
        break;
        case 4:
            $completedMissions = $this->db->select("SELECT " . $this->fieldsList . " FROM " . $this->table . " WHERE event = :event AND user_id = :user_id", array(':event' => 'complete_mission', ':user_id' => $userObj->id));
            $completedCampaigns = $this->db->select("SELECT " . $this->fieldsList ." FROM " . $this->table . " WHERE event = :event AND user_id = :user_id", array(':event' => 'complete_campaign', ':user_id' => $userObj->id));
            $isLevelUnlocked = (count($completedMissions) >= 2 && count($completedCampaigns)) ? true : false;
        break;
        case 5:
            $campaignRaisedMoney = $this->db->select("SELECT SUM(amount) FROM " . $this->table . " WHERE event = :event AND user_id = :user_id", array(':event' => 'complete_campaign', ':user_id' => $userObj->id));
            $completedCampaigns = $this->db->select("SELECT " . $this->fieldsList ." FROM " . $this->table . " WHERE event = :event AND user_id = :user_id", array(':event' => 'complete_campaign', ':user_id' => $userObj->id));
            $isLevelUnlocked = (count($compaignRaisedMoney) >= 50.00 && count($completedCampaigns) >= 2) ? true : false;
        break;
    }

    if($isLevelUnlocked)
    {
        $userHelper->setLevel($nextLevel);
    }

}

This code is working now, but I want to refactor it and am looking for any suggestions on how to improve it.


texts:
I'm working on this challenge:

  Given an array of integers of size N. Assume ‘0’ as invalid number and all other as valid number. Write a program that modifies the array in such a way that if next number is  valid number and is same as current number, double the current number value and replace the next number with 0. After the modification, rearrange the array such that all 0’s are shifted to the end and the sequence of the valid number or new doubled number is maintained as in the original array.

  Examples:

Input : arr[] = {2, 2, 0, 4, 0, 8}
Output : 4 4 8 0 0 0

Input : arr[] = {0, 2, 2, 2, 0, 6, 6, 0, 0, 8}
Output :  4 2 12 8 0 0 0 0 0 0

  Input:

  The first line of the input contains an integer T, denoting the number of test cases. Then T test case follows. First line of each test contains an integer N denoting the size of the array. Then next line contains N space separated integers denoting the elements of the array.

  Output:

  For each test case print space separated elements of the new modified array on a new line.

  Constraints:

  1 ≤ T ≤ 10³

  1 ≤ N ≤ 10⁵

  Example:

  Input:

2
5
2 2 0 4 4
5
0 1 2 2 0

  Output:

4 8 0 0 0
1 4 0 0 0

I managed to get my code to work for the given input and output cases. However, when I submit it, I get a "time limit exceeded" message.

#include <stdio.h>

int main() {
    //code
    int x,q,n,i,j,k,m,arr[100000],d,t;
    scanf("%d",&x);
    for(q=0;q<x;q++)
    {
        scanf("%d",&n);
        for(t=0;t<n;t++)
        {
            scanf("%d",&arr[t]);
        }
        for(i=0;i<n;i++)
        {
            if(i>0)
            {
                if(arr[i]==arr[i-1])
                {
                    arr[i-1]=arr[i]+arr[i-1];
                    arr[i]=0;
                }
            }
        }
        j=n-1;
        k=0;
        while(k != j)
        {
            if(arr[k]==0)
            {

                for(m=0;k+m+1<=j;m++)
                {
                    arr[k+m]=arr[k+m+1];
                }
                arr[j]=0;
               j--;

            }
            else
            {
                k++;
            }
        }
        for(d=0;d<n;d++)
        {
            printf("%d",arr[d]);

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

    }
    return 0;
}


texts: Multiple Formats: Reading Working Routine From File

texts:
It is my job to store the workout routine for a given individual in a multimap<string, Exercise*> using an overloaded extraction operator in main. I wanted to know if my code for said operator can be simplified and made more intuitive. There are three classes, but I have only shown Routines; the others seem trivial to include. Implementations will be done in the header file. I will be extracting information from the following file (routine.txt):

Donald Duck,2
Chin-ups,30
Lat Pulldown,20,90
David Ash, 2
Push-ups,5
Wrist curl,10, 2

The format is name,numberOfExercises followed by numberOfExcercises exercises. Each exercise involves weights or does not. A weighted exercise is formatted as exerName,reps,weight. A non-weighted exercise is formatted as exerName,reps. The inclusion of a space after a comma is not a mistake. main contains the following:

int main() {
   Routines routines;
   string name;
   ifstream inf("routines.csv");

   inf >> routines;
}

The routines class has the following:

#include <fstream>
#include <map>
#include "exercise.h"
#include "weightedexercise.h"

using namespace std;

class Routines
{
  multimap<string, Exercise*> routineMap;

public:
  friend istream& operator>>(istream& is, Routines& rout)
  {
    string name, line;
    char comma;
    int numEx, rep, weight = 0;
    // numEx is number of exercises.
    // name is name of person. line is the exercise information.

    getline(is, name, ',');

    do
    {
      is >> numEx;
      getline(is, line);

      for(int i = 0; i < numEx; i++)
      {
        getline(is, line, ',');
        is >> rep;
        is.get(comma);
        if(comma == ',')
          is >> weight;

        if(weight)
        {
          rout.routineMap.insert(multimap<string,
          Exercise *>::value_type(name, new WeightedExercise(line, rep, weight)));
          getline(is, line);
        }
        else
        {
          rout.routineMap.insert(multimap<string,
          Exercise *>::value_type(name, new Exercise(line, rep)));
        }

        weight = 0;
      }
    } while(getline(is, name, ','));
  }
};


texts: Scraping PubMed query results: follow-up

texts:
I recently posted a question looking for feedback on a script I wrote (see: Scraping PubMed query results)

Since then I have re-written it into a class, which I have posted below.  How does it look?  How can I improve upon it?

class PubMedQuery {

private $query;
private $searchParameters;
private $searchURL;
private $fetchParameters;
private $fetchURL;
private $searchResults;
private $fetchResults;
private $matches;
private $matchRegex;
private $emailAddresses;

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

public function setSearchParameters() {
    $this->searchParameters = array(
        'db'         => 'pubmed',
        'term'       => $this->query,
        'retmode'    => 'xml',
        'retstart'   => '0',
        'retmax'     => '1000',
        'usehistory' => 'y'
    );
}

public function getSearchParameters() {
    return $this->searchParameters;
}

public function setFetchParameters() {
    $this->fetchParameters = array(
        'db'        => 'pubmed',
        'retmax'    => '1000',
        'query_key' => (string) $this->searchResults->QueryKey,
        'WebEnv'    => (string) $this->searchResults->WebEnv
    );
}

public function getFetchParameters() {
    return $this->fetchParameters;
}

public function setSearchURL() {
    $this->baseSearchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?';
    $this->searchURL = $this->baseSearchURL . http_build_query($this->getSearchParameters());
}

public function getSearchURL() {
    return $this->searchURL;
}

public function setFetchURL() {
    $this->baseFetchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';
    $this->fetchURL = $this->baseFetchURL . http_build_query($this->getFetchParameters());
}

public function getFetchURL() {
    return $this->fetchURL;
}

public function setSearchResults() {
    $this->setSearchParameters();
    $this->setSearchURL();
    $this->searchResults = simplexml_load_file($this->getSearchURL());
}

public function getSearchResults() {
    $this->setFetchParameters();
    $this->setFetchURL();
    return file_get_contents($this->getFetchURL());
}

public function setEmailAddresses() {
    $this->matches = array();
    $this->matchRegex = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/';
    preg_match_all($this->matchRegex, $this->getSearchResults(), $this->matches);
    $this->emailAddresses = array_unique(array_values($this->matches[0]));
}

public function getEmailAddresses() {
    $this->setSearchResults();
    $this->getSearchResults();
    $this->setEmailAddresses();
    return $this->emailAddresses;
}
}

//Example using search term "psoriasis"
$query  = new PubMedQuery('psoriasis');
echo implode('<br />', $query->getEmailAddresses());


texts:
Given a JavaScript map object of dependencies and their dependencies,
  determine order to install them:

  Example:

  Input:

{
  p1: [p2, p3],
  p2: [p3],
  p3: []
}

  Output:

[p3, p2, p1]

I really feel like there's a dynamic or recursive solution to this that I can't figure out. Is this true? Can it be done better than my approach? Here's my approach with a while loop.

function installDeps(depsList) {
    var installed = [];
    var order = [];

    while (order.length < Object.keys(depsList).length) {

        for (var depsItem in depsList) {

            if (!installed[depsItem]) {
                var installable = true;

                for (var dep = 0; dep < depsList[depsItem].length; dep++) {
                    if (!installed[depsList[depsItem][dep]]) {
                        installable = false;
                        break;
                    }
                }

                if (installable) {
                    order.push(depsItem);
                    installed[depsItem] = true;
                }
            }
        }
    }

    return order;
}


texts: Splitting URL query string to key-value pairs

texts:
I have a URL query string "key={value}&key2={value2}&key3={value3}" and have to produce a key-value pair of the string by splitting & and =. Also, I have to watch out for corner cases such that if a key isn't present do not add it to the hash map but if a value is missing the key can be added with an empty value. One way is to first split the string by & and finally by =. So this can be accomplished but having two passes. But I am attempting to accomplish this in one pass.

First idea: I came up with one pass using the split function, but it didn't account for corner cases.

public Map<String, String> splitString(String s) {
    // String s represents ParamAndMacro
    String[] split = s.split("=|\\&");
    int length = split.length;
    Map<String, String> maps = new HashMap<>();
    for (int i=0; i<length; i+=2){
          maps.put(split[i], split[i+1]);
     }
    return maps;
}

Second idea: One pass with certain conditions and using StringBuilder:

public Map<String, String> splitString(String s){
 Map<String, String> maps = new HashMap<>();
 int length = s.length();
 StringBuilder sb = new StringBuilder();
 String key = "";
 String value = "";

char prev = ' ';
for (int i=0; i<length; i++) {
    char a = s.charAt(i);
    if ( a != '=' && a != '&' && prev != a) {
           sb.append(a);
      }
    //finds a key
    else if( a == '=' && prev != a && prev != '&') {
          key = sb.toString();
          sb = new StringBuilder();
      }
    // finds a value and also ensuring a key is not empty
    else if (a=='&' && prev != a && prev != '=') {
          value = sb.toString();
          sb = new StringBuilder();
          maps.put(key, value);
            }
    // checks corner case to see if a value is empty
    else if (prev=='=' && a == '&') {
          value = "";
          maps.put(key, value);
          sb = new StringBuilder();
    }
   //how to check if a key is missing and skip to other pair

            prev = a;
    }
    return maps;
}

My concern is whether my code is efficient in terms of splitting and using StringBuilder. Please feel free to improve or give suggestions.


texts: Proper way to cancel WebClient in BackgroundWorker

texts:
I have a WPF application that needs to get a XML document using a web request. The request is based on an id that the user enters. If the user enters a second id, before the first returns, I would like to cancel the first request, and start over with the second id. The following works, but I'm not sure if there is an easier way, or if this is correct. I am basically passing a ManualResetEvent reset event to a BackgroundWorker so that I can signal the thread to cancel the web request.

Is this approach poor form? Is passing in a reset event better than having a loop within the function that tests the DoWorkEventArgs::Cancel property every tenth of a second? Also, is there a way to delay the call to RunWorkerAsync until the background worker isn't busy, without blocking the thread? Or should I just create a new background worker every time?

Any input is much appreciated.

This is what I have in my window.xaml.cs.

    BackgroundWorker itemBackgroundWorker = new BackgroundWorker();
ManualResetEvent itemCancel = new ManualResetEvent(false);
private void tbID_TextChanged(object sender, TextChangedEventArgs e)
{
    int id;
    if (!int.TryParse(textBoxID.Text, out id))
        return;

    while (itemBackgroundWorker.IsBusy)
    {
        itemCancel.Set();
    }

    itemCancel.Reset();
    itemBackgroundWorker.RunWorkerAsync(new object[] { id, itemCancel });

}
void baselineSessionBackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    Object[] args = (Object[])e.Argument;

    int id = (int)args[0];
    ManualResetEvent cancel = (ManualResetEvent)args[1];
    try
    {
        currentItem = webFunctions.getItem(id, cancel);
    }
    catch (Exception exx)
    {
        System.Diagnostics.Debug.WriteLine("Find run {0} failed with {1}", id, exx.Message);
        currentItem = null;
    }
}
void baselineSessionBackgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    currentItemContentControl.GetBindingExpression(ContentControl.ContentProperty).UpdateTarget();
}

This is what I have for the static getItem method.

static string detailXMLQuery = "http://....";
public static myItem getItem(int id, ManualResetEvent cancelEvent = null)
{
    ManualResetEvent readFinishedEvent = new ManualResetEvent(false);
    if (cancelEvent == null)
        cancelEvent = new ManualResetEvent(true);
    else
        cancelEvent.Reset();

    Stream result = null;
    WebClient client = new WebClient();
    client.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
    {
        if (e.Error != null)
            System.Diagnostics.Debug.WriteLine("Error getting XML:" + e.Error.Message);
        else
            result = e.Result;

        System.Diagnostics.Debug.WriteLine("Set finished state");
        readFinishedEvent.Set();
    };
    client.OpenReadAsync(new Uri(string.Format(detailXMLQuery, id)));

    ManualResetEvent.WaitAny(new WaitHandle[] { cancelEvent, readFinishedEvent }, 10000);

    if (!readFinishedEvent.WaitOne(0))
    {
        client.CancelAsync();
        System.Diagnostics.Debug.WriteLine("Error getting XML: The request timed out or was canceled");
        throw new Exception("The request timed out or was canceled");
    }

    XmlDocument doc = new XmlDocument();
    doc.Load(result);

    //parse xml, test cancelEvent.Wait(0) to see if cancel has been signaled.

    return new myItem();
}


texts: Saving player name throughout script-launches

texts:
I would like to use this in a program to save users' names even after they relaunch the script. I was just wondering if there were some ways I could clean up this code.

Note: this currently was made to not support name changing, but could possibly be implemented in the future.

if os.path.isfile('names.json'): # if there is a file with names...
    text_file = open("names.json") # only open it in normal mode
else: # if not...
    text_file = open("names.json", "w+") # make one

if os.stat("names.json").st_size > 0:
    for line in text_file:
        if line.istitle():
            player_name = line
        else:
            player_name = console.input_alert('What is your name? ').title()
            text_file = open("names.json", "w")
            text_file.write(player_name)
            text_file.close()
else:
    player_name = console.input_alert('What is your name? ').title()
    text_file = open("names.json", "w")
    text_file.write(player_name)
    text_file.close()


texts: Next, greater permutation of digits of a number

texts:
Was looking at this question (which I initially misunderstood completely), to which Peter Taylor posted a good answer outlining a much better algorithm.

For kicks, I implemented it in Ruby, but I feel like it can be done more cleanly:

def next_greater_permutation(integer)
  digits = integer.to_s.chars.map(&:to_i)               # get digits
  k = digits.each_cons(2).to_a.rindex { |a, b| a < b }  # find k
  return integer if k.nil?                              # no k found, return the input unaltered
  head, tail = digits[0..k], digits[k+1..-1]            # split digits into two arrays
  l = tail.rindex { |n| n > head.last }                 # find l (local to the tail)
  head[k], tail[l] = tail[l], head[k]                   # swap the two values
  (head + tail.reverse).join.to_i                       # glue back together, return
end

(The k and l names are in keeping with the names used in the algorithm; usually I'd use more verbose names.)

It's not super complex or anything, but I just feel like there's a bit too much going on. I'm used to array-manipulation in Ruby being a matter of finding the right methods and chaining them, rather than fiddling with indices. Just feels like I'm missing some obvious shortcut.

To wit, the algorithm (quoted from Wikipedia) is:

  Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
  Find the largest index l greater than k such that a[k] < a[l].
  Swap the value of a[k] with that of a[l].
  Reverse the sequence from a[k + 1] up to and including the final element a[n].


texts: Matching a set of conditions based on keywords to text

texts:
I am currently working on a function that should return true or false based on a condition written in string by a user. The condition will look something like this:

((dog OR cat) AND *Horse*)

The () grouping objects and *word* making the search case insensitive.

How I approached the problem was to have a string that would replace the words by True or False and then simply do an eval() of the new string, giving us the final result.

For example ((dog OR cat) AND *Horse*) would become ((True or False) and True) if applied to the sentence "My dog is not a horse, obviously",

What I don't like about my code it is that it looks really messy, is there a better way to do this task?

import re
def text2cond(text, condition):
    """Will transform a string into a condition usable by tweet_filter"""
    # We will need to give modularity to this
    s = ""
    for token in condition.split():
        regex = None
        if token.startswith('('):
            open_par = 0
            case_sens = False
            for char in token:
                if char == "(":
                    open_par = open_par + 1
                elif char == "*":
                    case_sens = True
            if case_sens:
                regex = r"\b" + re.escape(token[open_par+1:-1]) + "\\b"
                if re.search(regex, text, re.IGNORECASE):
                    s= s + ("("*open_par + "True ")
                else:
                    s= s + ("("*open_par + "False ")
            else:
                regex = r"\b" + re.escape(token[open_par:]) + "\\b"
                if re.search(regex, text):
                    s= s + ("("*open_par + "True ")
                else:
                    s= s + ("("*open_par + "False ")
        elif token.endswith(')') and not token.startswith("*"):
            close_par = 0
            for char in token:
                if char == ")":
                    close_par = close_par + 1
            regex = r"\b" + re.escape(token[:-close_par]) + "\\b"
            if re.search(regex, text):
                s= s + ("True" + ")"*close_par + " ")
            else:
                s= s + ("False" + ")"*close_par + " ")
        elif token.lower() == "or":
            s= s + ("or ")
        elif token.lower() == "and":
            s= s + ("and ")
        elif token.lower() == "not":
            s= s + ("not ")
        elif token.startswith('*'):
            close_par = 0
            for char in token:
                if char == ")":
                    close_par = close_par + 1
            regex = r"\b" + re.escape(token[1:-1-close_par]) + "\\b"
            if re.search(regex, text, re.IGNORECASE):
                s= s + ("True" + close_par*")")
            else:
                s= s + ("False" + close_par*")")
    return s

_condition = "((dog OR cat) AND *Horse*)"
_text = "My dog is obviously not a horse"

print(text2cond(_text, _condition))
print(eval(text2cond(_text, _condition)))


texts: Running SSH commands on multiple servers

texts:
At the company I work at, we have no real way to quickly execute shell commands on all of our customers systems, which often results in what we call Tiny Tim tasks, where the list of all of our systems is split between the 5 devs we have, and we simply go through one-by-one, SSHing into each one and executing the necessary commands.

To streamline this process, I created a script in Python3 using Paramiko for SSH.
The script takes the path to a private OpenSSH key from command-line args, reads a list of hosts from a file called hosts.txt (lines in this file can be commented by prepending them with --), and a list of shell commands from a file called cmds.txt. Due to the way we set up our customers' systems, each domain has 2 servers, so the script loops over each host in the list twice, prepending disc1. and disc2. respectively to send the commands to both servers.

from paramiko.client import AutoAddPolicy
from paramiko.client import SSHClient
import sys
from sys import argv

if len(argv) < 2:
    print("Invalid args!")
    print("Usage: python3 run.py <private ssh key filepath>")
    exit()

with open('cmds.txt') as c:
    cmds = c.readlines()

with open('hosts.txt') as f:
    lines = f.readlines()

for line in lines:
    for i in range(1, 3):
        line = line.strip()
        host = "disc%s.%s" % (i, line)
        if line.startswith('--'):
            print("Host %s began with --, skipping" % line)
            continue
        client = SSHClient()
        client.set_missing_host_key_policy(AutoAddPolicy)
        client.load_system_host_keys()
        try:
            print("[%s]> Connecting as root on port 22..." % host)
            client.connect(host, 22, 'root', None, None, argv[1])
        except KeyboardInterrupt:
            break
        except Exception as err:
            print("[%s]> Connection failed: %s" % (host, err))
            continue
        for c in cmds:
            print("[%s]> Executing %s..." % (host, c.strip()))
            stdin, stdout, stderr = client.exec_command(c)
            print(stdout.read().decode('utf-8'))
            print(stderr.read().decode('utf-8'))
        client.close()
        print("[%s]> Done" % host)

I ran it through PEP8 and surprisingly didn't get any errors or warnings, but it's still quite messy and I'd appreciate feedback.


texts:
Given a string, reverse only the vowels present in it and print the resulting string.
example
input: ransomware
output: rensamwora

Here is my solution:

import java.util.Scanner;

public class ReversingVowels {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int numberOfTestCases = scanner.nextInt();

        while (numberOfTestCases --> 0) {
            StringBuilder stringWhoseVowelsShouldBeReversed = new StringBuilder(scanner.next());
            System.out.println(reverseVowels(stringWhoseVowelsShouldBeReversed));
        }

        scanner.close();
    }

    private static String reverseVowels(StringBuilder string) {

        if (string.length() == 0 || string.length() == 1) return string.toString();

        int start = 0;
        int end = string.length() - 1;

        while (true) {
            while (! isVowel(string.charAt(start))) {
                start++;
            }
            while (! isVowel(string.charAt(end))) {
                end--;
            }
            if (start >= end) {
                break;
            }
            else {
                swapVowels(string, start, end);
                start++;
                end--;
            }
        }
        return string.toString();
    }

    private static boolean isVowel(char character) {
        switch(character) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u': return true;
        default: return false;
        }
    }

    private static void swapVowels(StringBuilder string, int index1, int index2) {
        char tmp = string.charAt(index1);
        string.setCharAt(index1, string.charAt(index2));
        string.setCharAt(index2, tmp);
    }
}

Questions:

Are there any bad practises
Are there any issues
Can this be improved


texts: List of lists of arrays, zipping, modifying in place

texts:
I came back to some old code today and freaked out.  I was like "How does this even work, and if it works it can't do what I intended."  I ran a few quick tests and confirmed it did actually do what was intended.  I know the long term solution is to avoid this situation by having good unit tests -- then I don't need to freak out, I know the code is doing what I expect (New years resolution right there.)

But it wasn't that the code didn't do what it was supposed to, it did.  What it is doing is kind of complex, and it doesn't make it clear.

orig is a List of list of numpy arrays.  All the inner lists have the same lengths.

The information in orig is known as knowledge.  In particular each matrix inner list has 1-3 piece of knowledge, these knowledge are in have names the first is weight, the second is upwards-bias and the third downwards-bias

Each inner list comes is the knowledge of some particular object called a layer.  When those objects are collected to make a more knowledgeable object, then that object also has knowledge with is the list of the knowledge of its component parts.  So the outer list is a List of knowledge of layers. And is the overall knowledge

Sometimes I would like to destroy some of that knowledge by replacing all the matrices in a layer with a randomly valued matrices of the same size and I would like to specify that with a parameter called layer_nums_to_reset.

This parameter is a list of Booleans; it is equal in length to the outer list.

def rand_mat(rows,cols=None):
    if cols==None:
        ret =np.random.normal(0,0.01,(rows,))
    else:
        ret = np.random.normal(0,0.01,(rows,cols))
    return ret

def reset_layers(layer_nums_to_reset,*orig):
    assert(len(layer_nums_to_reset)  == len (orig[0]))
    def random_like(mat):
        return rand_mat(*mat.shape)

    news = [ [] for _ in orig]

    for layer_info in zip(layer_nums_to_reset, *orig):
        reset = layer_info[0]
        knows = layer_info[1:]
        for new_know_list, old_know in zip (news,knows):
            new_know = random_like(old_know) if reset else old_know
            new_know_list.append(new_know)

    return news

Since this code scares me mere months later, it needs to be improved.  It is a complicated idea, so it is not surprising the implementation is complicated.


texts: Correct usage of EF's DBContext in ASP.NET MVC application with Castle Windsor

texts:
I am trying to use Entity Framework as simple as posible. Use UnitOfWork and Repository patterns seems to be overkill because whole web application will be pretty straightforward. I came with this idea:

public class Entity
{
    ...
}

public class MyContext : DbContext
{
    //Set database connection details here.

    public DbSet<Entity> Entities{ get; set; }
}

Register DBContext with my implementation:

public class PersistenceInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Component.For<DbContext>()
                                    .ImplementedBy<MyContext>()
                                    .LifestylePerWebRequest()
                          );
    }
}

And finally I am using DBContext in controller this way:

public class HomeController : Controller
{
    private DbContext db;

    public HomeController(DbContext db)
    {
        this.db = db;
    }

    public ActionResult Index()
    {
        var entity = new Entity
        {
            //Set properties here.
        };

        db.Set<Entity>().Add(entity);
        db.SaveChanges();

        return View();
    }
}

Is this correct approach? Could there be any memory leaks or potential DBContext lifetime management problems? Could there be any problem with too many database connections opened?

I would say that this could be correct. From my quick testing it looks like it is working even when I need to use DBContext in component which is then used in controller. So DBContext instance will be shared for everything per one request. Which is the way how it should be used, I guess.


texts:
I'm working on one easy question (Leetcode 1275. Find Winner on a Tic Tac Toe Game) and am wondering how I can make the code even cleaner.

class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        from collections import Counter

        def is_win(pos: List[List[int]]) -> bool:
            pos = set(tuple(i) for i in pos)
            d1, d2 = set([(0, 0), (1, 1), (2, 2)]), set([(0, 2), (1, 1), (2, 0)])
            x = Counter(i for i, _ in pos)
            y = Counter(i for _, i in pos)
            d1 -= set(pos)
            d2 -= set(pos)
            return (3 in x.values()) or (3 in y.values()) or not d1 or not d2

        a, b = moves[::2], moves[1::2]
        A, B = is_win(a), is_win(b)
        if A:
            return 'A'
        elif B:
            return 'B'
        elif not A and not B and (len(moves) == 9):
            return 'Draw'
        return 'Pending'


texts: Angular Websocket service with wait for response sending

texts:
I am writing an Angular Websocket service that can send messages to a server and then can subscribe to the response.
I am grateful for every suggestion to improve this.

import { Injectable, OnDestroy } from '@angular/core';
import {webSocket, WebSocketSubject} from "rxjs/webSocket";
import {of, from, Observable, timer, BehaviorSubject, pipe, EMPTY} from "rxjs";
import {share, filter, timeout, switchMap, take, catchError, mergeMap} from "rxjs/operators";

export class WsMessage{
  Id: number;
  TimeStamp: Date;
  ResponseId: number;
  MessageData: string;
}

class MessageQueue{
  Message: WsMessage;
  TimeStamp: Date;
  SyncId: number;
}

@Injectable({  providedIn: 'root'})
export class WebSocketServiceService implements OnDestroy {
  // Each message has a maximum lifetime of 10 mimnutes.
  private readonly MaxMessageQueueTime = 600;
  private clearQueueTimer: any;
  private messageQueue: Array<MessageQueue> = new Array<MessageQueue>();
  private socket: WebSocketSubject<WsMessage>;
  private idGenerator: number;

  private messageReceiver = new BehaviorSubject<WsMessage>(null);
  public OnMessages: Observable<WsMessage>;

  constructor(){
    this.OnMessages = this.messageReceiver.asObservable();
      // Check every 30s for clearing old messages.
    this.clearQueueTimer = setInterval(() =>{
      if(this.messageQueue){
        let maxTime = new Date();
        maxTime = new Date(maxTime.setTime(maxTime.getTime() +
        (this.MaxMessageQueueTime * 1000)));
        this.messageQueue= this.messageQueue.filter(m => m.TimeStamp <= maxTime);
      }
    }, 30000);
  }

  public Init(url: string){
      this.idGenerator = 0;
      if(this.socket!= null) {
        this.socket.unsubscribe();
        this.socket = null;
      }
      this.socket = webSocket<WsMessage>({
        url: url,
        openObserver: {
          next: value => {
            console.log(value);
          }
        }
      });
      this.socket.subscribe(msg => {
        if(msg != null && msg.ResponseId > 0){
          let m = new MessageQueue();
          m.SyncId = msg.Id;
          m.Message = msg;
          m.TimeStamp = new Date();
          this.messageQueue.push(m);
        }
        this.messageReceiver.next(msg);
        console.log("msg received: " + msg);
      },
      error1 => {
        console.log("error received: " + error1);
      },
      () => {
        console.log("connection closed!");
      });
    }

    public sendAndWait(msg: WsMessage, wait: number): Observable<WsMessage>{
      if(msg == null){
        return null;
      }
    let id = this.idGenerator++;
    msg.Id = id;
    if(this.socket == null){
      return null;
    }
    this.socket.next(msg);
    let result = this.OnMessages.pipe(
      filter(p => p.Id == id),
      take(1),
      timeout(wait),
      catchError((error) => {
        console.log("timeout: " + error);
        return EMPTY;
      })).pipe(share());

    result.pipe(untilDestroyed(this)).subscribe(value => {
      if(value != null) {
        this.messageQueue.splice(this.messageQueue.findIndex(i => i.SyncId == id), 1);
      }
    });
    return result;
  }

  ngOnDestroy(): void {
    clearInterval(this.clearQueueTimer);
    if(this.socket != null) {
      this.socket.unsubscribe();
    }
  }
}


texts:
I'm arguing here with a colleague over two implementations of how to handle a processing logic:

VERSION 1:

public class SomeManager {
    private readonly Dictionary<Type, Action<IData>> dataHandlers;

    public SomeManager() {
        dataHandlers = new Dictionary<Type, Action<IData>> {
            {typeof(DataTypeOne), HandleDataTypeOne},
            {typeof(DataTypeTwo), HandleDataTypeTwo},
            {typeof(DataTypeThree), HandleDataTypeThird}
            //... and so on
        };
    }

    //... could be other code here

    public void Process(IData data) {
        var dataType = data.GetType();

        if (!dataHandlers.ContainsKey(dataType )) {
            Log.Error(string.Format("Unrecognized data type: {0}", dataType ));
            return;
        }

        dataHandlers[dataType ](data);
    }

    private void HandleDataTypeOne(IDispatchData data) {
        //...specific handling here
    }

    private void HandleDataTypeTwo(IData data) {
        //...specific handling here
    }

    private void HandleDataTypeThree(IData data) {
        //...specific handling here
    }
}

VERSION 2:

public class SomeManager {
    public SomeManager() {
    }

    //... could be other code here

    public void Process(IData data) {
        if (data is DataTypeOne) {
            HandleDataTypeOne(data);
        } else if (data is DataTypeTwo) {
            HandleDataTypeTwo(data);
        } else if (data is DataTypeThree) {
            HandleDataTypeThree(data);
        //other cases here
        } else {
           Log.Error(string.Format("Unrecognized data type: {0}", data.GetType()));
        }
    }

    private void HandleDataTypeOne(IDispatchData data) {
        //...specific handling here
    }

    private void HandleDataTypeTwo(IData data) {
        //...specific handling here
    }

    private void HandleDataTypeThree(IData data) {
        //...specific handling here
    }
}

In our case, performance is not an issue.

We are talking here about a specific scenario of 5 data types.


texts:
I posted a question last week about refactoring an after_create callback. The code in this question is for the create action. I'm using Stripe to handle credit card payments and am roughly following the railscast on Stripe integration.

Here's my create action on the Payment model:

def create
  @unpaid_subs = Subscription.where(:user_id => current_user.id).unpaid.includes(:course)
  @payment = Payment.new(params[:payment])

  @payment.user_id = current_user.id
  @payment.email = current_user.email
  @payment.kind = @payment.determine_kind
  @payment.amount = calculate_cost(@unpaid_subs)

  if @payment.save_with_payment
    redirect_to dashboard_url, :notice => "Thank you for Paying!"
  else
    render :action => 'new'
  end
end

I am going to change the model associations so that payment belongs_to :user, so setting the user_id and email will go away. Here's the save_with_payment method:

def save_with_payment
  if valid?
    charge = Stripe::Charge.create(amount: amount, description: "Charge for #{email}", card: stripe_card_token, currency: "usd")
    save!
  end
rescue Stripe::InvalidRequestError => e
  logger.error "Stripe error while creating charge: #{e.message}"
  errors.add :base, "There was a problem with your credit card."
  false
end

determine_kind is a simple if conditional for setting the kind attribute. calculate_cost is in a module right now and included where needed.

def calculate_cost(unpaid) # Used to return amount total in cents for payment
  @amount_in_pesos = BigDecimal.new(unpaid.size) * COURSE_COST
  @amount_in_cents = (@amount_in_pesos.div(EXCHANGE_RATE, 10).round(2) * 100).to_i
  @amount = @amount_in_cents
  @amount
end

So, I'm mainly wanting general suggestions for improvement of this code. I was a little confused as to where calculate_cost should go (maybe as a method on the Payment model, even though it doesn't use an instance of Payment). Is there any better way to handle the call to the Stripe API?


texts:
I have a server which has a permanent state which has to be saved on stable storage. It is composed by three fields:

List<LogEntry> log
int  currentTerm
int votedFor

They have to be set during the server setup (in other words, when the server object is created). Every time that I update their "volatile" value, the relative file must be updated. Until the first time that any of these fields is updated, the value of the relative file must not be changed (in this way if the server goes down before the first udpate, then the state files remain untouched). As last thing, usually the only operation made on the log field is the append operation, but it is possible to replace elements too.

I'd like to have your opinion about the server setup operation (in other words, the constructor). Below you will find my code and solution, but I don't like the fact that when you create a ObjectOutPutStream the original file is overwritten with a new one, but I didn't think anything better than this.

public ServerRMI(...)
{
    ...
    ObjectInputStream reader;
    log = new ArrayList<>();
    try {
        //if Log file exists then should exists Metadata too
        if(Files.exists(Paths.get("Server" + id + "Log"), LinkOption.NOFOLLOW_LINKS))
        {
            reader = new ObjectInputStream(new FileInputStream("Server"+id+"Log"));
            try
            {
                //until there are LogEntry objects in the file, read them and add them to log
                while(true)
                    log.add((LogEntry) reader.readObject());
            }
            catch (EOFException e){}
            catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            reader = new ObjectInputStream(new FileInputStream("Server"+id+"Metadata"));
            currentTerm = reader.readInt();
            votedFor = reader.readInt();
        }
        else//if it is the first time that the server is set up initialize all persistent fields
        {
            currentTerm = 1;
            votedFor = -1;
            log = new ArrayList<LogEntry>();
        }
        logWriter = new ObjectOutputStream(new FileOutputStream("Server"+id+"Log"));
        metadataWriter = new ObjectOutputStream(new FileOutputStream("Server" + id + "Metadata"));
        //since creating a new ObjectOutputStream overwrite the old file with the an empty one, as first thing we rewrite the old content
        for(LogEntry entry : log)
            logWriter.writeObject(entry);
        metadataWriter.writeInt(currentTerm);
        metadataWriter.writeInt(votedFor);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}