texts: Finding prime numbers in user specified array

texts:
I have a program that searches for prime numbers in an array specified by the user.  The program starts by asking how big the user wants the array to be, then asks how many threads to split the computations.

I tested 1000 numbers, 10,0000, 100,000 and 1 million, and they all yielded results in a fairly reasonably time.  1 million numbers took about 2 minutes.  When I tried 10 million numbers, well.. the program is still running well over 2 hours with no results.

I'm wondering if the speed is normal, or if there's something fundamentally wrong with my find prime algorithm that is making it take so long to yield the desired results.

Prime.Java

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;

public class Prime extends Thread implements Runnable {
    //public List<Integer> primeList = new ArrayList<>();

    static ArrayBlockingQueue<Integer> primeList;
    int start, end;

    //int max = num;
    public int count = 0;

    public Prime(int start, int end) {
        this.start = start;
        this.end = end;
    }

    Scanner scan = new Scanner(System.in);

   public void run() {
       for (int n = start; n <= end; n++) {
           boolean prime = true;
                  for (int j = 2; j < n; j++) {
                          if (n%j == 0){
                              prime = false;
                              break;
                                }
                  }

                  if(prime && n !=1 && n!=0){   // Added conditions so it does not count 1 or 0 as prime.
                        count++;
                        primeList.add(n);

                }

          }
   }
}

Worker.Java

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;

public class Worker {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("How big would you like the array? ");
        int num = scan.nextInt();

        int [] primes = new int [num];

        System.out.println("How Many threads? ");
        int nThreads = scan.nextInt();  // Create variable 'n'  to handle whatever integer the user specifies.  nextInt() is used for the scanner to expect and Int.

        final Prime[] pThreads = new Prime[nThreads];

        long startTime = System.currentTimeMillis();
        Prime.primeList = new ArrayBlockingQueue<>(primes.length); // Guaranteed to be enough
        int step = primes.length / nThreads + 1;
        for(int i = 0; i<nThreads; i++){
            pThreads[i] = new Prime(i * step, Math.min(primes.length, (i + 1) * step - 1));
            pThreads[i].start();
        }

        try {
            for (int i = 0; i < nThreads; i++)
                pThreads[i].join();
        } catch (InterruptedException e) {
            }

            long stopTime = System.currentTimeMillis();

            long elapsedTime = stopTime - startTime;
            System.out.println("Execution time = : "+  elapsedTime);

            System.out.println("----------------------------------------------------");

            int cores = Runtime.getRuntime().availableProcessors();
            System.out.println("How many Cores this Java Program used: " + cores);

            System.out.println("Array length " + primes.length);

          for ( int i = 0; i < nThreads; i++)
             System.out.println("Thread " + i + "  Prime count: " + pThreads[i].count); // Display Thread count
             System.out.println("Total prime count: " + Prime.primeList.size()); // Output total amount of primes from the Array List
            // System.out.println(Prime.primeList);

    }
}


texts: Implementing a TTY loading / waiting animation

texts:
I implemented a class to animate waiting for processes:

from sys import stdout, stderr
from threading import Thread

def reset_string(string):
    """Returns the reset string required to delete the provided string."""

    strlen = len(string)
    return ''.join(('\b' * strlen, ' ' * strlen, '\b' * strlen))

class TTYAnimation:
    """Text animation for interactive TTY."""

    def __init__(self, message='', animation='–\\|/', end='',
                 template='{}: {}', interval=0.1, file=stdout):
        self.message = message
        self.animation = animation
        self.template = template
        self.interval = interval
        self.file = file
        self.result = end
        self._thread = None
        self._run = False

    def __enter__(self):
        """Starts animation iff in interactive Shell."""
        self.start()
        return self

    def __exit__(self, *_):
        """Stops the animation."""
        self.stop()

    def print_and_reset(self, string):
        """Prints an animation string and resets
        it after the specified interval.
        """
        print(string, flush=True, end='', file=self.file)
        sleep(self.interval)
        print(reset_string(string), flush=True, end='', file=self.file)

    def finalize(self, result):
        """Prints the terminal animation string."""
        if result is True:
            animation = str(LogLevel.SUCCESS)
        elif result is False:
            animation = str(LogLevel.ERROR)
        else:
            animation = result

        text = self.template.format(self.message, animation)
        print(text, file=self.file, flush=True)

    def run(self):
        """Runs the animation.
        Do not call this method directly,
        use start() instead.
        """
        while self._run:
            for item in self.animation:
                if not self._run:
                    break

                self.print_and_reset(self.template.format(self.message, item))

    def start(self):
        """Starts the animation."""
        if self._thread is None:
            self._run = True
            self._thread = Thread(target=self.run)
            self._thread.start()
            return True

        return False

    def stop(self, result=None):
        """Stops the animation."""
        if self._thread is None:
            return False

        self._run = False
        self._thread.join()
        self._thread = None
        self.finalize(self.result if result is None else result)
        return True

The full module can be found here.

I'd like to reduce the class' complexity while maintaining the current behaviour and get rid of threading, if possible.

Invocation example

from time import sleep

with TTYAnimation('Hang in there') as anim:
    sleep(5)


texts:
I am a CS student and I was wondering is this code looks clean. I tested it and it passed every tested but I think the delete(Node node) is a bit long, I did not find a way to reduce it

Node class

public class Node {
      private int data;
      private Node next;
      Node(int data){
        this.data = data;
      }

      public int getValue(){
        return this.data;
      }

      public void setNext(Node next){
        this.next = next;
      }

      public Node nextNode(){
        return this.next;
      }
    }

LinkedList class

public class LinkedList {
  Node head;
  Node tail;
  int size = 0;

  public void add(Node node){
    if(tail == null && head == null){
      tail = node;
      head = node;

    } else{
      tail.setNext(node);
      tail = tail.nextNode();
    }
    size ++;
  }

  public int getSize(){
    return this.size;
  }
  public int getTail(){
    if(tail == null){
      return -1;
    } else {
      return tail.getValue();
    }
  }

  public void delete(Node node){
    if(isPresent(node)){
      if(size == 1){
        this.tail = null;
        this.head = null;
        size = 0;
      }
      else if(node == head){
        head = head.nextNode();
        size --;
      }

      else if(node == tail){
        Node iterator = head;
        while(iterator.nextNode().nextNode() != tail){
          iterator = iterator.nextNode();
        }
        tail = iterator.nextNode();
        iterator.nextNode().setNext(null);
        size --;
      }

      else{
        Node iterator = head;
        while(iterator.nextNode() != node){
          iterator = iterator.nextNode();
        }
        iterator.setNext(iterator.nextNode().nextNode());
        size --;
      }
    }
  }

  public int getHead(){
    if(head == null){
      return -1;
    } else {
      return head.getValue();
    }
  }

  public void printList(){
    Node iterator = head;

    while(iterator != null){
      System.out.println(iterator.getValue());
      iterator = iterator.nextNode();
    }
  }

  public boolean isPresent(Node node){
    if(head == null){
      return false;
    }

    else if(head.getValue() == node.getValue()){
      return true;
    }

    else {
      Node iterator = head;
      while(iterator != null){
        if(iterator.getValue() == node.getValue()){
          return true;
        }
        iterator = iterator.nextNode();
      }
      return false;
    }
  }
}


texts: Adding two numbers as strings from a textfile

texts:
I just implemented code to add two ints together as strings and I'm sure my method is inferior. I've looked up other methods too but I'd appreciate criticisms specific to my code. I really want to make sure I don't develop bad habits in C++ and I think leveraging the knowledge of brighter individuals than myself on this site will help with that :).
Am I relying too much on iterators btw?

Anyhow, the code is below and be as harsh as you want. Thanks!

//This program intends to read very large integers from a text file
//the format is two integers per line. It will then add them together and output
//the sums one each line

//first, succesfully read from the text file and store into two vectors
//each digit being an element
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;

int main()
{

    string line,s1,s2;
    vector<string> vec1, vec2; //string 1 and string 2 store each of the 2 numbers per line as individual digits
    vector<string> final;      //create vector of strings that holds the sum of each pair of strings per line
    ifstream myfile("bignum.txt"); //this opens the file bignum.txt
    if (myfile.is_open())
    {
       int  count=0; //count lines
       while (!myfile.eof())
       {
           getline(myfile,line);
           bool flag=true; //bool to see if integer 2 should be stored now
           for (int i=0; i<line.length(); i++)
           {
               if (line[i]==' ')
                   flag=false;
               else
               {
                   if (flag)
                       s1+=line[i];
                   else
                       s2+=line[i];
               }

                //by the end of this loop we have two strings representing each of the numbers
           }

           //will now append 0's to the front of the smaller string in order to make the strings the same length
          if (s1.length()<s2.length())
              s1=string(s2.length()-s1.length(),'0')+s1;
          else
              s2=string(s1.length()-s2.length(),'0')+s2;

           //create a variable that acts as the surplus/carry for each single-digit addition
           int carry=0;

           //create iterators allowing for iteration over a vector
           string::reverse_iterator it1 = s1.rbegin(),it2=s2.rbegin();
           string sum_string="";

           for (; it1!=s1.rend(); it1++, it2++)
           {
               //convert chars to ints
               int k1=*it1-'0';
               int k2=*it2-'0';

               //intermediate sum
               int sum_inter=k1+k2+carry;
               carry=0;

               sum_string.insert(0,to_string(sum_inter%10));
               carry+=int((sum_inter-sum_inter%10)/10);

           };

           //insert the last carry into the highest digit position
           sum_string.insert(0,to_string(carry));

           //go through sum_string and omit leading 0's
           bool lead_zero=true;
           string::iterator leadit=sum_string.begin();
           while(lead_zero)
           {
               if (int(*leadit-'0')==0)
                  sum_string.erase(0,1);
               else
                 lead_zero=false;
           }

           final.push_back(sum_string);

           //clear strings 1 and 2 for reuse

           s1.clear();
           s2.clear();
       }

        vector<string>::iterator i1=final.begin();
        int count3=0;
        for (; i1!=final.end(); i1++)
        {
            count3++;
            cout<<"The sum of the numbers on line "<<count3<<" is "<<*i1<<"\n";
        }

    }
    else cout <<"file could not be opened";
    return 0;
}


texts:
This code is for a problem in which I'm to find the total number of numbers that exist between A and B, of which sum of digits and sum of square of digits are prime.

How can I make this optimal?

import java.util.Scanner;
public class LuckyNumbers {
    static int T,ans[];
    static long A,B;
    public static void main(String ar[]){
        Scanner scan=new Scanner(System.in);
        T=scan.nextInt();
        ans=new int[T];
        for(int i=0;i<T;i++){
            A=scan.nextLong();
            B=scan.nextLong();
            for(long j=A;j<=B;j++){
                if(getLucky(j)){
                    ans[i]++;
                }
            }
        }
        for(int i=0;i<T;i++){
            System.out.println(ans[i]);
        }
    }
    public static boolean getLucky(long j){
        boolean lucky=false;
        long rem,sum=0,sum1=0;
        while(j>0){
            rem=j%10;
            sum=sum+rem;
            sum1=sum1+(rem*rem);
            j=j/10;
        }
        if(isPrime(sum)&&isPrime(sum1)){
            lucky=true;
        }
        return lucky;
    }
    public static boolean isPrime(long sum){
        boolean status=true;
        if(sum!=1){
            for (int i=2; i < sum ;i++ ){
              long n =sum % i;
              if (n==0){
                    status=false;
                    break;
              }
            }
        }else{
            status=false;
        }
        return status;
    }
}


texts:
Introduction

I have created an algorithm that generates n! Sudoku Grids in poly-time.I verified the correctness of my grids with a SAT solver up to 50x50. I'm awaiting a review for improvements. It seems that it's in \$O(n^3)\$ time. I am saying valid complete Puzzles can be generated in poly-time, not solving arbitrary puzzles in poly-time.

Working Code

Here's a link to my code. It's working and input should be like a list [1,2,3,4,5,6,7,8,9]. Brackets needed for input.

Input should be like a list. [1,2,3....] and no repeating elements.

There is input because 9 x 9 is not the only valid Sudoku it can generate. It can generate 50 x 50, 12 x 12, 10 x 10

tup = input()[1:-1].split(',')

x = input('Enter mapping to generate valid Sudoku eg. 3 for 9 x 9')
e = input('Enter 9 for 9 x 9 ...12 for 12 x 12')
f = input('Enter 3 if its a 9 x 9 and corresponding for n^2 x n^2')

x = int(x)
e = int(e)
f = int(f)

squares = []

for index in range(len(tup)):
  tup.append(tup.pop(0))
  squares.append(tup.copy())

#Everything below here is just printing

for s in range(x):
  for d in range(0,e,f):
    for si in range(s,e,f):
      for li in range(d,d+f):
        print(squares[si][li], end = '')
    print('')

Conclusion

Side note: If you want to create 12 x 12 or any larger Sudoku's, you'll need to edit the input so that the values are readable (e.g. ['[01]','[02]',....]).

Larger Valid Grid

I was wondering if you can point out my mistakes in the code?


texts: Metaclass to run a __first__ method for the first instantiation of a class

texts:
I had an idea for a __first__ special method for a class. It would be run after __new__ and before __init__ the first time a specific object is instantiated but is not then run if you instantiate the object again. For example, if you run:

class Foo:
    def __first__():
        print('Inside __first__')
    def __init__(self):
        print('Inside __init__')
a = Foo()
b = Foo()

It would return:

Inside __first__
Inside __init__
Inside __init__

In order to try and create this particular syntax I decided to create a meta class so that you could simply add this syntax to a class of your choice. This was my final code for the meta class and it was the first time I have tried meta class syntax so I was interested in what you thought about my code:

class First(type):
    _first = True
    def __call__(cls, *args, **kwargs):
        if cls._first:
            cls._first = False
            cls._oldinit = cls.__init__
            def init(*args, **kwargs):
                cls.__first__()
                cls._oldinit(*args, **kwargs)
            cls.__init__ = init
            cls.__init__.__doc__ = cls._oldinit.__doc__
        else:
            cls.__init__ = cls._oldinit
        return super(First, cls).__call__(*args, **kwargs)


texts: Printing odd and even numbers with two threads

texts:
I would like to refactor this code printing odd and even numbers with two threads considering agile practice:

public class EvenOddNumberPrinter {

    private static class NumberPrinter {

        // To check if even number is printed or not.
        private boolean isEvenPrinted = true;

        public void printOdd(int number) throws InterruptedException {
            // Get a lock on NumberPrinter
            synchronized (this) {
                // Wait until even is not printed.
                if (!isEvenPrinted)
                    wait();

                System.out.println(number);
                isEvenPrinted = false;

                // Notify the other waiting thread which is waiting on
                // NumberPrinter
                // Other thread will get out of waiting state
                notify();
            }
        }

        public void printEven(int number) throws InterruptedException {
            synchronized (this) {
                if (isEvenPrinted)
                    wait();

                System.out.println(number);
                isEvenPrinted = true;
                notify();
            }
        }
    }

    private static class OddNumberGenerator implements Runnable {

        private NumberPrinter q;
        private int max;

        public OddNumberGenerator(NumberPrinter q, int max) {
            this.q = q;
            this.max = max;
        }

        @Override
        public void run() {
            for (int i = 1; i < max; i = i + 2) {
                try {
                    q.printOdd(i);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    private static class EvenNumberGenerator implements Runnable {

        private NumberPrinter printer;
        private int max;

        public EvenNumberGenerator(NumberPrinter printer, int max) {
            this.printer = printer;
            this.max = max;
        }

        @Override
        public void run() {
            for (int i = 2; i <= max; i = i + 2) {
                try {
                    printer.printEven(i);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        int maxNumber = 10;
        NumberPrinter printer = new NumberPrinter();
        new Thread(new EvenNumberGenerator(printer, maxNumber)).start();
        new Thread(new OddNumberGenerator(printer, maxNumber)).start();
    }

}


texts: Automation script for creating NuGet packages

texts:
I've been creating some NuGet packages recenly and to automate the process I created the following script that:

reads the package id from the script name
reads the package version from the nuspec file
can rebuild the solution, create a package and upload it by specifying the jklparameters where:

j - 0/1 - disables/enables project rebuild
k - 0/1 - disables/enables package creation
l - 0/1 - disables/enables package upload to the server

Usage:

./MyPackage.ps1 110

This would create a package called MyPackage with rebuilding the solution but not uploading it to the server yet

param([String]$cmd)

$build = $cmd.Substring(0,1) -eq "1"
$pack = $cmd.Substring(1,1) -eq "1"
$push = $cmd.Substring(2,1) -eq "1"

$packageId=[System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition)

[xml]$nuspec = Get-Content $PSScriptRoot\$packageId.nuspec
$version = $nuspec.SelectSingleNode("//package/metadata/version").InnerText

if ($build)
{
    msbuild `
        /t:Rebuild `
        /nologo `
        /p:Configuration=Release `
        /p:TargetFrameworkVersion=v4.5.2 `
        /p:Platform="Any CPU" `
        /p:OutDir="$PSScriptRoot\lib\net452" `
        `"$PSScriptRoot\..\Foo.sln`"
}

if ($pack)
{
    nuget pack `
        $PSScriptRoot\$packageId.nuspec `
        -properties configuration=release `
        -outputdirectory C:\NuGet\packages\
}

if ($push)
{
    nuget push `
        C:\NuGet\packages\$packageId.$version.nupkg `
        -configfile $PSScriptRoot\NuGet.config
}


texts: Keeping only maximum date rows in a group


texts:
I submitted the following Python 3 code for this HackerRank challenge. Given an n × n grid with an m and a p in random cells of the grid, it prints the next step in a path that moves the m to the p. I'd like any feedback on this.

def nextMove(n,r,c,grid):
    #First, find the princess
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if grid[i][j] == "p":
                a = i
                b = j
    # i = row, j = column
    nm = ("UP" if (r-a) > 0 else "DOWN")
    if r-a == 0:
        nm = ("LEFT" if (c-b) > 0 else "RIGHT")
    return nm

n = int(input())
r,c = [int(i) for i in input().strip().split()]
grid = []
for i in range(0, n):
    grid.append(input())

print(nextMove(n,r,c,grid))


texts:
I'm new to JS and am trying to write a perfectly clean source code. I'm using gulp to concatenate and minify my files, as well as removing comments. So the end result will always be the same in production environment: a single line without spaces. But for a dev environment, I'm trying to achieve clean code.

I'm building a small style guide template engine, based on Jekyll. But I need JS for several features, like dynamic styling of components. I might be overzealous but here is one of my modules with its source indentation and formatting:

$(function() {

    /* Dynamic Styling ------------------ */

    // Links
    $('.field-style a')
        .each(function() {
            var base =
                $(this)
                .next('pre')
                .children('code')
                .text();
            var replaced =
                base
                .replace(
                    /    |{|}|^a |\r?\n|\r/g,
                    '');
            $(this)
                .attr('style', replaced);
        });

    // Color box
    $('.field-style .colored')
        .each(function() {
            var base =
                $(this)
                .next('pre')
                .children('code')
                .text();
            var replaced =
                base
                .replace(
                    /\D+/g,
                    '');
            $(this)
                .css('background', '#' + replaced);
        });

    // LESS code blocks
    if ($('.field-style .less')
        .length) {
        $('.field-style .less')
            .html($('.field-style .less')
                .html()
                .replace(
                    /(none)|(decimal)|(inside)|(hidden)/g,
                    '$&'));

        $('.field-style .less')
            .html($('.field-style .less')
                .html()
                .replace(
                    /(em)|(px)/g,
                    '$&'));
    };

    /* Code blocks trigger ------------------ */

    // Button markup
    var button =
        '<button type="button" href="javascript:;"' +
        'class="btn btn-primary show-code">' +
        'Voir CSS</button>';

    // Button generator
    $('pre')
        .before(button);

    // Animation
    $('.show-code')
        .on('click', function() {
            $(this)
                .next('pre')
                .slideToggle();
            return false;
        });

});

As you can see, I indented every method as well as every var. I also break lines in replace method for each argument

What would you say about this indentation level?


texts:
This is a follow-up of the old BMI Calculator that I previously wrote. I read a majority of the feedback that you guys gave and I would like to thank you all for the kind comments. Here is the link. BMI Revised version. Please do another favor which is to screen through the codes below again.

These are the codes that I wrote and try to improve.

def to_start():
    while True:
        try:
            _start = input("Press Y to begin")
        except ValueError:
            continue
        else:
            if _start in ("Y", "y"):
                print("Let's begin")
                return _BMI()
            else:
                print("Invalid input")
                continue

def _BMI():
    while True:
        try:
            weight = float(input("Please enter your weight(kg): "))
            weight_confirm = input("Y to confirm. N to re-enter: ")
        except ValueError:
            continue
        else:
            if weight_confirm in ("Y","y"):
                break
            else:
                continue
    while True:
        try:
            height = float(input("Please enter your height(m): "))
            height_confirm = input("Y to confirm. N to re-enter: ")
        except ValueError:
            continue
        else:
            if height_confirm in ("Y","y"):
                index = (float(weight/(height*height)))
                if 18.5 <= index <= 22.9:
                    print("Low Risk")
                elif 23 <= index <= 27.4:
                    print("Moderate Risk")
                else:
                    print("High Risk")
                break
            else:
                continue

to_start()


texts: Finding all the prime factors of a number

texts:
I want to calculate all the prime factors of a number in the range 2 ≤ N ≤ 107. Here is my function:

public static long cal_me(int a, long[] A){

     long ans=1;
     int count=0;
     while(a%2==0){
         a/=2;
       count++;
     }
     if(count!=0)  // I am calculating value which depend on Number of prime Number
     ans = (long) ((Math.pow(2,2*count+1)+1)/3);

     if(A[a]!=-1) return ans*A[a];

     for(int i=3;i<=Math.sqrt(a) && a!=1;i+=2)
     {
         if(A[a]!=-1){

             return ans*A[a];
         }
         count=0;
           while(a%i==0){
               a/=i;
               count++;

           }

           if(count!=0)
               ans *=(long) ((Math.pow(i,2*count+1)+1)/(i+1));

     }

     if(a>2)
        ans *=  (long) ((Math.pow(a,3)+1)/(a+1));

     return ans;
}

My calling function:

for(int i=2;i<=10000000;i++)
A[i] = cal_me(i,A);

The above program me took 10s. I want something faster — how should I improve this?


texts: Loading a database table using a promise chain

texts:
I am creating a util module that I'm using to communicate with a MS-SQL database. I want each public method to return a promise. I started with a private function that executes a DB query and returns a promise. The function establishes a connection to the DB then it executes the query. My current code just lets all errors fall through to a single catch, and I'm not sure if this is a best practice or not.

I was hoping someone could answer that for me and any other suggestions about code read ability or anything.

var config = require('./mainConfig')();
var sql = require('mssql');
var connection =  new sql.Connection(config.db.sql);
var Promise = require("bluebird");

exports.getAll = function(table){

    return executeQueryStatment("select * from " + table);

};

function executeQueryStatment(query, newconnection) {

    var conn =  newconnection || connection;
    var request = new sql.Request(conn);

    return new Promise(function(res, rej){

     conn.connect().then(function(){

       return request.query(query);

     }).then(function (data) {

         res(data);
         conn.close();
     })
     .catch(function(err) {
        // plan on handling all errors here
        // is it better to handle each error individually upstream?
        console.log(err);
        conn.close();

    })

  });

};


texts: Displaying all application errors in a view

texts:
I'm learning ASP.NET Core with MVC pattern and I didn't find anything useful related to this argument.

Actually I'm looking for a way to handle all the application errors inside a single View. The first thing that I did was create the View for display the error, this is the design (pretty simple though):

<h2>@(ViewBag.ErrorMessage == null ? "An error happened" : "" + @ViewBag.ErrorMessage + "")</h2>

and this is the Error controller:

public class ErrorController : Controller
{
    [HttpGet]
    public IActionResult Index(string errorMessage)
    {
        ViewBag.ErrorMessage = errorMessage;
        return View();
    }
}

Essentially, I used the ViewBag for valorize a property called ErrorMessage which contains the parameter errorMessage.

Let me show an example of this logic for the email confirmation:

public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
    if (userId == null || token == null)
    {
        return RedirectToAction("Index", "Error");
    }

    var user = await _userManager.FindByIdAsync(userId);

    if (user != null)
    {
       if (user.EmailConfirmed)
       {
            return RedirectToAction("Index", "Error", new { errorMessage = "Email already confirmed" });
       }

       IdentityResult result;

       try
       {
           result = await _userManager.ConfirmEmailAsync(user, token);
       }
       catch (InvalidOperationException ex)
       {
           return RedirectToAction("Index", "Error", new { errorMessage = ex.Message });
       }

       if (result.Succeeded)
       {
           //TODO: Send another email
           return View("ConfirmEmail", user);
       }
    }

    return RedirectToAction("Index", "Error", new { errorMessage = "Utser not found" });
    }

Now, I'm not an expert yet of ASP.NET Core so I don't know if my practice is good enough for a production environment, someone could maybe propose a better way or improve my solution?


texts: Is my Python tkinter application properly structured?

texts:
I started a simple OOP GUI project with tkinter in Python since I've been studying the basics for a while, but I'm not sure if my code is properly structured and following the programming conventions. I haven't finished it yet but the sooner I learn the good practices the better. My goal is to make a mini game. For now it only has a main window and a character selection window with some widgets in it. (For didactic purposes, I want it to be done with an OOP approach).

import tkinter as tk
from itertools import product

# Creating main page
class MainApplication(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.master = master

        # produce the set of coordinates of the buttons
        main_positions = product(range(2), range(5))

        # Creating main page widgets
        frame = tk.Frame(root, bg="#34495e")
        frame.grid()

        lb = tk.Label(frame, width=111, height=4, bg="#2c3e50", text="Champions", fg="white", font=50,
                      justify=tk.CENTER)
        lb.grid(row=0, column=0, columnspan=5, pady=(0, 50), sticky="snew")

        # Creating multiple buttons
        for i, item in enumerate(main_positions):
            button_main = tk.Button(frame, width=16, height=8, bg="#2c3e50", relief=tk.RIDGE, fg="white",
                                    justify=tk.CENTER, text=f"Champion {item[1] + 1}",
                                    command=ChampionWindow.champions_window)

            button_main.grid(row=item[0] + 1, column=item[1], pady=(0, 50))

        button = tk.Button(frame, width=30, height=3, bg="#2c3e50", relief=tk.RIDGE, text="Done", fg="white", font=20,
                           command=root.destroy)

        button.grid(row=3, columnspan=5, pady=(0, 150))

# Creating champion select window
class ChampionWindow(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.master = master

    @staticmethod
    def champions_window():
        ch_window = tk.Tk()
        ch_window.title("Champion Select")
        ch_window.resizable(False, False)
        ch_window.configure(background="#192a56")

        champion_position = product(range(30), range(5))

        def scroll(ch_event):
            ch_canvas.configure(scrollregion=ch_canvas.bbox("all"))

        def select_champion():
            pass

        ch_canvas = tk.Canvas(ch_window, bg="blue", width=470, height=500)
        ch_frame = tk.Frame(ch_canvas, bg="#273c75")

        vscrollbar = tk.Scrollbar(ch_window, orient="vertical", command=ch_canvas.yview)

        ch_canvas.configure(yscrollcommand=vscrollbar.set)
        ch_canvas.grid(sticky="snew")

        vscrollbar.grid(row=0, column=3, sticky="sn")

        ch_canvas.create_window((0, 0), window=ch_frame, anchor="nw")
        ch_frame.bind("<Configure>", scroll)

        # Creating multiple buttons
        for x, itm in enumerate(champion_position):
            btn = tk.Button(ch_frame, width=12, height=6, bg="#2c3e50", relief=tk.RIDGE, fg="white", justify=tk.CENTER,
                            command=select_champion)

            btn["text"] = f"Pick champ {x+1}"
            btn.grid(row=itm[0], column=itm[1])

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root)
    root.configure(background="#273c75")
    root.geometry("1000x570+450+200")
    root.resizable(False, False)
    root.title("Champion")
    root.mainloop()

Images:

   - The buttons open the character selection window

- In the future the buttons will pick the selected character that will be represented by an image with PIL library.


texts: How to reduce code from different alert-dialogue?

texts:
I have three types alert dialogue. Each alert dialogue behave differently but I don't like to write three types of alert dialogue in same class because it extends the class size drastically. Here are the three alert dialogue given below:

public boolean onJsAlert(WebView view, String url, String message,
        final android.webkit.JsResult result) {
    new AlertDialog.Builder(currentActivity)
            .setTitle("Alert !")
            .setMessage(message)
            .setPositiveButton(android.R.string.ok,
                    new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            result.confirm();
                        }
                    }).setCancelable(false).create().show();

    return true;
}

@Override
public boolean onJsConfirm(WebView view, String url, String message,
        final android.webkit.JsResult result) {
    new AlertDialog.Builder(currentActivity)
            .setTitle("Confirmation")
            .setMessage(message)
            .setPositiveButton(android.R.string.yes,
                    new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            result.confirm();
                        }
                    })
            .setNegativeButton(android.R.string.no,
                    new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            result.cancel();
                        }
                    }).setCancelable(false).create().show();

    return true;
}

And the last alert dialogue is:

public void onGeolocationPermissionsShowPrompt(final String origin,
        final GeolocationPermissions.Callback callback) {

    final boolean remember = true;

    AlertDialog.Builder builder = new AlertDialog.Builder(
            WebviewActivity.this);
    builder.setTitle("Locations");
    builder.setMessage(" Would like to use your Current Location")
            .setCancelable(true)
            .setPositiveButton("Allow",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int id) {
                            callback.invoke(origin, true, remember);

                            SharedPreferences pref = currentActivity
                                    .getPreferences(currentActivity.MODE_PRIVATE);
                            SharedPreferences.Editor editor = pref
                                    .edit();
                            editor.putBoolean("isLocationAvailable",
                                    true);
                            editor.commit();

                            webview.loadUrl(getUrl(gps.getLatitude(),
                                    gps.getLongitude(), "true"));
                        }
                    })
            .setNegativeButton("Don't Allow",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int id) {
                            callback.invoke(origin, false, remember);
                            webview.loadUrl(getUrl("", "", "false"));

                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}

How can I reduce the code size. Any suggestion please?


texts:
I am just starting to implement unit testing into my project and familiarizing myself with NUnit.  I have added unit tests for encryption/decryption methods that I have implemented, and am looking for more things to start testing for in my existing code before moving forward.

The most basic classes that I have are my IValueConverters, so I thought it would be a good place to start.

Here is my first test:

[TestFixture]
public class ConverterUnitTest
{
    [TestCase]
    public void BooleanToVisibilityConverterTest()
    {
        var btvConverter = new BooleanToVisibilityConverter();

        Assert.That(btvConverter.Convert(true, typeof(Visibility), null, "en-us").Equals(Visibility.Visible));
        Assert.That(btvConverter.Convert(false, typeof(Visibility), null, "en-us").Equals(Visibility.Collapsed));
    }
}

As you can see, this test is just ensuring that true returns Visibility.Visible and false returns Visibility.Collapsed.  What I am wondering is, does it make sense to have multiple Asserts in one test, or should I split them up into multiple tests even though they are both testing the same converter? Also, is it a good practice to test converters?


texts: Three-way join in Entity Framework Core to retrieve all roles that a user has

texts:
I'm very new to Entity Framework Core, so I'm concerned about whether I've done this query in the most efficient way possible.

The database I'm querying looks like this:

Basically, UserRoles is a a "linking table" between the User and the Roles in order to create a one-to-many relationship. If a user exists at all, they will always have at least one role, but they could have several roles.

I want to get the role name based on the NT ID of the user.

This is something I plan to do fairly often, so I separated it out into a separate utility (rather than having it in the controller).

In SQL, I'd just do two inner joins. However, what I did here is to query UserRoles (rather than using Join).

public class UserUtilities
{
    public static List<Roles> GetRoles(string ntid)
    {
        var ctx = new MyLiveDocsContext();
        List<Roles> roles =
            (from ur in ctx.UserRoles
             where ur.User.Ntid == ntid
             select ur.Role).ToList();

        return roles;
    }
}

Ive tested this and it does what I want, but I'm wondering if this is the best way to do this. For example, would it be better to use an explicit join instead?


texts:
I've been working on a large Ruby on Rails application for several years. We inherited it and refactored and upgraded it, but there are some sections that have not been touched in at least 5 years (parts created by the original developer(s)). One such section is payment processing code. The code works for the most part, so we leave it untouched. The only problem is that whenever a charge is denied by the payment processor, the user gets a 500 error instead of a helpful message.

I've removed all the error-handling code from the following snippets.

The maze begins in a controller:

  def submit_credit_card
    ...
    @credit_card = CreditCard.new(params[:credit_card].merge(:user => @user))
    @credit_card.save
    ...
    @submission.do_initial_charge(@user)
    ...
  end

Then in the Submission model:

  def do_initial_charge(user)
    ...
    self.initial_charge = self.charges.create(:charge_type => ChargeType.find(1), :user => user)
    self.initial_charge.process!
    self.initial_charge.settled?
  end

In the Charge model:

  aasm column: 'state' do
    ...
    event :process do
      transitions :from => [:created, :failed], :to => :settled, :guard => :transaction_successful?
    end
    ...
  end

  def initialize(*params)
    super(*params)
    ...
    self.amount = self.charge_type.amount
  end

  def transaction_successful?
    user.reload
    credit_card = CreditCard.where(user_id: user_id).last
    cct = self.cc_transactions.build(:user => user, :credit_card => credit_card, :cc_last_four => credit_card.num_last_four, :amount => amount, :charge_id => id)
    cct.process!
    if self.last_cc_transaction.success
      self.update_attribute(:processed, Time.now)
      return true
    else
      self.fail!
      return false
    end
  end

There are a lot of questionable bits above such as reloading the user and finding the last CreditCard rather than passing in the one just saved. Also this code depends on a ChargeType loaded from the database with a hard-coded ID.

In CcTransaction we continue down the trail:

  def do_process
    response = credit_card.process_transaction(self)
    self.authorization = response.authorization
    self.avs_result    = response.avs_result[:message]
    self.cvv_result    = response.cvv_result[:message]
    self.message       = response.message
    self.params        = response.params.inspect
    self.fraud_review  = response.fraud_review?
    self.success       = response.success?
    self.test          = response.test
    self.response      = response.inspect
    self.save!
    self.success
  end

All this appears to do is save a record in the cc_transactions database table. The actual payment processing is performed in the CreditCard model. I won't bore you with the details of that class. The actual work is performed by ActiveMerchant::Billing::AuthorizeNetCimGateway.

So we have at least 5 models involved (Submission, Charge, ChargeType, CcTransaction, and CreditCard). If I were to do this from scratch, I would only use a single Payment model. There are only 2 charge types, so I would hard code those values as class variables. We don't store credit card details, so that model is unnecessary. Transaction info can be stored in the payments table. Failed payments do not need to be saved.

I could go in and do this refactoring fairly easily except for the requirement that nothing should ever go wrong on the production server. Each of the redundant classes has many methods that could be called from anywhere in the code base. There is a suite of integration tests but the coverage is not 100%.

How should I go about refactoring this while ensuring nothing breaks? If I went through the 5 payment classes and greped every method to find out where they're called there's a high probability I will miss something. The client is already used to how the current code runs and introducing any new bugs is unacceptable. Apart from increasing test coverage to 100%, is there any way to refactor this with certainty that nothing will break?


texts: Print the length of words as a vertical histogram

texts:
I thought I'd give it a shot. What I came up with is from a culmination of my last two submissions, incorporating most of the feedback from this community, including better naming of variables, initialization, and making my program a bit more user-friendly. I'm not sure which optimizations I can make or if there are any issues with my code.

Any feedback is welcome!

#include <stdio.h>

/* print the length of words as input to a histogram with vertical bars */
int main(void) {
  int c, i, j;
  int word_length = 0;
  int max_word_frequency = 0;
  int histogram[10] = {0};

  putchar('>');
  while ((c = getchar()) != EOF && word_length < 10) {
    if (c != ' ' && c != '\n' && c != '\t') {
      ++word_length;
    }
    else {
      ++histogram[word_length];
      word_length = 0;
    }
  }
  for (i = 0; i < 10; ++i) {
    printf("%d ", i);
    if (histogram[i] > max_word_frequency)
      max_word_frequency = histogram[i];
  }
  putchar('\n');
  for (i = 0; i < max_word_frequency; ++i) {
    for (j = 0; j < 9; ++j) {
      if (histogram[j] > 0) {
         printf("x ");
         histogram[j] = histogram[j] -1;
      }
      else {
         printf("  ");
      }
    }
  putchar('\n');
  }
}


texts: Guess user number between 0 and 100 (Binary Search)

texts:
I am at the beginning of learning python and one of my homeworks (in chapter regarding loops) where to write a code that would guess user number between 1 - 100.

I believe I used algorithm called binary search.

# Introduction
print('\nThink about a number between 0 - 100 and let me guess which is it.',
      '\n\nI will ask you whether my guess is lower or higher than your number',
      '\nIndicate "l" if lower than your number',
        '"h" if higher than your number and',
        '"e" if my guess is correct.'
      '\n\nYou ready?, let"s start!\n')

# Algorithm
count = 0
lborder = 0
hborder = 100
guess = 50

while True:
    answer = input('Is your number higher, lower or equal to ' + str(guess) + ':')
    if answer == 'l':
        hborder = guess
        guess = round((lborder + guess)/2)
    elif answer == 'h':
        lborder = guess
        guess = round((hborder + guess) / 2)
    elif answer == 'e':
        break
    else:
        print('Unrecognizable answer. Use: "l", "h", "e"')
    count += 1

print('\nHooray! It took me', count, 'to guess your number.', sep=' ')
input('\nPress Enter to Exit.')

My question is basically whether there is a better algorithm for finding those numbers (quicker).
Also do you have any other comments about my code.


texts:
Here is a good article on an optional reference type in C++. They discuss std::optional<T&>, but as that doesn't compile I have made my own.

One purpose of this type is to remove raw pointers from function signatures (where references alone cannot be used), as a raw pointer does not convey any indication of what it will be used for (become owned, deleted, iterated, dereferenced, etc).

#include <functional>
#include <optional>

template<typename T>
/** @brief An optional refference **/
class opt_ref {
    using std_opt_ref = std::optional<std::reference_wrapper<T>>;
    std_opt_ref data = std::nullopt;
public:
    using type = typename std::reference_wrapper<T>::type;

    /** public member functions **/

    T& get() { return data.value().get(); }
    const T& get() const { return data.value().get(); }
    bool has_value() const { return data.has_value(); }
    T& value_or(T&& other) const { return data.value_or(other); }

    /** constructors **/

    opt_ref() {}
    opt_ref(T& source) : data(source) {}
    opt_ref& operator = (T&& other) { data.value().get() = other; return *this; }

    /** comparisons **/

    bool operator == (const T& t) { return data.value() == t; }
    bool operator == (const std::nullopt_t&) {return !data.has_value(); }

    /** implicit conversion **/

    operator T&() { return data.value().get(); }
    operator const T&() const { return data.value().get(); }
    operator std::reference_wrapper<T>() { return data.value(); }
    operator const std::reference_wrapper<T>() const { return data.value(); }
};


texts: Hash function for a key of type structure

texts:
I need to implement a hash function for a key of type structure. This structure is as follows:

typedef struct hash_key_s {
    void *k1;
    char *k2;
    char *k3;
} hash_key_t;

My proposed hash function is as follows:

unsigned long hash_func (void *key)
{
    hash_key_t  *k = (hash_key_t *) key;
    unsigned long h = 0;
    char c = 0;
    char *p = k->k2;

    if (p != NULL) {
        for (c=0; c=*p; p++) {
            h = h*31 + c;
        }
    }
    p = k->k3;
    if (p != NULL) {
        for (c=0; c=*p; p++) {
            h = h*31 + c;
        }
    }

    h = h*31 + (((unsigned long) k->k1) >> 2);
    return h*110351524UL;
}

I just want to know if it is a good hash or if I can improve it further.


texts: Combine a boolean condition with a Where clause in same query

texts:
I'm trying to see if I can somehow reduce the length of this query.
I have a common part with the string.Compare(...),

is IsProperty == true I would like to take all strings where Value is property, and false do the opposite.

What I have now is:

List<KeyValuePair<int,string>> Groups =
    isProperty ? model.Groups.Where(
      m => string.Compare(m.Value, "properties", true) == 0
    ).ToList() :
    model.Groups.Where(
      m => string.Compare(m.Value, "properties", true) != 0
    ).ToList();

What I would like:

List<KeyValuePair<int,string>> Groups =
    model.Groups.Where(
      m => string.Compare(m.Value, "properties", true) == 0 || !=0 //depending on isProperty
    ).ToList();

Not sure if it is all possible. (What I really want is to add it to the .Where when I pull values from DB)


texts:
This is an implementation of the Nothing programming language. The language spec is as follows:

  Design philosophy

  In the current software industry focus lays on solving complex
  problems by using complicated algorithms. The language "Nothing" was
  created to shift this focus from complex problems towards the
  expectations of the programmer and the user. This way even the most
  complicated programming challenges swiftly disappear as if they never
  have existed before. Basically, the main strengths of the language
  "Nothing" are:

  to create bug-free and portable software https://esolangs.org/wiki/Nothing
  to shift focus from complex technical solutions towards the expectation of the programmers and users

  Program structure

  Nothing has a very simple and straightforward structure. It is a
  typeless language which does not use any of the known programming
  constructs like loops, choices and the like. It is the only language
  which can be considered 1GL, 2GL, 3GL, 4GL and 5GL all at the same
  time.

What I would like to know:

Does my program conform to the language specs?
Does it follow the design philosophy?
Readability, performance, etc. Any improvements welcome

Source code:

/*
 * A 'Nothing' compiler
 * <http://www.turtle.dds.nl/nothing/>
 * September 2010, RoPe Development Inc.
 *
 * Author: authorname
 */

#include <iostream>
#include <fstream>
#include <cstdlib> // EXIT_FAILURE
#include <string> // std::char_traits<char>::eof

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        std::cerr << "nothing: fatal error: no input files\n";
        std::cerr << "compilation terminated.";
        return EXIT_FAILURE;
    }

    std::ifstream program(argv[1]);

    if (!program)
    {
        std::cerr << "nothing: error: " << argv[1] << ": No such file or directory\n";
        std::cerr << "nothing: fatal error: no input files\n";
        std::cerr << "compilation terminated.";
        return EXIT_FAILURE;
    }

    if (program.peek() != std::char_traits<char>::eof())
    {
        std::cerr << "nothing: fatal error: program is not empty\n";
        std::cerr << "compilation terminated.";
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

Example:

# bash
$ touch helloworld.not
$ ./nothing helloworld.not
$


texts:
I wrote this perl script that analizes a text and plot out a bar graph of the word occurrences during the text.

Since come mainly from Javascript and PHP, i would like to know how bad is this code and if there is room for improvement and how, any tip will be appreciated!

Thanks!

#!usr/bin/perl -w
use strict;
use warnings;
use GD::Graph::bars;
use GD::Graph::colour;

if (!$ARGV[0]) {
    die "Error:\nPlease supply a txt file and a database of words to exclude\n";
}

my $file = $ARGV[0];
my $dbfile = $ARGV[1];
my $cnt = 0;
my %wordlist = ();
my @db = ();
my $threshold = 18;

binmode STDOUT,"utf8";

open (HNDL,'<:utf8', $file) || die "wrong filename";

if ($dbfile){
    open (HDB,'<:utf8', $dbfile) || die "wrong filename";
    @db = <HDB>; # load file into array
    foreach my $db (@db) {
        # remove newlines
        #$db =~ s/\n\s*//;
        chomp($db);

    }
}

while (my $val = <HNDL>)
{
    my @val = split / /, $val; # split each space build words array

    foreach my $word (@val){
        # clean the word remove newlines
        #$word =~ s/\n\s*//;
        chomp($word);
        # clean the word remove everything until '
        $word =~ s/^.\'//;
        # clean the word remove any nonword characters
        # $word =~ s/[^a-zA-Z_0-9]//;
        # clean the word remove dots and commas
        $word =~ s/,|\.//;

        if (length($word) < 2){
            next;
        };

        # check if the word is to be excluded
        my $exclude = 0;
        if ($dbfile){
            foreach my $dbword (@db) {
            # check if the string contains dbword
            # ^ check for occurence at start
            # $ check for occurence at end
            # /i case insensitive
              if ($word =~ m/^$dbword$/i){
                $exclude = 1;
                #print "Escluso: $word";
              }
            }
        }

        if($exclude == 0) {
          # check word in the hash
            if (exists $wordlist{$word}) {
                #if present augment value by one
                $wordlist{$word}++;
            }else{
            #if not present add
                $wordlist{$word} = 1;
            }
        }else{
            # do nothing
        }

    }
}

# Export CSV

# Print header
print ("Word,Value\n");

# print hash elements for each sorted element
for my $key ( sort { $wordlist{$a} <=> $wordlist{$b} }  keys %wordlist){

        #print "$key ---> $wordlist{$key}\n\n";
        if ($wordlist{$key} >= $threshold){
            print "$key,$wordlist{$key}\n";
            }
    }

# Export Graph
my $graph = GD::Graph::bars->new(1024, 600);

# Build data arrays
my @xdata = ();
my @ydata = ();
my @data = ();
for my $key ( sort { $wordlist{$a} <=> $wordlist{$b} }  keys %wordlist){

        #print "$key ---> $wordlist{$key}\n\n";
        if ($wordlist{$key} >= $threshold){
            push(@xdata,$key);
            push(@ydata,$wordlist{$key});
            }
    }

push (@data,\@xdata);
push (@data,\@ydata);

$graph->set(
    x_label     => 'Words',
    x_label_position => '0.5',
    y_label     => 'Number of Hits',
    title       => 'Number of Hits for Each Word',
    bar_spacing => 5,
    bar_width => 25,
    transparent  => '0',
    bgclr  => 'white'
) or warn $graph->error;

my $image = $graph->plot(\@data) or die $graph->error;

# write file to output
$file =~ s/\.[*]$//;

open(PNGOUT,">","$file.png");

binmode PNGOUT;
print PNGOUT $image->png;

close(PNGOUT);

close (HDB);
close (HNDL);


texts: Function calls as parameters for other functions

texts:
I am in two minds about function calls as parameters for other functions. The doctrine that readability is king makes me want to write like this:

br = mechanize.Browser()
raw_html = br.open(__URL)
soup = BeautifulSoup(raw_html)

But in the back of my mind I feel childish doing so, which makes me want to write this:

br = mechanize.Browser()
soup = BeautifulSoup(br.open(__URL))

Would it actually look unprofessional to do it the first way? Is there any serious reason to choose one method over the other?


texts: Overloading istream>> to read comma-separated input

texts:
I have the following very simple class:

class accusation
{
private:
    std::string murderer;
    std::string weapon;
    std::string place;
public:
    accusation() = default;
    accusation(std::string, std::string, std::string);
    friend std::ostream& operator<<(std::ostream&, const accusation&);
    friend std::istream& operator>>(std::istream&, accusation&);
};

I have overloaded my extraction from istream operator as follows:

std::istream& operator>>(std::istream& is, accusation& readable)
{
    std::vector<std::string> accusation;
    std::string token, word;
    //divide by commas
    while (std::getline(is, token, ','))
    {
        std::string pushable;
        std::stringstream ss(token);
        while (ss >> word) pushable += word + " ";
        if (pushable.size() != 0) pushable.pop_back(); //remove that last white space
        std::transform(pushable.begin(), pushable.end(), pushable.begin(), ::tolower);
        accusation.push_back(pushable);
    }
    if (accusation.size() == 3)
    {
        is.clear();
        bool valid{ false };
        //check it matches one of the clue::characters
        for (const auto& character : clue::characters)
            if (accusation[0] == character)
            {
                valid = true;
                break;
            }
        if (valid)
        {
            valid = false;
            //check it matches one of the clue::weapons
            for (const auto& weapon : clue::weapons)
                if (accusation[1] == weapon)
                {
                    valid = true;
                    break;
                }
            if (valid)
            {
                valid = false;
                //check it matches one of the clue::places
                for (const auto& place : clue::places)
                    if (accusation[2] == place)
                    {
                        valid = true;
                        break;
                    }
                if (valid)
                {
                    readable.murderer = accusation[0];
                    readable.weapon = accusation[1];
                    readable.place = accusation[2];
                }
                else
                    is.setstate(std::ios_base::failbit);
            }
            else
                is.setstate(std::ios_base::failbit);
        }
        else
            is.setstate(std::ios_base::failbit);
    }
    else
        is.setstate(std::ios_base::failbit);
    return is;
}

I am reading input as green, dagger, kitchen and storing it in my accusation. The first element has to be in clue::characters (an array of possible game characters), second element in clue::weapons, and third element in clue::places.

Can somebody suggest a cleaner way to overload this operator? The code works as expected, but I believe that there is a lot of space for improvements. Any push into the right direction is highly appreciated.


texts:
Problem

By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.

My solution

-- Formula for finding n-th Fibonacci number
fibonacci 1 = 1
fibonacci 2 = 2
fibonacci n
    | n >= 3    = fibonacci (n - 1) + fibonacci (n - 2)
    | otherwise = fibonacci 2 + fibonacci 1

-- Intermediate code: list of first 32 Fibonacci numbers
fibonacciList = [fibonacci i | i <- [1..32]]

-- list of even Fibonacci numbers from fibonacciList
evenFibonacci = [eF | eF <- fibonacciList, eF `mod` 2 == 0]

-- list of evenFibonacci from fibonacciList not exceeding 4 million
evenFibonacci' = [eF' | eF' <- evenFibonacci, eF' <= 4000000]

-- sum of the even fibonacci numbers not exceeding 4 million
sumEvenFibonacci' = sum evenFibonacci'

-- display the result
main = print sumEvenFibonacci


texts:
I'd already asked for my code to be reviewed earlier here

First Chess project)

Full code

Considering the suggestions put forth for that question, I spent a day and refactored my whole code. For those who have seen my previous question/code, could you you point out anything which I have as of yet not improved upon?

For everyone else, all I want to know is whether I am on the right track while programming in python. Could you please tell me if there is something unpythonic in my code? What parts are not written in the way "good Python code" is meant to be written? Here is a snippet I feel is not really good:

1. Taking input from user

This is in the main loop:

input_read=False

if len(m)==4:
  X1,Y1,X2,Y2 = m                           # assigning final co-ordinates
  m=[]                                  # empty the buffer input list
  input_read=True

if not input_read:
    events=pygame.event.get()
      for event in events:

          if event.type == pygame.QUIT:         # Quitting
              exit(0)

          if event.type == pygame.MOUSEBUTTONUP: pressed= False     # get ready for next click
          if event.type ==  pygame.MOUSEBUTTONDOWN and not pressed:
              pressed=True
              if event.button==1:
                  if len(m)==2:                                     # add second click co-ordinates
                      pos = pygame.mouse.get_pos()
                      x = pos[0]/80+1
                      y = pos[1]/80+1
                      m.extend([x,y])

              else:
                    pos = pygame.mouse.get_pos()                    # add first click co-ordinates
                    x = pos[0]/80+1
                    y = pos[1]/80+1
                    j=checkPositionToPieceDict((x,y))               # Checks that the first click has a piece
                    if j:                                           # of your colour and selects it.
                        if j.colour==colour:
                            selectedPiece=j
                            m.extend([x,y])

Could you please just go through the code and tell me if this is how Python is written in the industry?


texts: How to parse arrays back and forth to function in a smart way

texts:
Inside my main function I got a lot of these.

var statsArray = [];
statsArray = pushStats(r, htmlRecp, '', statsArray);
statsArray = pushStats(e, '', htmlExpe, statsArray);
etc...

Then I got statsArray function where I insert or update new items in the array.

function pushStats(currKey, lineRecp, lineExpe, statsArray){
    var selectStats = statsArray.filter(function(obj){
        return obj.key == currKey
    })
    if (!selectStats.length) {
        statsArray.push(
            {
                'key'       : currKey,
                'receipt'   : lineRecp,
                'expense'   : lineExpe
            }
        )
    } else {
        if (lineRecp) {
            selectStats[0].receipt = lineRecp;
        } else {
            selectStats[0].expense = lineExpe;
        }
    }
    return statsArray;
}

My question is this, how can I do this smarter?

statsArray = pushStats(aa, bb, cc, statsArray);

Is this the only way to do this? To send statsArray back and forth like this?


texts: Extracting the timestamp, minimum score, and maximum score from hundreds of arrays

texts:
So this is what I'm doing:

I have hundreds of arrays, each of them filled with a date in milliseconds in the first position, and the rest of the array is filled with user game scores.

Let's just call this array above var scoresDates

The ultimate goal is to have each of those arrays contain only the date in milliseconds, the smallest score and then the largest score, in that order. To do this, I set up for loop within a for loop, that will loop the larger array and the systematically make several operations until the end result is achieved. I would like to see if there are better ways to do it or optimize this process.

This is what I have...

// Logic that stacks all the scores per unique day from all the user's game scores. All unique dates with subsequent scores are stored in the uniqueDaysScores array.

uniqueDaysScores = [];
uniqueDaysScores.push(scoresDates[0]);

for(var i = 0, ii = scoresDates.length; i < ii; i++){
  var tempArray = [];

  if(scoresDates[i][0] == uniqueDaysScores[0][0]){
    uniqueDaysScores[0].push(scoresDates[i][1]);
  } else{
    tempArray.push(scoresDates[i][0]);
    tempArray.push(scoresDates[i][1]);
    uniqueDaysScores.unshift(tempArray);
  }
}

// Storted scores from smallest to largest for each unique date for user games played.

scoreSorted = [];

// Logic to take all the scores, sort them from decreasing to increasing order, then package the date, lowest and shortest score into the finished array, scoreSorted.

for(var i = 0, ii=uniqueDaysScores.length; i < ii; i++){
  var scoreSorted1 = [];
  var scoreSortedPrimer = [];

// First level for loop that goes through the unique scores array and ignores the date, while pushing all the scores into the scoreSorted1 array.

  for(var z = 0, zz = uniqueDaysScores[i].length; z < zz; z++){
    if(uniqueDaysScores[i][z] < 1000){
      scoreSorted1.push(uniqueDaysScores[i][z]);
    }
  }

  // Next step is sorting the scoreSorted1 array from lowest score to highest score.
  scoreSorted1.sort(function(a,b){
    return a-b;
  });

  // Find maximum and minimum scores in the array and finally push them into the scoreSortedPrimer array.
  var primerMin = Math.min.apply(Math, scoreSorted1);
  scoreSortedPrimer.push(primerMin);
  var primerMax = Math.max.apply(Math,scoreSorted1);
  scoreSortedPrimer.push(primerMax);

  // Finally, find the date and push it into the scoreSortedPrimer array, so it can be pushed into the main scoreSorted array.

  for(var x = 0, xx = uniqueDaysScores[i].length; x < xx; x++){
    if(uniqueDaysScores[i][x] > 1000){
      scoreSortedPrimer.unshift(uniqueDaysScores[i][x]);
    }
  }
  uniqueDaysScores.push(scoreVarianceSortedPrimer);
}

The uniqueDaysScores array will contain all the arrays with the date first and the lowest and highest score thereafter. I have added comments to make it easier to follow. It kind of seems like a long process and I'm just curious if there is a more experienced programmer that can see where this script can be optimized or improved.


texts: Building a good C++11 template library - compile-time checked enum array

texts:
The task is to add data or values to members of a given enum class. The compiler should check if a value for each enum member is available, and not just the default constructor empty values. It is a tool to verify that no values are forgotten during a change.

The interface is modeled after the array of enumeration type in Delphi/Pascal which I find very useful.

Since I'm interested to learn about library design, I guess the interface is the important part:

template<typename Enum, typename T>
class enum_array {
public:
  typedef typename std::array<T, enum_length<Enum>::result>::const_iterator
          const_iterator;
  typedef typename std::array<T, enum_length<Enum>::result>::iterator iterator;
  typedef T value_type;

  //--------------------------------------
  template<typename ... Args>
  enum_array(Args ... list);

  //--------------------------------------
  template<typename otherEnum>
  enum_array(const enum_array<otherEnum, value_type> &other );

  //--------------------------------------
  template<typename otherEnum>
  enum_array(enum_array<otherEnum, value_type> &&other );

  //--------------------------------------
  template<typename otherEnum>
  enum_array<Enum, value_type>& operator= (const enum_array<otherEnum, value_type> &other);

  //--------------------------------------
  template<typename otherEnum>
  enum_array<Enum, value_type>& operator= (enum_array<otherEnum, value_type> &&other);

  //--------------------------------------
  constexpr size_t size() const;

  //--------------------------------------
  // read values
  const value_type& at(int index) const;

  const value_type& operator[](int index) const;

  const value_type& at(Enum type) const;

  const value_type& operator[](Enum type) const;

  value_type& at(int index);

  value_type& operator[](int index);

  value_type& at(Enum type);

  value_type& operator[](Enum type);

  //--------------------------------------
  // write values
  void set_value(int index, const value_type &value);

  void set_value(Enum type, const value_type &value);

  //--------------------------------------
  // iterator access
  iterator begin();

  iterator end();

  const_iterator begin() const;

  const_iterator end() const;

  //--------------------------------------
  // algorithms
  Enum find(const value_type &value) const;

  Enum find(const value_type &value, Enum default_value) const;
};

I provided copy and move constructors, and assignment operators, with the compile time checks mentioned above, as well as value and iterator access.

To have it working, one needs to publish the size of an enum class which is done by these two macros:

#define DEF_ENUM(name, ...)                                                    \
  enum class name : uint8_t { __VA_ARGS__ };                                   \
  SETUP_ENUM_LENGTH(name, BOOST_PP_VARIADIC_SIZE(__VA_ARGS__))

#define SETUP_ENUM_LENGTH(enum_type, length)                                   \
  template<> struct enum_length<enum_type> { enum { result = length }; };

A use case looks like this:

DEF_ENUM(Columns, name, address, city, country)

// Does not compile, and tells you that the count is not right.
enum_array<Columns, std::string> Columntitle_bad {"Name", "Address", "City"};
// Compiles.
enum_array<Columns, std::string> Columntitle {"Name", "Address", "City", "Country"};


texts: A regex pattern that matches all forms of integers and decimal numbers in Python

texts:
The question is pretty self-explanatory. I wrote a regex pattern which should (in theory) match all possible integers and decimal numbers. The pattern is as follows:

import re

pattern = '^[+-]?((\d+(\.\d*)?)|(\.\d+))$'
re.compile(pattern)

How foolproof is this pattern? I tested out quite a few scenarios, and they all worked fine. Am I missing some edge case here? Thanks for any help.


texts: std::vector of pointers with the rule of three

texts:
I have a class that has a std::vector of pointers, I'm NOT going to give any of those pointers to objects outside of it, I mean, I'm not going to share the pointers. - I was reading that isn't everywhere that we will use smart pointers and that raw pointer isn't useless as long that someone is responsible for deleting it. The problem with that class is that it can be inherited and if I don't use the rule of three all the classes that inherits from will have a copy of the vector with the pointers then the destructor of those objects will result in double delete. - Is it safe or I still need to use std::shared_ptr in this case?

class Keeper
{
public:
    Keeper() {}
    Keeper(const Keeper&) = delete;
    Keeper& operator=(const Keeper&) = delete;

    virtual ~Keeper()
    {
        for (int i = 0; i < pointers.size(); ++i)
        {
            delete pointers[i];
        }
    }

    void push_back(Pointer * pointer)
    {
        pointers.push_back(pointer);
    }

    // erase method...
protected:
    std::vector<Pointer *> pointers;
};


texts: Thread safe singleton class to connect to Cassandra

texts:
I am working with Cassandra and using the Datastax Java driver for it. Here is my singleton class where it makes a connection to Cassandra:

public class CassUtil {
  private static final Logger LOGGER = Logger.getInstance(CassUtil.class);

  private Session session;
  private Cluster cluster;

  private static class Holder {
    private static final CassUtil INSTANCE = new CassUtil();
  }

  public static CassUtil getInstance() {
    return Holder.INSTANCE;
  }

  private CassUtil() {
    List<String> servers = TestUtils.HOSTNAMES;
    String username =
        TestUtils.loadCredentialFile().getProperty(TestUtils.USERNAME);
    String password =
        TestUtils.loadCredentialFile().getProperty(TestUtils.PASSWORD);

    PoolingOptions opts = new PoolingOptions();
    opts.setCoreConnectionsPerHost(HostDistance.LOCAL,
        opts.getCoreConnectionsPerHost(HostDistance.LOCAL));

    Builder builder = Cluster.builder();
    cluster =
        builder
            .addContactPoints(servers.toArray(new String[servers.size()]))
            .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)
            .withPoolingOptions(opts)
            .withReconnectionPolicy(new ConstantReconnectionPolicy(100L))
            .withLoadBalancingPolicy(
                DCAwareRoundRobinPolicy
                    .builder()
                    .withLocalDc(
                        !TestUtils.isProduction() ? "DC2" : TestUtils.getCurrentLocation()
                            .get().name().toLowerCase()).withUsedHostsPerRemoteDc(3).build())
            .withCredentials(username, password).build();

    try {
      session = cluster.connect("testkeyspace");
      StringBuilder sb = new StringBuilder();
      Set<Host> allHosts = cluster.getMetadata().getAllHosts();
      for (Host host : allHosts) {
        sb.append("[");
        sb.append(host.getDatacenter());
        sb.append(host.getRack());
        sb.append(host.getAddress());
        sb.append("]");
      }
      LOGGER.logInfo("CONNECTED SUCCESSFULLY TO CASSANDRA CLUSTER: " + sb.toString());
    } catch (NoHostAvailableException ex) {
      LOGGER.logError("error= ", ExceptionUtils.getStackTrace(ex));
    } catch (Exception ex) {
      LOGGER.logError("error= " + ExceptionUtils.getStackTrace(ex));
    }
  }

  public void shutdown() {
    LOGGER.logInfo("Shutting down the whole cassandra cluster");
    if (null != session) {
      session.close();
    }
    if (null != cluster) {
      cluster.close();
    }
  }

  public Session getSession() {
    if (session == null) {
      throw new IllegalStateException("No connection initialized");
    }
    return session;
  }

  public Cluster getCluster() {
    return cluster;
  }
}

I wanted to see if my CassUtil constructor can be improved in any way. It looks like CassUtil has 40+ lines of code. I think it can be broken down to a few methods but I am not able to figure out how I should do it.


texts:
I am trying to stop an executing runnable instance after the run method has been called.

I have come up with the below approach

    public class StoppableWorkflowTask implements Runnable {
        volatile Thread runner = null;

        @Override
        public void run() {
            runner = Thread.currentThread();
            try {

                while (true) {
                    System.out.println("Stop Thread " + Thread.currentThread().getId());
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

        void stop() {
            runner.stop();
        }

    }

public class StoppableWorkflowTaskTest {
    public static void main(String[] args) {
        StoppableWorkflowTask stoppableTask = new StoppableWorkflowTask();

        Thread thread = new Thread(stoppableTask);

        thread.start();
        System.out.println(thread.currentThread().getId());

        try {
            stoppableTask.stop();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

As per Java documention it is unsafe to call thread.stop(). I have checked few examples , but all either use thread.sleep() which can be terminated on interrupt.


texts:
I am making a code with basic RSA encryption/decryption.  My professor wants me to speed up this function but it is already so simple and I am lost.  Any ideas?

def decrypt(kenc,d,n):
    kdec=(kenc**d)%n
    return kdec


texts: Pandas add calculated row for every row in a dataframe

texts:
I have a dataframe like so:
id  variable  value
1      x        5
1      y        5
2      x        7
2      y        7

Now for every row, I want to add a calculated row. This is what I am doing as of now:
a = 2
b = 5
c = 1
d = 3
df2 = pd.DataFrame(columns =  ["id", "variable", "value"])
for index, row in df.iterrows():
    if row['variable'] == 'x':
        df2 = df2.append({'id':row['id'], 'variable':'x1', 'value':a*row['value']+b}, ignore_index=True)
    else:
        df2 = df2.append({'id':row['id'], 'variable':'y1', 'value':c*row['value']+d}, ignore_index=True)
df = pd.concat([df, df2])
df = df.sort_values(['id', 'variable'])

And so finally I get:
id  variable  value
1      x        5
1      x1       15
1      y        5
1      y1       8
2      x        7
2      x1       19
2      y        7
2      y1       10

But surely there must be a better way to do this. Perhaps where I could avoid for loop and sorting, as there are a lot of rows.


texts: Pull back records that include child records

texts:
I am trying to pull back records that include child records for the View I'm putting together. Right now I have a working Linq statement, but it's big, and I think I could make it cleaner.

var reqMatsInc = (from rm in db.RequiredMaterial
                    join p in db.Project on rm.ProjectTemplateId equals p.ProjectTemplateId
                    where p.ProjectId == id
                    select new RequiredMaterialViewModel
                    {
                        RequiredMaterialId = rm.RequiredMaterialId,
                        ProjectTemplateId = rm.ProjectTemplateId,
                        RequiredMaterialName = rm.RequiredMaterialName,
                        RequiredMaterialDescription = rm.RequiredMaterialDescription,
                        CustomFormId = rm.CustomFormId,
                        AcceptFile = rm.AcceptFile,
                        RequiredMaterialRoles = (
                        from rmr in db.RequiredMaterialRole
                        where rmr.RequiredMaterialId == rm.RequiredMaterialId
                        select new RequiredMaterialRoleViewModel
                        {
                            RequiredMaterialRoleId = rmr.RequiredMaterialRoleId,
                            RequiredMaterialId = rmr.RequiredMaterialId,
                            RoleId = rmr.RoleId,
                            RoleName = rmr.Role.RoleName,
                            IsActive = rmr.IsActive
                        }
                        ).ToList()
                    }
);

Right now the ViewModel classes are pretty much mirror images of the Code First class they represent. db is my DbContext.

Here are some of the ViewModel classes:

RequiredMaterialViewModel

public class RequiredMaterialViewModel
{
    public Guid RequiredMaterialId { get; set; }

    public Guid ProjectTemplateId { get; set; }

    public ProjectTemplate ProjectTemplate { get; set; }

    [Display(Name = "Required Material Name")]
    public string RequiredMaterialName { get; set; }

    [Display(Name = "Required Material Description")]
    public string RequiredMaterialDescription { get; set; }

    public Guid? CustomFormId { get; set; }

    public CustomForm CustomForm { get; set; }

    public bool AcceptFile { get; set; }

    public ICollection<RequiredMaterialRoleViewModel> RequiredMaterialRoles { get; set; }

    public bool IsActive { get; set; }
}

RequiredMaterialRoleViewModel:

public class RequiredMaterialRoleViewModel
{
    public Guid RequiredMaterialRoleId { get; set; }

    public Guid RequiredMaterialId { get; set; }

    public int RoleId { get; set; }

    public string RoleName { get; set; }

    public bool IsActive { get; set; }
}

I can just get the RoleName for this View; that simplifies it some.


texts:
I'm retrieving the operating system platform with .NET Core with system.runtime.interopservicesI have created the code below and was wondering if there was any other way that I could improve it since I haven't been able to get a switch statement to work in the OperatingSystem class.

/// <summary>
/// Operating System Class
/// For Retrieving The OS
/// Platform.
/// AE : 9/08/2018
/// </summary>
class OperatingSystem
{
    /// <summary>
    /// Operating System Platforms.
    /// </summary>
    public enum OSPlatform
    {
        Windows,
        OSX,
        Linux,
        Not_Supported
    }

    /// <summary>
    /// Return Operating System
    /// </summary>
    public static OSPlatform GetPlatform
    {
        // Switch Statement Not Compatitable
        get
        {
            if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                return OSPlatform.Windows;
            }
            else if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
            {
                return OSPlatform.OSX;
            }
            else if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux))
            {
                return OSPlatform.Linux;
            }
            else
            {
                return OSPlatform.Not_Supported;
            }
        }
    }
}

The class is being called like this,

static void Main()
{
    switch (OperatingSystem.GetPlatform)
    {
        case OperatingSystem.OSPlatform.Windows:
            Console.WriteLine("Goto Windows Class");
            break;
        case OperatingSystem.OSPlatform.OSX:
            Console.WriteLine("Goto OSX Class");
            break;
        case OperatingSystem.OSPlatform.Linux:
            Console.WriteLine("Goto Linux Class");
            break;
        default:
            Console.WriteLine("OS Not Supported");
            break;
        }
        Console.ReadKey();
    }


texts:
I have made an Android app called RunTracker - https://github.com/michaelnares/runtracker/tree/master/app.  The intended functionality is that the app saves runs to the local filesystem, shows your current location and current run, and has a clickable list of runs.  I feel that the existing code can be improved, but I'm not sure how.  For example, the code for the MainActivity is quite verbose:

package com.michaelnares.runtracker.activities;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;

import com.michaelnares.runtracker.R;
import com.michaelnares.runtracker.data.RunPoint;
import com.michaelnares.runtracker.utils.PermissionsHandler;
import com.michaelnares.runtracker.utils.RunsViewModel;
import com.michaelnares.runtracker.utils.Utils;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<RunPoint> runPointsList = new ArrayList<>();
    private RunsViewModel runsViewModel;
    private AppCompatActivity activity = this;
    private PermissionsHandler permissionsHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        permissionsHandler = new PermissionsHandler(this, MainActivity.this);
        setContentView(R.layout.activity_main);
        permissionsHandler.checkForPermissions();
        runsViewModel = ViewModelProviders.of(this).get(RunsViewModel.class);
        runsViewModel.setActivity(this);
        runsViewModel.setContext(getApplicationContext());

        final Button goToListButton = findViewById(R.id.goToList);
        goToListButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MainActivity.this, RunsListActivity.class);
                startActivity(intent);
            }
        }); // The setOnClickListener() block ends here.

        final Switch locationSwitch = findViewById(R.id.locationSwitch);
        locationSwitch.setChecked(runsViewModel.canTrackLocation());
        locationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                runsViewModel.setCanTrackLocation(isChecked);
                if (isChecked && permissionsHandler.allConditionsMet()) {
                    permissionsHandler.startTrackingRuns();
                } else { // So save the current run, if the user switches the toggle off.
                    saveCurrentRun();
                }
            }
        });
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Keeps the screen on always, when the app is running.
    } // The onCreate() method ends here

    private void saveCurrentRun() {

        if (runsViewModel == null) {
            runsViewModel = ViewModelProviders.of(this).get(RunsViewModel.class);
        }
        try {
            runsViewModel.saveCurrentRun(); // Saving them to external storage.
        } catch (JSONException e) {
            Log.e(Utils.getPackageName(MainActivity.this), "There was a JSONException whilst trying to save the journey points.");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(Utils.getPackageName(MainActivity.this), "There was an IOException whilst trying to save the journey points.");
            e.printStackTrace();
        }
    }
} // The main class ends here.

Can I rewrite the code to achieve better separation of concerns, i.e. less code in the MainActivity.  How can the code be improved elsewhere?


texts: Merging array entries referenced by indexes in another array

texts:
I have one question list (q_arr) and the user can either skip or attempt that question. In the end of last question, I display all question with their selected answer and "N/A"  if not attempted.

Attempted question list is r_arr, where q property is the question number from q_arr list (q:1 means the first element of q_arr).

    (function() {

    let r_arr = [{q:1, a:true},{q:3, a:false}];
    let q_arr = [
                { q: 'one', o: [true, false] },
                { q: 'two', o: [true, false] },
                { q: 'three', o: [true, false] },
                { q: 'four', o: [true, false] }
            ];

    //desired output: [{q:"one", a: true}, {q:"two", a: "N/A"}, {q:"three", a: false}, {q:"four", a:"N/A"}]

    let op = q_arr.filter((s, idx, arr) => {
        // console.log("s", s, idx, arr);
        let id = idx + 1;
        r_arr.map((f) => {
            if (id === f.q) {
                f.q = s.q;
            }
        });
    });

    console.log("r_arr", r_arr);
    })();

Now I again need to filter with q_arr and change to get not attempted question list and merge with this new r_arr and this seems a lengthy way.

Kindly suggest a way to solve this problem in fewer lines in ES6.


texts:
I am writing codes to have the Euclidean distance of two matrices and then storing them in a matrix. Could anyone please review this?

a <-matrix(1:2,ncol = 2,nrow = 2)
a
     [,1] [,2]
[1,]    1    1
[2,]    2    2

b <-matrix(3:6,ncol = 2,nrow = 2)
b
     [,1] [,2]
[1,]    3    5
[2,]    4    6

n <-matrix(data = NA)
 for (i in 1:nrow(a)) {
   for (j in 1:nrow(b)) {
    n[i]<-sum(abs(a[i,]-b[j,])^2)
  }
}
n


texts: Razor view to render simple scaffolding for complex type

texts:
After several attempts to follow my intuition that this code can be refactored to something more DRY, I keep hitting road blocks.

Hoping someone can see a refactor that might get me going in a nicer direction.

I'm trying not to break anything out of this one code file, although, I suppose helper types could be placed in a top level code block if they help.

This razor view essentially presents all string string types in an arbitrarily complex type as a single form:

Member.cshtml

@model Tuple<object, Type, string>
@{
    var targetObj = Model.Item1;
    var targetType = Model.Item2;
    var path = Model.Item3;
}

    @foreach (var prop in
        from p in targetType.GetProperties()
        where p.Name != "SyncRoot"
        orderby p.Name
        select p)
    {
        var name = (path + "." + prop.Name).TrimStart('.');
        if (prop.PropertyType == typeof (string))
        {
            var value = "";
            if (targetObj != null)
            {
                var propValue = prop.GetValue(targetObj);
                if (propValue != null)
                {
                    value = propValue.ToString();
                }
            }

                @prop.Name
                <input class="form-control" value="@value" name="@name"/>

        }
        else if (prop.PropertyType.IsArray && prop.PropertyType.GetElementType() == typeof (string))
        {
            var value = "";
            if (targetObj != null)
            {
                var propValue = prop.GetValue(targetObj) as string[];
                if (propValue != null)
                {
                    value = propValue[0];
                }
            }

                @(prop.Name)[]
                <input class="form-control" value="@value" name="@(name)[0]"/>

        }
        else if (prop.PropertyType.IsArray)
        {
            object value = null;
            if (targetObj != null)
            {
                value = prop.GetValue(targetObj);
            }

                <fieldset>
                    <legend>@(prop.Name)[]</legend>
                    @Html.Partial("Member", Tuple.Create(value, prop.PropertyType.GetElementType(), name))
                </fieldset>

        }
        else if (!prop.PropertyType.Name.StartsWith("System."))
        {
            object value = null;
            if (targetObj != null)
            {
                value = prop.GetValue(targetObj);
            }

                <fieldset>
                    <legend>@prop.Name</legend>
                    @Html.Partial("Member", Tuple.Create(value, prop.PropertyType, name))
                </fieldset>

        }
    }


texts:
I reinvented a c++ smart pointer, shared_ptr to be precise. It is meant for practice purpose and does not attempt to replace the standard implementation. To the best of my knowledge, the code works as expected. I decided to skip the custom deleter because I want to keep things simple for now. I would love feedbacks and constructive criticism.
Here is the implementation
shared.hpp
#ifndef SHARED_PTR_H_
#define SHARED_PTR_H_

#include <cstddef>

namespace smp
{
    template<typename T>
    class shared_ptr
    {
        public:
            explicit shared_ptr(T* ptr = nullptr);
            ~shared_ptr();
            shared_ptr(shared_ptr& ptr);
            shared_ptr operator=(shared_ptr& ptr);
            shared_ptr(shared_ptr&& ptr) noexcept;
            shared_ptr operator=(shared_ptr&& ptr) noexcept;

            T operator*();
            T* operator->() const;

            size_t use_count() const;
            void reset();
            T* get();
            bool unique() const;
            operator bool() const;

        private:
            T* obj_ptr;
            struct RefCount {
                size_t use_count_;
                T* object_;
            }* ref_cnt;

    };

    template<typename T>
    shared_ptr<T> make_shared(T object);
}

#endif /* SHARED_PTR_H_ */

shared.cpp
#include "shared.hpp"

#include <algorithm>
#include <iostream>

namespace smp
{
    template<typename T>
    shared_ptr<T>::shared_ptr(T* ptr)
        : obj_ptr{ptr}, ref_cnt{new RefCount()}
    {
        ref_cnt->object_ = ptr;
        if(ptr)
            ++ref_cnt->use_count_;
    }

    template<typename T>
    shared_ptr<T>::shared_ptr(shared_ptr& ptr)
        : ref_cnt{new RefCount()}
    {
        obj_ptr = ptr.obj_ptr;
        ref_cnt = ptr.ref_cnt;

        ++ref_cnt->use_count_;
    }

    template<typename T>
    shared_ptr<T> shared_ptr<T>::operator=(shared_ptr& ptr)
    {
        obj_ptr = ptr.obj_ptr;
        ref_cnt = ptr.ref_cnt;
        ++ref_cnt->use_count_;

        return *this;
    }

    template<typename T>
    shared_ptr<T>::shared_ptr(shared_ptr&& ptr) noexcept
        : obj_ptr{nullptr}, ref_cnt{new RefCount()}
    {
        obj_ptr = std::move(ptr.obj_ptr);
        ref_cnt = std::move(ptr.ref_cnt);

        ptr.reset();
    }

    template<typename T>
    shared_ptr<T> shared_ptr<T>::operator=(shared_ptr&& ptr) noexcept
    {
        if(obj_ptr)
            reset();
        obj_ptr = std::move(ptr.obj_ptr);
        ref_cnt = std::move(ptr.ref_cnt);

        ptr.obj_ptr = nullptr;

        return *this;
    }

    template<typename T>
    shared_ptr<T> make_shared(T object)
    {
        return shared_ptr<T>(new T{object});
    }

    template<typename T>
    T shared_ptr<T>::operator*()
    {
        return *obj_ptr;
    }

    template<typename T>
    T* shared_ptr<T>::operator->() const
    {
        return &*obj_ptr;
    }

    template<typename T>
    size_t shared_ptr<T>::use_count() const
    {
        return ref_cnt->use_count_;
    }

    template<typename T>
    void shared_ptr<T>::reset()
    {
        obj_ptr = nullptr;

        if(ref_cnt)
            --ref_cnt->use_count_;

        if(ref_cnt->use_count_ == 0)
            ref_cnt->object_->~T();
    }

    template<typename T>
    T* shared_ptr<T>::get()
    {
        return obj_ptr;
    }

    template<typename T>
    bool shared_ptr<T>::unique() const
    {
        return (ref_cnt->use_count_ == 1);
    }

    template<typename T>
    shared_ptr<T>::operator bool() const
    {
        return (obj_ptr != nullptr);
    }

    template<typename T>
    shared_ptr<T>::~shared_ptr()
    {
        if(obj_ptr)
            reset();
    }
}


texts:
I'm new to SQLite but have programmed in BASIC (and other languages) for pushing 50 years.

Given the sample code extract, please offer suggestions for improvement:

    Sub addAuthor(ByVal authorlnf As String, ByVal authorfnf As String)
        Dim objConn As SQLiteConnection
        Dim objCommand As SQLiteCommand
        objConn = New SQLiteConnection(CONNECTION_STR)
        objConn.Open()
        objCommand = objConn.CreateCommand()
        objCommand.CommandText = "INSERT INTO [author] ([authorlnf], [authorfnf]) VALUES ('" & authorlnf & "', '" & authorfnf & "');"
        Try
            objCommand.ExecuteNonQuery()
        Catch ex As InvalidOperationException
            MessageBox.Show("An error has occurred: " & ex.Message)
        Catch ex As SQLiteException
            MessageBox.Show("An error has occurred: " & ex.Message)
        End Try

        If Not IsNothing(objConn) Then objConn.Close()

End Sub

This is an index of book authors and this routine will be called several thousand times. I'm replacing VB dictionaries as memory is becoming a limiting factor.


texts:
With Tornado 3.2 they made some updates to auth module and have updated the code. Earlier I was using open id for Google login, since it will be deprecated in the future I am switching the code to Oauth 2.0 login. Also I was using tornado.web.asynchronous, now I have updated the code to use tornado.gen.coroutine

/products is only available for logged in users. Once the user is authenticated from Google or Facebook, a cookie called 'trakr' is set. In implementation of get_current_user() whether 'trakr' is set or not is checked.

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        user = self.get_secure_cookie('trakr')
        if not user: return None
        return True

class FAuthLoginHandler(BaseHandler, tornado.auth.FacebookGraphMixin):
    @tornado.gen.coroutine
    def get(self):
        if self.get_current_user():
            self.redirect('/products')
            return

        if self.get_argument('code', None):
            user = yield self.get_authenticated_user(
                redirect_uri=settings.fb_redirect_url,
                client_id=self.settings['facebook_api_key'],
                client_secret=self.settings['facebook_secret'],
                code=self.get_argument('code'))

            if not user:
                self.clear_all_cookies()
                raise tornado.web.HTTPError(500, 'Facebook authentication failed')

            user = yield self.facebook_request("/me", access_token=user["access_token"])

            if not user:
                raise tornado.web.HTTPError(500, "Facebook authentication failed.")

            self.set_secure_cookie('trakr', user.get('email'))
            self.redirect('/products')
            return

        elif self.get_secure_cookie('trakr'):
            self.redirect('/products')
            return

        else:
            yield self.authorize_redirect(
                redirect_uri=settings.fb_redirect_url,
                client_id=self.settings['facebook_api_key'],
                extra_params={'scope': 'email'}
            )

class GAuthLoginHandler(BaseHandler, tornado.auth.GoogleOAuth2Mixin):
    @tornado.gen.coroutine
    def get(self):
        if self.get_current_user():
            self.redirect('/products')
            return

        if self.get_argument('code', False):
            user = yield self.get_authenticated_user(redirect_uri=settings.google_redirect_url,
                code=self.get_argument('code'))
            if not user:
                self.clear_all_cookies()
                raise tornado.web.HTTPError(500, 'Google authentication failed')

            access_token = str(user['access_token'])
            http_client = self.get_auth_http_client()
            response =  yield http_client.fetch('https://www.googleapis.com/oauth2/v1/userinfo?access_token='+access_token)
            user = json.loads(response.body)

            self.set_secure_cookie('trakr', user['email'])
            self.redirect('/products')
            return

        elif self.get_secure_cookie('trakr'):
            self.redirect('/products')
            return

        else:
            yield self.authorize_redirect(
                redirect_uri=settings.google_redirect_url,
                client_id=self.settings['google_oauth']['key'],
                scope=['email'],
                response_type='code',
                extra_params={'approval_prompt': 'auto'})