texts:
This is solution to the assembly line problem.  Here is complete description, which is too big and verbose to re-describe. I apologize for the inconvenience of the hyperlink.

Note: I do understand merits of unit testing in separate files. But deliberately added it to main method for personal convenience, so I request that you not consider that in your feedback.

I'm looking for request code review, optimizations and best practices.

final class Station {

    private final int stationTime;
    private final int transtionToTime; // time to transition`to` this station
    private final int transitionFromTime; // time to transitition `from` this station.

    public Station(int stationTime, int transitionTime, int transitionFromTime) {
        this.stationTime = stationTime;
        this.transtionToTime = transitionTime;
        this.transitionFromTime = transitionFromTime;
    }

    public int getStationTime() {
        return stationTime;
    }

    public int getTransitionToTime() {
        return transtionToTime;
    }

    public int getTransitionFromTime() {
        return transitionFromTime;
    }
}

public final class AssemblyLine {

    private AssemblyLine() {}

    /**
     * Given an assembly line, outputs the shortest time needed to go through it.
     * The input data structures are not expected to be changed by client.
     *
     * @param line1     the assembly line 1
     * @param line2     the assumbly line 2
     * @return          the minumum time needed to process the item.
     */
public static int assemblyLineShortestTime(List<Station> line1, List<Station> line2) {
    int prevLine1Min = line1.get(0).getStationTime() + line1.get(0).getTransitionToTime();
    int prevLine2Min = line2.get(0).getStationTime() + line2.get(0).getTransitionToTime();
    for (int i = 1; i < line1.size(); i++) {
        int currentLine1Min = line1.get(i).getStationTime() + Math.min(prevLine1Min, prevLine2Min + line1.get(i).getTransitionToTime());
        int currentLine2Min = line2.get(i).getStationTime() + Math.min(prevLine1Min + line2.get(i).getTransitionToTime(), prevLine2Min);

        prevLine1Min = currentLine1Min;
        prevLine2Min = currentLine2Min;
    }
    return Math.min(prevLine1Min + line1.get(line1.size() - 1).getTransitionFromTime(), prevLine2Min + line2.get(line2.size() - 1).getTransitionFromTime());
}

    public static void main(String[] args) {

        List<Station> line1 = new ArrayList<Station>();
        line1.add(new Station(4, 10, 7));
        line1.add(new Station(5,  9, 4));
        line1.add(new Station(3,  2, 5));
        line1.add(new Station(2,  8, 18));

        List<Station> line2 = new ArrayList<Station>();
        line2.add(new Station( 2, 12, 9));
        line2.add(new Station(10,  7, 2));
        line2.add(new Station( 1,  4, 8));
        line2.add(new Station( 4,  5, 7));

        assertEquals(35, assemblyLineShortestTime(line1, line2));
    }
}


texts: C++ conversion from std::string to arithmetic type using std::locale::classic()

texts:
I recently had a bug where extracting a decimal from a string failed due to locale settings. That is, some locales use a , as a decimal point, rather than a .. An important goal is that the conversion function is deterministic.

I have usually used boost::lexical_cast for such tasks, but my understanding is that this is reliant on the global application locale. I have therefore implemented a variant of lexical_cast that uses the std::locale::classic "C" locale for the conversion.

#include <type_traits>
#include <locale>
#include <string>
#include <sstream>
#include <stdexcept>

namespace typeconv
{

/**
 * Convert @c str to a T
 *
 * @param str string to convert to a T
 * @return the value contained within @c as a T
 *
 * @pre @c str is arithmetic and can be converted to a T
 * @note std::locale::classic() is used for the conversion.
 *
 * @throws std::invalid_argument if str cannot be converted to an object of type T.
 */
template<typename T>
inline auto lexical_cast(const std::string& str)
    -> typename std::enable_if<std::is_arithmetic<T>::value, T>::type
{
    std::istringstream istr(str);
    istr.imbue(std::locale::classic());

    T val;
    istr >> val;

    if (istr.fail())
        throw std::invalid_argument(str);

    return val;
}

}

I plan to extend the template function in future to include other conversions, such as an arithmetic type to std::string. Any comments on the implementation are welcome.


texts:
I am new to programming, and think this code could be improved upon.  Any suggestions?

  #include <stdio.h>
  #define size 10
  void main()
  {

    int  i,j,ii,jj,arr[size]={1,2,4,2,1,1,2,1,1,2};
    int count=0, max_count=0, start_index=0, temp_start_index=0;

    for(i=0;i<size;++i)
    {
       for (j=size-1;j>=0;--j)
       {
          for (ii=i,jj=j;;++ii,--jj)
          {
             if (arr[ii]==arr[jj])
             {
                if (count==0)
                {
                   temp_start_index=ii;
                }
                ++count;
                if (ii==jj)    //odd number of elements in palindrome
                {
                    count=count*2-1;
                    break;
                }else{
                       if (ii>jj)   //even number of elements in palindrome
                       {
                          --count;
                          count=count*2;
                          break;
                       }
               }

           }

           else
           {
               count=0;
               break;
           }
       }

       if (count>max_count)
       {
           max_count=count;
           start_index=temp_start_index;
           count=0;
           temp_start_index=0;

       }
   }
 }

  for (i=start_index;i<start_index+max_count;++i)
  {
    printf("%d ",arr[i]);
  }
  printf("\n");
  printf("%d\n",max_count);
 }


texts:
i came across this fun puzzle while being on vacation.

It was designed by Robert Abbott and painted into the grass of a Wisconsin farm. Robert succeeded into making it seem really easy to solve. Well, it is not. I spent hours with my friends wandering the puzzle and left frustrated.

I decided to solve it using computers. chose javascript because it made it easy to visualize the process and solution.

Initially i started with a brute force algorithm, which run for hours and got me nowhere. Than i shifted to this final one (below). I just kinda came up with this recursive solution that explores all paths, and terminates any path that comes across a previously visited node, so the one that makes it to the end should be the shortest one in (my) theory. I am wondering if this is a known algorithm (and how i botched it), and if there is a better way to achieve this. Also this algo appears to find the answer in 28 steps (including entry step).. A friend of mine solved this using an algo that works its way back from the end which supposedly solved it in 20 steps.

anyways, the working solution can be seen here.

here is the recursive function:

_delay = 50;
_successfulSteps = null;
function findRecursive(params){
    var cell = params[0];
    var steps = params[1];
    var history = params[2];
    var x = getX(cell);
    var y = getY(cell);
    var steps = getCellSteps(cell);
    markCellActive(x,y);

    var h = [];
    for (var i = 0; i<history.length; i++) {
        h.push(history[i]);
    };
    h.push([getX(cell),getY(cell)]);

    if (steps == 0) {
        var sp = $('#solutionSpan')[0];
        sp.innerHTML = 'solved in ' + h.length + ' steps';
        return;
    }

    for (var i = history.length - 1; i >= 0; i--) {
        if (x == history[i][0] && y == history[i][1]) {
            // this cell already processed
            console.log('terminating recursion for: ' + y + ':' + x);
            return;
        }
    };

    var rightCell = getRightCell(x,y, steps);
    var leftCell = getLeftCell(x,y, steps);
    var upCell = getUpCell(x,y, steps);
    var downCell = getDownCell(x,y, steps);

            // add delay to visualize the process
    if (rightCell){
        setTimeout(findRecursive, _delay, [rightCell, steps, h]);
    }
    if (leftCell){
        setTimeout(findRecursive, _delay, [leftCell, steps, h]);
    }
    if (upCell){
        setTimeout(findRecursive, _delay, [upCell, steps, h]);
    }
    if (downCell){
        setTimeout(findRecursive, _delay, [downCell, steps, h]);
    }

}

(i should note that this is not the prettiest code and i'm not looking for a way to reduce # of lines or anything, just to find a better algorithm)


texts:
I want to get this code reviewed for a function I wrote that pulls log messages from a MySQL table:

def get_logs_messages(request_id, destination=None):
    """
        get logs from deployment table
    :param int request_id: request id of selected deployment.
    :param str destination: destination site
    :return: list of messagesfor selected deployment based on request id.
    :rtype: list
    """
    conn = MySQLdb.connect(**dbconfig)
    query = "SELECT deployment_id " \
            "from deployment " \
            "WHERE request_id={request_id} " \
            " {dest}".format(
                request_id=request_id,
                dest="AND DESTINATION = '{loc}'".format(loc=destination) if destination else "")
    cursor = conn.cursor()
    cursor.execute(query)
    data = cursor.fetchall()
    cursor.close()
    msgs = []
    for item in data:
        query = "SELECT modified_dt , message from scripts_deployment_logs WHERE deployment_id = {}".format(item[0])
        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        for dt, msg in result:
            msgs.append("{dt}: {msg}".format(dt=str(dt), msg=msg))
        cursor.close()
    conn.close()
    return msgs

I get a request ID from a web interface which is using a REST API to call this function, and this function retrieves the deployment id based on which it displays the logs. I am not very fluent with the MySQL part so I have used mysql.connector with simple SQL queries.


texts: Shortest path from U to V using at most k nodes

texts:
I'm trying to solve a problem that asks for a shortest path between two cities with at most k nodes.

The first line of input has the number of test cases. On the second line 3 integers are given, which are respectively, the number of nodes, the number of edges and the maximum number of nodes in the shortest path. After that all edges are described with 3 integers representing 2 connected cities and a weight of travel from city 1 to city 2.

For the output just print the shortest path. If there is no shortest path print '-1'

I'm using a \$O(k * n ^ 2)\$ Floyd-Warshall solution. Is there a better solution? This solution is exceeding the time limit.

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

#define MAX ((unsigned int) -1)

int main(){
    unsigned int number_of_cases;
    scanf("%u",&number_of_cases);

    for (int i = 0; i < number_of_cases; ++i) {
        unsigned int number_of_nodes,number_of_edges,limit_of_nodes;
        scanf("%u %u %u",&number_of_nodes,&number_of_edges,&limit_of_nodes);

        unsigned int g[number_of_nodes][number_of_nodes];
        memset(g, -1, sizeof(g));

        for (int j = 0; j < number_of_edges; ++j) {
            unsigned int u,v,w;
            scanf("%u %u %u",&u,&v,&w);
            g[u][v] = w < g[u][v] ? w : g[u][v]; //since there is no negative weight... we can choose the minimum one to the adjacency list and ignore the others.
        }

        /*
            In the k'th run the floyd-warshall algorithm gives the shortest path with k edges.
            If i want a shortest path with number of nodes = limit_of_nodes . I just need limit_of_nodes - 1 edges.
         */
        --limit_of_nodes;
        for (int k=0 ; k < limit_of_nodes ; k++)
            for (int i=0 ; i < number_of_nodes ; i++)
                for (int j=0 ; j < number_of_nodes ; j++)
                    if (g[i][k] !=  MAX && g[k][j] != MAX && g[i][k] + g[k][j] < g[i][j])
                        g[i][j] = g[i][k] + g[k][j];

        if(g[0][number_of_nodes-1] == MAX )
            puts("-1");
        else
            printf("%u\n", g[0][number_of_nodes-1]);
    }

    return 0;
}

Some observations:

The number of nodes of a solution can't be less than 2 (since the initial and final nodes are in the solution).
There are no negative numbers on the input.
There can be more than 1 edge between 2 cities. (Is this relevant ?)

Input sample:

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

Output sample:

5
-1
3

A complete description of the problem is here


texts:
I'm interested in recursive generation of trees in Python.  For my eventual application, it's important that the trees be represented as a list of nodes (rather than say a dictionary, or an edge list, or some other format).  Also, in my eventual application, each node of the tree will have between 0 and hundreds of children.  In this skeleton code, the number of children for each node is generated randomly.

The trees generated have a parameter-defined maximum depth, but because even nodes not at the maximum depth might have no children, some leaves will be closer to the root than others.

I wrote this function for the task:

import random

def generate_random_tree(nodelist=[], idx=0, parent=None, depth=0, max_children=2, max_depth=2):
    """Build a list of nodes in a random tree up to a maximum depth.
        :param:    nodelist     list, the nodes in the tree; each node is a list with elements [idx, parent, depth]
        :param:    idx          int, the index of a node
        :param:    parent       int, the index of the node's parent
        :param:    depth        int, the distance of a node from the root
        :param:    max_children int, the maximum number of children a node can have
        :param:    max_depth    int, the maximum distance from the tree to the root"""
    if depth < max_depth and depth >=0:
        # add a random number of children
        n = random.randint(0, max_children)
        nodelist.extend([[idx+i, parent, depth] for i in xrange(n)])

        # for each new child, add new children
        [generate_random_tree(nodelist, len(nodelist), idx+i, depth+1, max_children, max_depth) for i in xrange(n)]

    elif depth == max_depth:
        # add a random number of leaves
        n = random.randint(0, max_children)
        nodelist.extend([[idx+i, parent, depth] for i in xrange(n)])
        return

    else:  # this should never happen
        raise ValueError('Algorithm halted because depth > max_depth or depth < 0.')
        return

The function is used like this:

tree =[[0, None, 0]]  # the algorithm starts with a root node which has no parents and depth 0
random.seed(0)
generate_random_tree(nodelist=tree, idx=len(tree), parent=0, depth=1, max_children=3, max_depth=3)

[0, None, 0]
[1, 0, 1]
[2, 0, 1]
[3, 0, 1]
[4, 1, 2]
[5, 1, 2]
[6, 1, 2]
[7, 4, 3]
[8, 5, 3]
[9, 6, 3]
[10, 6, 3]
[11, 2, 2]
[12, 11, 3]
[13, 11, 3]
[14, 11, 3]
[15, 3, 2]
[16, 15, 3]

This function does the task, but I'm eager for feedback on the quality of this implementation.  Any feedback is welcome, of course, but particular questions I have include:

Are there any better ways to find appropriate indices for each new node other than calling len()?
Are there simple, recursive Python implementations that return values rather than relying on list mutability?
(This may be out of scope for se.cr; if so, please ignore)  Is there a way to get the enumeration to be depth-first rather than the breadth-first implementation I currently have?

Although this code isn't going to go into a production in environment or be worked on by teams of professional software engineers, high-level comments about readability, best practices, and hidden corner cases would be much appreciated.


texts: Two approaches to print all permutations - returning versus passing through the “result” list

texts:
I have noticed many of the backtracking problems have two ways of solving.

One is to return "whatever's the required list", vs passing-through the "result" to every call and appending to it. What is the downside of returning (is it less memory/time efficient)? Example - To print all possible permutations, what makes this solution inefficient vs the second one.

public List<List<Integer>> perm(int[] nums){
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    if(nums.length == 0){
        result.add(new ArrayList<Integer>());
        return result;
    }
    for(int i= 0;i<nums.length;i++){
        int first = nums[i];
        int[] remnums = new int[nums.length-1];
        int j = 0;
        for(int cur : nums){
            if(cur != first){
                remnums[j] = cur;j++;
            }
        }
        List<List<Integer>> tmp = perm(remnums);

        for(List<Integer> t : tmp){
            t.add(0,first);

        }
        result.addAll(tmp);
    }
    return result;
}

2nd approach ---

public List<List<Integer>> permute(int[] nums) {
   List<List<Integer>> list = new ArrayList<>();
   // Arrays.sort(nums); // not necessary
   backtrack(list, new ArrayList<>(), nums);
   return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
   if(tempList.size() == nums.length){
      list.add(new ArrayList<>(tempList));
   } else{
      for(int i = 0; i < nums.length; i++){
         if(tempList.contains(nums[i])) continue; // element already exists, skip
         tempList.add(nums[i]);
         backtrack(list, tempList, nums);
         tempList.remove(tempList.size() - 1);
      }
   }
}


texts:
To recover from yesterday's disaster, I re-read the SOLID principles and refactored my code. Hopefully I did a better job than yesterday. I wanted to keep my Student class immutable, but that meant I would have to change the class every time a new Student type was introduced, that violated the S in SOLID. Here is what I came up with.

public interface StudentStatus {
    Collection<String> retrieveDocuments();
    StudentType retrieveStatus();
}

public final class Student {

   private final String ID;
   private final String firstname;
   private final String lastname;
   private final StudentStatus status;

   public Student(String iD, String firstname, String lastname, StudentStatus status) {
       ID = iD;
       this.firstname = firstname;
       this.lastname = lastname;
       this.status = status;
   }

   public Collection<String> retrieveDocuments() {
       return status.retrieveDocuments();
   }

   public StudentType retrieveStatus() {
      return status.retrieveStatus();
   }

My requirements are:

Domestic students don't require documentation
International student do require documentation (passports, etc..)

Domestic Implementation:

    public final class Domestic implements StudentStatus {

       private final StudentType type;
       private final Collection<String> documents;

       public Domestic() {
           this.type = StudentType.Domestic;
           this.documents = unmodifiableList(new ArrayList<String>(documents);
       }

       @Override
       public Collection<String> retrieveDocuments() {
           return unmodifiableList(new ArrayList<String>(documents);
       }

       @Override
       public StudentType retrieveStatus() {
           return type;
       }
   }

International Implementation:

    public final class International implements StudentStatus {

       private final StudentType type;
       private Collection<String> documents;

       public International(Collection<String> documents) {

           this.type = StudentType.International;
           this.documents = Collections.unmodifiableList(new ArrayList<String>(documents));
       }

       @Override
       public Collection<String> retrieveDocuments() {
           return Collections.unmodifiableList(new ArrayList<String>(documents));
       }

       @Override
       public StudentType retrieveStatus() {
          return type;
       }
    }

If there is any new type of status, it can be added my implementing StudentStatus, no need to modify the Student class.

Use:

        List<String> documents = new ArrayList<String>();
        documents.add("Passport");
        documents.add("Drivers License");

        StudentStatus domestic = new Domestic();
        StudentStatus international = new International(documents);

        List<Student> students = new ArrayList<Student>();
        students.add(new Student("123456789","Susan","Ceesharp", domestic));
        students.add(new Student("987654321","Bill","Finalclass", international));

        for(Student display : students) {
            System.out.println(display.getID() + " " + display.retrieveStatus());
        }

I'm aware none of my classes have validation, I kept these out to keep my code clear and concise.

Goal:
Keep the Student immutable without violating SOLID.


texts: Goldbach's Conjecture using Sieve of Eratosthenes

texts:
I created a simple Java program to calculate Goldbach's conjecture and I was wondering how I could improve it (besides using clearer prompt messages).

/* Title: Goldbach Conjecture
 * Author: Harris R
 */

import java.util.Scanner;

public class Goldbach
{
  public static void main(String[] args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please input an integer to find two prime numbers whose sum add up to it.");
    int input = scan.nextInt();
    if(input < 4)
    {
      System.out.println("Number must be greater than or equal to 4");
      return;
    }
    if(input%2 > 0)
    {
      System.out.println("Number must be even.");
      return;
    }
    long startTime = System.nanoTime();
    int[] primes = generatePrimes(input);
    findPairs(input, primes);
    long endTime = System.nanoTime();
    System.out.println("\n This program took: " + (endTime-startTime) + " nanoseconds or " + ((endTime-startTime)*1e-9) + " seconds.");
  }

  private static int[] generatePrimes(int max)
  {
    boolean[] isComposite = new boolean[max + 1];
    for (int i = 2; i * i <= max; i++)
    {
      if (!isComposite [i])
      {
        for (int j = i; i * j <= max; j++)
        {
          isComposite [i*j] = true;
        }
      }
    }
    int numPrimes = 0;
    for (int i = 2; i <= max; i++)
    {
      if (!isComposite [i]) numPrimes++;
    }
    int [] primes = new int [numPrimes];
    int index = 0;
    for (int i = 2; i <= max; i++)
    {
      if (!isComposite [i]) primes [index++] = i;
    }
    return primes;
  }

  private static void findPairs(int input, int[] primes)
  {
    String primepairs = "";
    for(int i = 0; i < primes.length; i++)
    {
      for(int j = i; j < primes.length; j++)
      {
          int p = primes[i];
          int q = primes[j];
          if(p+q == input)
          {
              primepairs += "\n" + q + " + " + p + " = " + input;
          }
      }
      System.out.println("Program Completion: " + (((double)i/primes.length)*100) + "%");
    }
    System.out.println(primepairs);
  }
}


texts: JavaScript calculator using inputs value

texts:
I’m trying to make a simple calculator with 3 inputs in JavaScript but it doesn’t work. For now my code is:

<input placeholder="Number" id="Number F” class="Number F" onchange="calculator()">
<input placeholder="/ ,  * ,  -  or +" id="Number O" class="Number O" onchange="calculator()">
<input placeholder="Number" id="Number S" class="Number S" onchange="calculator()">

<button id="button" onclick="calculator()"></button>

I’m beginner in coding. What is wrong? Please Help Me! Thank you!


texts:
This scrapes results from thefreedictionary.com:

#!/usr/bin/python

from bs4 import BeautifulSoup as bs
import re
from requests import get

def remove_non_ascii(text):
    return re.sub(r'[^\x00-\x7F]+', '', text)

def get_soup(url):
    raw = remove_non_ascii(get(url).content)
    soup = bs(raw)
    return soup.select("#MainTxt")[0].select('.ds-single')[0].text.strip()

def lookup(word):
    base_url = "http://www.thefreedictionary.com/"
    query_url = (base_url + word)
    return get_soup(query_url)

if __name__ == '__main__':
    print lookup('linux')

Example

Warning: this script may fail to comply with thefreedictionary.com's TOS


texts: Python program to find Armstrong numbers in a certain range

texts:
I have written a Python program to check for Armstrong numbers in a certain range.

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.

Here is my code:

lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))

for num in range(lower, upper + 1):

   order = len(str(num))

   sum = 0

   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit ** order
       temp //= 10

   if num == sum:
       print(num)

Here is an example output:

Enter lower range: 200
Enter upper range: 5000

370
371
407
1634

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts:
I have the following assignment that I succeeded in solving, but the code is very inefficient.  I would appreciate if someone could show me a more efficient way, perhaps with substring. Note that I am not allowed to use imports or regexes or add more functions.

/**
 * Separates a given string into tokens, which are the "words" that are
 * separated by one or more occurrences of the given separator character.
 * Returns the tokens as an array of String values.
 */
public static String[] tokenize (String str, char separator) {
    // Removes all the occurrences of the separator at the beginning and end of str
    String source = trim(str, separator);
    String[] tokens = new String[charRunCount (source,separator)+1];
    String tmp = ""; // a string in order to take a word, then run over this string
    int j = 0;
    int i = 0;
    while (i < tokens.length) {
        if ( source.charAt (j) != separator ) {
            do {
                tmp += source.charAt (j);
                if ( j >= source.length () - 1 ) {
                    break;
                }
                else { // so that we math the source length
                    j++;
                }
            } while (source.charAt (j) != separator);
        }
        if ( source.charAt (j) == separator ) {
            j++;
            while (source.charAt (j) == separator) {
                j++;
            }
        }
        tokens[i] = tmp;// taking the token into place
        tmp = ""; //resetting the token so we can begin anew

        i++;
    }
    return tokens;
}

the charRunCount() function:

public static int charRunCount(String str, char c){
    char last = 0;
    int counter = 0;
    for (int i = 0; i < str.length(); i++) {
        // whenever a run starts.
        if (last != c && str.charAt(i) == c) {
            counter++;
        }
        last = str.charAt(i);
    }
    return counter;
}


texts: Pigeon and grain problem: find time until all the grain is eaten

texts:
Problem:

  There are \$n\$ pigeons and \$m\$ grains. Pigeon \$i\$ eats a single grain every \$x_i\$ seconds. Find the time until all the grain is eaten.

  Input:

  A line with the integer \$m\$ giving the number of grains, followed by a line with \$n\$ integers \$x_1, x_2, \ldots, x_n\$ giving the time taken by each pigeon to eat one grain.

Currently I am doing a loop over each second and finding how many grains in that seconds are eaten. This with numpy I am able to get a good performance but for large inputs (\$m=10^{25}\$ and \$n=300000\$) the program runs forever.

What can I do mathematically to solve this?

import numpy

def melt(grains,birdTimes):
    counter=0
    counts = numpy.zeros(len(birdTimes,),dtype=numpy.int)
    birdTimes = numpy.array(birdTimes)
    while (grains>0):
        counts=counts+1
        temp=birdTimes-counts
        zeroA = numpy.where(temp==0)[0]
        grains = grains - len(zeroA)
        counts[zeroA] =0
        counter+=1
    return counter


texts: Building navigation structure for multiple users by adding values to multiple arrays at once

texts:
I have a multidimensional array with associative values... I want to add some information to multiple arrays at the same time. Doing $array1=$array2=array(... seems to work but I'm worried that it's too easy. Will any array get extra data or have data overwritten by doing this?
What kind of unexpected behavior might I expect from this kind of code? Al should have 3 entries in it, while Bob and Chris will each have two... right? It seems to work, but I'm worried I'm overlooking something.

<?    $content['Al'][]= array(
       "link"=>"/admin.php",
       "text"=>"Admin Login",
       "icon"=>"wp.png");
    $content['Al'][]=$content['Bob'][]=$content['Chris'][] = array(
       "link"=>"/Wordpress/wp-login.php",
       "text"=>"Login to Wordpress",
       "icon"=>"wp.png");
    $content['Al'][]=$content['Bob'][]=$content['Chris'][] = array(
       "link"=>"/Gallery/Login.php",
       "text"=>"Login to Gallery",
       "icon"=>"picutres.jpg");

function userbox($heading,$contents){
    if($contents=="") return;
    echo "

".$heading."

";

    foreach ($contents as $key){
        if($key['link']!="")echo "";
        if($key['icon']!="")echo"";
        echo $key['text'];
        if($key['link']!="")echo "";
        if($key['updated']!="")echo " (".$key['updated'][0].")";
        echo "
";
        }
    echo "

";
}

?>

Then in the content of the page I have

<?userbox($user,$content[$user]);?>

This should show a 'refbox' div with the users links in it within the page.


texts:
I wrote code that parses a table header string in order to obtain two string tags, one for variable name (like GDP) and another for unit of measurement (like bln_rub). The tags collectively make a unique identifier for the table data.

Perhaps something can be done better/shorter/more easily readable?

import Data.List (isInfixOf)

type Label = Maybe String

data Variable = Variable
    { name :: Label,
      unit :: Label
    } deriving (Show, Eq)

makeVariable :: String -> String -> Variable
makeVariable name unit = Variable (Just name) (Just unit)

isDefined:: Variable -> Bool
isDefined var = (name var /= Nothing) && (unit var /= Nothing)

isIdentical:: Variable -> String -> String -> Bool
isIdentical var name unit = (makeVariable name unit) == var

-- Map allows a readable view of tuple-like
-- associative structure.
data Map = Map
    { label :: String,
      texts :: [String] -- note: can use non-empty List
    } deriving (Show)

nameMaps = [
      Map "GDP" ["Gross domestic product"]
    , Map "INDPRO" ["Industrial production"]
    ]

unitMaps = [
      Map "bln_rub" ["bln rub", "billion ruble"]
    , Map "rog" ["% change to previous period"] -- rate of growth
    ]

-- COMMENT: code below converts nameMaps and unitMaps
--          to list of tuples which are used for searching a header
asTuples :: Map -> [(String, String)]
asTuples (Map label texts) = [(text, label) | text <- texts]

findAllKeys :: [(String, String)] -> String -> [String]
findAllKeys mapper header = [key | tup@(text, key) <- mapper,
                                text `isInfixOf` header]

getLabel :: [Map] -> String -> Label
getLabel maps' header = case findAllKeys (flatten' maps') header of
        [] -> Nothing
        (x:_) -> Just x
    where flatten' = concatMap asTuples

getName = getLabel nameMaps
getUnit = getLabel unitMaps
parseHeader text = Variable (getName text) (getUnit text)

x = parseHeader "Gross domestic product, bln rub"
flag = (isDefined x) && (isIdentical x "GDP" "bln_rub")
raise x = error ("Something wrong with: " ++ show x)

main = do
    if flag then putStrLn $ show x else
      raise x
    return ()


texts:
I am struggling with the basic concepts of SASS.

I have a page that has multiple section, all of them are sharing properties like width, font-size etc.

I would like to optimize my code and do one of the following:

1. Use an extendable silent class

%main-section{
    width: 100%;
    //... more styles
}

.about {
    // this is a main-section
    @extend %main-section;
}

2. mixin

@mixin main-section($text-color, $bg-color) {

  //some paramaters would provide a flexible module
  width: 100%;
  // etc.
}

3. just a simple class to apply in my HTML

.main-section{
    width: 100%;
    //... more styles
}

I don't know which one i should choose. Maybe there's even a better solution i didn't mention. What is your opinion?


texts: Ruby method that returns an age from a date of birth

texts:
I have a method on my user model to calculate the user's age and return a human readable string.  My user's can be between 1 month old and above so the returned string is different depending on if the person is "2 months old" or "1 year old" or "2 years and 3 months old".

I have reviewed a few SO posts to come to this solution.  Is there anything I am missing?  Leap years?

def age
    dob = self.date_of_birth

    # if a date of birth is not nil
    if dob != nil

      # get current date
      now = Date.current

      # has person had their birthday yet this year
      had_birthday = ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? true : false)

      # if yes then subtract this year from birthday year, if not then also subtract 1 to get how many full years old they are
      years = now.year - dob.year - (had_birthday ? 0 : 1)

      # get the calendar month difference from birthdya calendar month and today's calendar month.  if they have not had their birthdya yet then subtract the difference from 12
      months = had_birthday ? now.month - dob.month : 12 - (now.month - dob.month)

      # for under 1 year olds
      if years == 0
        return months > 1 ? months.to_s + " months old" : months.to_s + " month old"

      # for 1 year olds
      elsif years == 1
        return months > 1 ? years.to_s + " year and " + months.to_s + " months old" : years.to_s + " year and " + months.to_s + " month old"

      # for older than 1
      else
        return months > 1 ? years.to_s + " years and " + months.to_s + " months old" : years.to_s + " years and " + months.to_s + " month old"
      end

    # No date of birth saved so can not calculate age
    else
      return "No Date of Birth"
    end
  end


texts:
I am making a Ping Pong game using Html5 Canvas. I am concerned about the movement(_b) method. This method should move the computer paddle (up and down) vertically and follow the ball. Some sort of simple AI. Everything works like it should but there is a lot of repetition of if else blocks that might be handled differently. Like shorter code or at least a bit more elegant.
The _b in the movement(_b) is parameter  for the ball that will be passed as an argument.
The keyword this refers to the computer paddle
The code below might give you an idea of what I am talking about.
class Paddle {
    constructor(x, y, width, height, color) {
        this.x = x
        this.y = y
        this.width = width
        this.height = height
        this.color = color
    }
    // collision  logic here...
}

class Ball {
    constructor(x, y, x_velocity, y_velocity, radius, color) {
        this.x = x;
        this.y = y;
        this.velocity = {
            x: x_velocity,
            y: y_velocity
        }
        this.radius = radius;
        this.color = color;
        this.isBouncingAllowed = true;
    }
    // movement logic here...
}

 class ComputerPaddle extends Paddle {
    constructor(...args) {
        super(...args)
    }

    movement(_b) {
        let centerOfPaddle = this.y + this.height / 2;

        if (centerOfPaddle < _b.y - 80) {
            this.y += 4
        }
        else if (centerOfPaddle > _b.y + 80) {
            this.y -= 4
        }
        else if (centerOfPaddle < _b.y - 60) {
            this.y += 2
        }
        else if (centerOfPaddle > _b.y + 60) {
            this.y -= 2
        }
        else if (centerOfPaddle < _b.y - 40) {
            this.y += 1
        }
        else if (centerOfPaddle > _b.y + 40) {
            this.y -= 1
        }
        else if (centerOfPaddle < _b.y - 20) {
            this.y += 0.5
        }
        else if (centerOfPaddle > _b.y + 20) {
            this.y -= 0.5
        }
    }
    update(_ball_) {
        this.movement(_ball_)
        this.ballInteraction(_ball_)
        this.draw()
    }
}

let player = new PlayerPaddle(20, canvas.height / 2 - sizes.paddle.height / 2, sizes.paddle.width, sizes.paddle.height, 'red')
let computer = new ComputerPaddle(canvas.width - (20 + sizes.paddle.width), canvas.height / 2 - sizes.paddle.height / 2, sizes.paddle.width, sizes.paddle.height, 'cyan')
let ball = new Ball(250, 350, 5, 0, sizes.ball.radius, 'green')

function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    ball.update()
    player.update(ball)
    computer.update(ball)
}
animate();

Any suggestions will be much appreciated.
EDIT: I did add the Ball and Paddle constructors. The methods in the classes containing the movement and collision detection logic were not included because that code is over 100 lines long and probably not relevant for my question.


texts: Marking class with no abstract methods as an abstract

texts:
Consider an interface:

public interface IWindowOperations
{
    // Some operation methods.
}

Class definitions:

public abstract class BaseWindow<T> : IWindowOperations
{
    // partially implemented class.
}

public class TraditionalWindow<T> : BaseWindow<T>
{
    // Fully implemented class.
}

public class ModernWindow<T> : BaseWindow<T>
{
    // Fully implemented class.
}

(1) is already marked as an abstract so it cannot be instantiated. (2) and (3) are fully implemented though they should not be instantiated, rather they should be derived by other class specifying <T> so the application framework can register them.
e.g.

 public class SliderWindow<Win8> : ModernWindow<Win8>
 {
        // In general case this is just an empty class
        // unless special handling is needed.
 }

In this case is it right to mark (2) and (3) as an abstract? Those are just template defining some concrete functionality but also allows derived classes to override if required.


texts: SICP - exercise 2.27 - reversing elements of a list and sublists

texts:
From SICP

  Exercise 2.27: Modify your deep-reverse procedure of Exercise 2.18 to produce a deep-deep-reverse procedure that takes a list as argument and returns as its value the list with its elements deep-reversed and with all sublists deep-deep-reversed as well. For example,

(define x (list (list 1 2) (list 3 4)))

x
((1 2) (3 4))

(deep-reverse x)
((3 4) (1 2))

(deep-deep-reverse x)
((4 3) (2 1))

Please review my code.

(define (deep-deep-reverse lst)
    (cond ((null? lst) '())
        ((list? lst) (append (deep-deep-reverse (cdr lst)) (list (deep-deep-reverse (car lst)))))
    (else lst)))

I spent an hour doing this, and I am actually extremely surprise on how small this code is in the end. How can I improve this code? Perhaps make it faster?


texts:
I would like to know if there is any pre-existing implementation of my solution so I don't have to reinvent the wheel.

What I'm trying to create is an utility which allows me to create critical section around given object. Can you check my code if there are any errors in my implementation?

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

public class MultiCriticalSection {
    private final ConcurrentHashMap<Object, ExtendReentrantLock> locks = new ConcurrentHashMap<>();

    private final Object globalLock = new Object();

    /**
     * Run critical section guarded by given object. It is potentionally blocking code!
     */
    public <T> T doWithLock(final Object key, Callable<T> fce) throws Exception {
        ExtendReentrantLock lock = getLock(key);
        try {
            return fce.call();
        } finally {
            freeLock(key, lock);
        }
    }

    /**
     * Run critical section guarded by given object. It is potentionally blocking code!
     */
    public void doWithLock(final Object key, Runnable fce) {
        ExtendReentrantLock lock = getLock(key);
        try {
            fce.run();
        } finally {
            freeLock(key, lock);
        }
    }

    /**
     * Release the lock. If there are no threads waiting and the lock is marked for removal it will be removed.
     */
    private void freeLock(final Object key, final ExtendReentrantLock lock) {
        synchronized (globalLock) {
            if (!lock.hasQueuedThreads() && lock.remove) {
                locks.remove(key);
            }
            lock.remove = true;
            lock.unlock();
        }
    }

    /**
     * Acquire lock. If there are no locks for given object it is created.
     * If there is a lock for given object and it is locked the removal flag is cleared. This way the currently running thread will not
     * remove the lock from memory.
     */
    private ExtendReentrantLock getLock(final Object key) {
        ExtendReentrantLock lock;
        synchronized (globalLock) {
            lock = locks.computeIfAbsent(key, o -> new ExtendReentrantLock());
            if (lock.isLocked()) {
                lock.remove = false;
            }
        }
        lock.lock();
        return lock;
    }

    /**
     * Utility class adding a flag to ReentrantLock.
     */
    private class ExtendReentrantLock extends ReentrantLock {
        boolean remove = true;
    }

}

The goal is not to allow 2 concurrent threads to operate on the same data. That is, only one object can operate on given object at same time. The other thread will be blocked, until the working thread is finished. The locks are automatically cleared when there are no threads running.


texts: Minimalistic, self-contained class for reading a sectionless INI file

texts:
When sections are ignored and no writing capability is needed, an INI reader becomes quite simple to implement. Here is my attempt at reading a sectionless INI file without any non-std dependencies.

The general idea is to store all key-value pairs in a <string, string> map, and use getters to convert the value string to desired type on demand.

#include <fstream>
#include <iostream>
#include <map>
#include <string>

class SectionlessINIReader {

private:
    std::map<std::string, std::string> dict;

public:

    // https://stackoverflow.com/a/1798170/3516684
    static std::string trim(const std::string& str,
                 const std::string& whitespace = " \t")
    {
        const auto strBegin = str.find_first_not_of(whitespace);
        if (strBegin == std::string::npos)
            return ""; // no content

        const auto strEnd = str.find_last_not_of(whitespace);
        const auto strRange = strEnd - strBegin + 1;

        return str.substr(strBegin, strRange);
    }

    SectionlessINIReader(const std::string& filename) {

        std::ifstream file(filename);
        std::string line;
        int idxEq;
        while (std::getline(file, line))
        {

            if ((line.find_first_not_of(";#")==0) &&
                ((idxEq = line.find("=")) != std::string::npos)) {

                    std::string key = trim(line.substr(0,idxEq));
                    std::string value = trim(line.substr(idxEq+1));

                    dict[key] = value;
                }
        }
        file.close();
    }

    std::string get(std::string key) {
        return dict[key];
    }

    bool getLong(std::string key, long* p_value) {

        std::string value = dict[key];

        if (value=="") {
            return false;

        } else {
            *p_value = std::stol(dict[key]);
            return true;
        }
    }

    // bool getDouble(...)

};

The intended usage is:

SectionlessINIReader ini("config.ini");
long age;
if (ini.getLong("age", &age))
    std::cout << "Name: " << ini.get("name") << "; age: " << age << std::endl;


texts:
I have made a custom webview which is used to open a very heavy site in terms of database. The webview uses custom code for uploading files using an upload handler class. I need suggestions on how I can optimize my code for better performance.

Features necessary (current custom webview written below does it all):

The basic functionality is just to load a responsive WordPress website.
Webview should support image uploading features.
mailto: links should open in the default email client.

I am adding the complete main activity page for your reference.

package com.Example.application;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;

import android.annotation.SuppressLint;

public class MainActivity extends Activity  implements OnClickListener {

      final Context context = this;
    private WebView webView;
     private ImageButton btnrefresh;
     private TextView txtrefresh;
     private Menu optionsMenu;
     private WebChromeClient.CustomViewCallback customViewCallback;
        private View mCustomView;

    @SuppressWarnings("deprecation")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //define button
        btnrefresh = (ImageButton) findViewById(R.id.imageButton1);

        btnrefresh.setOnClickListener(this);
        btnrefresh.setVisibility(View.GONE);

        //define textView
        txtrefresh = (TextView)findViewById((R.id.textView1));
        txtrefresh.setVisibility(View.GONE);

        if(isConnected())
        {

            webView = (WebView) findViewById(R.id.webView1);
            webView.getSettings().setJavaScriptEnabled(true);
               webView.getSettings().setAppCacheEnabled(true);

                webView.getSettings().setRenderPriority(RenderPriority.HIGH);
                webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
                webView.getSettings().setSaveFormData(true);
        //  webView.getSettings().setPluginState(PluginState.ON);
          webView.setWebViewClient(new WebViewClient()
          {
          @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {

              if (url.startsWith("mailto:")) {
                  sendEmail(url.substring(7));
                  return true;
              }

              return false;
          }

        });

            initWebView(webView);
            webView.loadUrl("http://Example.com/");

            }

        else
        {


texts:
I was just wondering if this is a good example, following good practices, of a C program for launching an interpreted script from a native binary executable. Here the interpreter is Perl and the script an implementation of something analogous to du --apparent-size, but the idea is general.

Also, is this code secure against potentially hostile users, at least if Perl is the interpreter (for instance, in a suid or sgid program)?

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc, char** argv)
{
  char* command[argc+3];
  command[0] = "/usr/bin/perl";
  command[1] = "-W";
  command[2] = "-T";
  command[3] = "/home/demetri/bin/awklikeperl.pl";
  for (int i = 0; i < argc; i++) {
    command[i+4] = argv[i+1];
  }
  execv(command[0], command);
  int error = errno;
  fprintf(stderr, "Failed to exec: %s\n", strerror(error));
  if (error == ENOENT) {
    return(127);
  } else {
    return(126);
  }
}


texts: Save multiple group permissions in one go

texts:
The method SaveGroupStepPermissions(...) is a database API class.
If an error occurs within the method the exception is trapped. Whether this is good design or not is not the scope of this question as I need to adhere to product guidelines.

I feel that this method is to complex and too lenghty. The obvious solution is to break out code into new functions, but I'm not sure how to do that in a way that is logical.

Important! If an error occurs the method should stop processing and return. That means both foreach loops must be exited.

Note: Input validation is performed in InsertGroupStepPermission() and UpdateGroupStepPermission().

Feel free to suggest improvements to code and comments beside the main question!

public static List<EventItem> SaveGroupStepPermissions(string connectionString, int companyID, List<Group> groups, List<GroupStepPermissions> gsp)
{
    var result = new List<EventItem>();
    result.Add(new EventItem("Insert Step permissions"));
    result.Add(new EventItem("Update Step permissions"));
    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlTransaction tran = conn.BeginTransaction("ProductName.GSP.cid" + companyID.ToString()))
            {
                foreach (Group group in groups)
                {
                    foreach (GroupStepPermissions stepPermission in gsp)
                    {
                        if (stepPermission.RowID == 0) //new permission that does not exist in the database. (INSERT)
                        {
                            try
                            {
                                InsertGroupStepPermission(conn, tran, stepPermission, companyID, group.ID);
                                result[0].SubEvents.Add(new EventSubItem("Added rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'", StatusEnum.OK, "Insert OK", stepPermission));
                            }
                            catch (Exception x)
                            {
                                result[0].SubEvents.Add(new EventSubItem("Failed to add rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'", StatusEnum.Failed, x.Message, stepPermission));
                                throw;
                            }
                        }
                        else //Existing stepPermission. (UPDATE)
                        {
                            try
                            {
                                UpdateGroupStepPermission(conn, tran, stepPermission, companyID, group.ID);
                                result[1].SubEvents.Add(new EventSubItem("Updated rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'", StatusEnum.OK, "Update OK", stepPermission));
                            }
                            catch (Exception x)
                            {
                                result[1].SubEvents.Add(new EventSubItem("Failed to update rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'", StatusEnum.Failed, x.Message, stepPermission));
                                throw;
                            }
                        }
                    }
                } //End outer for
                tran.Commit(); //important :)
            }
        }
    }
    catch(Exception x)
    {
        var eItem = new EventItem("Failed to save step permissions");
        eItem.SubEvents.Add(new EventSubItem("Error: " + x.Message));
        result.Add(eItem);
    }
    return result;
}


texts:
https://www.codewars.com/kata/best-travel

Briefly, the problem states that we have to create a function choose_best_sum(int t, int k,std::vector<int> xs) that will take as parameters t (maximum sum of elements, integer >= 0), k (number of elements to be chosen from the vector, k >= 1) and ls (list of positive elements to choose k elements from). The function returns the "best" sum i.e. the biggest possible sum of k elements less than or equal to the given limit t, if that sum exists, or otherwise -1.

For Example:

If ls = [50, 55, 57, 58, 60], t = 174 and k = 3,

Then all the possible choices of k(3) elements in ls are:

[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]

The corresponding sums are then: 162, 163, 165, 165, 167, 168, 170, 172, 173, 175.

Out of which, 173 is the largest sum less than t(174),so the function chooseBestSum(int t, int k, std::vector<int>& ls) returns 173.

From what I understand of the problem, one must basically enumerate and the compare all the possible combinations of k elements from the vector. My solution works, but times out, so it isn't accepted. I've basically tried to create a sliding window that slides through the vector and adds the elements inside the window to i-th and j-th elements and then adds them all to a local sum variable to be compared to the best sum. I know that four for-loops are a performance nightmare for a problem like this. What can I do to optimize it? Or is their an obvious other strategy that I'm missing?

class BestTravel
{
public:
    static int chooseBestSum(int t, int k, std::vector<int>& ls);
};

int BestTravel::chooseBestSum(int t, int k, std::vector<int>& ls){
    int best_sum = 0;
    for(int i =0;i<=ls.size()-k;i++){ //selects the first element for each combination
        for(int s=i+1;s<ls.size()-(k-2);s++){ //creates a sliding window(?) for k-2 elements
        int l_sum = ls[i];
          for(int x = s;x<s+(k-2);x++){ // iterates through the window and adds the elements to the local sum (l_sum)
          l_sum+=ls[x];
          }
          for(int j = ls.size()-1;j>=s+(k-2);j--){//adds the remaining elements from the end to the local sum
           l_sum+=ls[j];
           if(l_sum<=t&&l_sum>best_sum){best_sum = l_sum;}
           l_sum-=ls[j];
          }
        }
    }
    return best_sum;
}

```


texts:
An object (POJO) holds query arguments and has two-binding to a form using some MVC framework. later the object needs to be converted to a query string that will be appended to an HTTP request.

function objectToQueryString(obj) {
        return Object.keys(obj)
            .filter(key => obj[key] !== '' && obj[key] !== null)
            .map((key, index) => {
            var startWith = index === 0 ? '?' : '&';
            return startWith + key + '=' + obj[key]
        }).join('');
    }

Any pitfalls?  IE9+ is what we support.

Example input:

{isExpensive:true, maxDistance:1000,ownerName:'Cindy',comment:''}

And its expected output:

?isExpensive=true&maxDistance=1000&ownerName=cindy


texts: 3-Digit Narcissistic Numbers Program - Python

texts:
Just wanted to share my Narcissistic Numbers Program with y'all (not sure if it's good, but I gave it my best). Hope you like it!
This program prints out all the narcissistic numbers from the smallest number and biggest number's range. Ex. in the 1-100 range, only the narcissistic numbers will show on the console.
Some of you may be wondering, "What the hell are narcissistic numbers??" Once you go through a number of examples, I'm sure they won't be as bad as they sound (no pun intended). Narcissistic numbers are also known as Armstrong numbers, though I'm going to use the term 'narcissistic' rather than 'Armstrong' to avoid being inconsistent and flipping back and forth.
Overview: Narcissistic numbers are numbers that are equivalent to the sum of the cubes of their digits (3-digit numbers). This definition's verbose structure confused me, but after looking through a couple of examples, it made much more sense.

Procedure: (this is only applicable to 3-Digit Numbers)

Pick a number: 153

FYI: I broke the definition down into my own steps.

I split the number up into its individual digits; 1, 5 and 3
or you can just identify which digits the number (153 in this case) is composed of; 1, 5 and 3

Both ways bear the same result, but I tend to over-complicate things, so you can choose which way to use.

Now that all the digits are split up, we need to cube them all (separately) like this:
[1⋅1⋅1] + [5⋅5⋅5] + [3⋅3⋅3]; I included the square brackets for clarity's sake.

If you're not using brackets, then make sure you're following the BEDMAS rules.
If you simply calculate the following in a calculator: 1⋅1⋅1 + 5⋅5⋅5 + 3⋅3⋅3, then the result you will get is: 1025.

I believe I have provided a thorough enough over-view as to what narcissistic numbers are. Now, I hope the code will be easier for many people to understand.
The code is as follows:
import time
initial_time = time.time()

# initializing 's_number' (the smallest number) and 'l_num' (the largest number)
s_number = 100
l_number = 500

for number in range(s_number, l_number + 1):

    # order of the numbers
    order = len(str(number))

    # initializing sum
    sum = 0

    var = number
    while var > 0:
        digit = var % 10
        sum += digit ** order
        var //= 10

    # setting restrictions for program
    if number == sum:
        print(number)

total_time = time.time() - initial_time
print('Time to complete task:',total_time)

If there's anything to change/add to make the program more efficient/better please don't hesitate to let me know. I would appreciate your insight on this project.


texts: MVC API controller processing POST request

texts:
Do I need to restructure for readability?

 public HttpResponseMessage Post([FromBody]BoatProperties props)
    {
        // model validation
        if(ModelState.IsValid)
        {
            // check if guid is set, else set it; don't set when user is admin
            if(props.Guid == null && !User.IsInRole("Admin"))
            {
                props.Guid = Membership.GetUser().ProviderUserKey as Guid?;
            }

            Boat boat = BoatProvider.GetBoat(props.Guid);

            try
            {
                // can't find existing boat: create new boat
                if (boat == null)
                {
                    boat = new Boat(props);
                    BoatProvider.AddNew(boat);
                }
                // otherwise update existing boat
                else
                {
                    BoatProvider.Update(boat);
                }
            }
            catch(Exception ex)
            {
                // error while updating/adding model
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            // everything ok!
            return Request.CreateResponse(HttpStatusCode.OK, BoatProvider.GetBoat(props.Guid));
        }
        // validation failed
        return CreateResponse(HttpStatusCode.BadGateway);
    }

As you can see I'm exiting all those conditions with a return statement. If I restructure my code like this:

if(!ModelState.IsValid)
{
    return CreateResponse(HttpStatusCode.BadGateway);
}
if (props.Guid == null  && !User.IsInRole("Admin"))
{
    props.Guid = guid;
}

I will have less indentations and it may be more readable and all the steps seem more distanced from each other.


texts: Convert seconds to hours/minutes/seconds and pretty print

texts:
I'm self taught in python 3, and I frequently keep track of how long my scripts have been running using the time library.

import time
startTime = time.time()

#The main body of script...

print('The script finished in {0} seconds'.format(time.time() - startTime)

However this can be unhelpful if the script has been running for some time, an example output being:

'The script has been running for 4323.580279111862 seconds'

I wrote a function which takes a float variable and prints the time in a more readable way. I convert the seconds to integer to get rid of the 12 decimal places, and I can pass a boolean value which changes the wording of the print to indicate that the script is still running or has finished.

def printRuntime(seconds,finished=False):
    seconds = int(seconds)
    status = 'has been running for'
    if finished == True:
        status = 'finished in'

    if seconds < 60:
        print('The script {} {} seconds'.format(status,seconds))
        return
    elif seconds < 3600:
        minutes = seconds // 60
        seconds = seconds - 60*minutes
        print('The script {} {} minutes & {} seconds'.format(status,minutes,seconds))
        return
    else:
        hours = seconds // 3600
        minutes = (seconds - 3600*hours) // 60
        seconds = seconds - 3600*hours - 60*minutes
        print('The script {} {} hours, {} minutes & {} seconds'.format(status,hours,minutes,seconds))
        return

import time
startTime = time.time()

#The main body of script...

printRuntime(time.time() - startTime)

Since I'm self taught I have no real idea about best practice. I feel like there must be a more concise way of doing this, what mistakes am I making?


texts:
I want to determine whether or not the selected element exists in the list. This is the current procedure that I'm using for finding the element exist in a list or array. Is there any fast procedure for finding an element with any of these?

int[] array = { 1,2,9,3,5,6,7,8,10};

boolean isFound = false;
for(int i =0; i< array.length;i++) {
    if(array[i] == 4 || array[i] == 9) {
      isFound = true;
      break;
    }
}
System.out.println(isFound);


texts: Cross product to find Lorentz force in C++

texts:
User enters velocity vector \$v\$, charge \$q\$ of particle and magnetic field vector \$B\$ and the code prints the Lorentz force \$F = q * (v * B)\$

#include <iostream>

using namespace std;

int main()
{
    double v[3];
    double B[3];
    double q;
    int i;
    double F = (0.0, 0.0, 0.0);
    double i_X, j_X, k_X;
    cout << "Enter in components of velocity vector v:\n";

    for(i=0; i<3; i++)
    {
        cout << "Component " << i+1 << ": ";
        cin >> v[i];
    }

    cout << "Enter in charge of particle q: ";
    cin >> q;

    cout << "Enter in components of magnetic field vector B:\n";

    for(i=0; i<3; i++)
    {
        cout << "Component " << i+1 << ": ";
        cin >> B[i];
    }

    i_X= (v[1]*B[2])-(v[2]*B[1]);
    j_X= (v[2]*B[0])-(v[0]*B[2]);
    k_X= (v[0]*B[1])-(v[1]*B[0]);

    cout << endl;
    cout << endl;

        cout << "F =  "<< q* i_X << "i" << " + " << q* j_X << "j" << " + " << q* k_X << "k" << endl;

     return 0;
}

is this the correct way to do this or is there a more succinct way?


texts:
I designed this object for a "bread formula". They use a concept known as baker's percentages, but you don't need to understand the math to help with the object design.

I designed it as an object (of type Formula) that contains objects (of type Ingredient).

Both classes have nullable properties. C# demarcates nullable types using a ? after the type, like so:

public decimal? Weight { get; set; }

The reason I declare them as nullable types is because I don't know their values (when I create an instance of them) until I calculate them later, as which point I update the null value with a calculated value.

The calculations are just basic methods, like CalculateSum() or CalculateWeight().

Is there a better way to design this object? It works, but I feel like it's the wrong way to do things. I feel like I'm trying to force-fit inline/declarative style programming into an OOP design, but I don't know how else to do it, being so new to OOP.

My thinking is that this object has this property. I won't know its value when I create an instance of it, so I must declare it as nullable. Once I calculate its value using a method that's also internal to the class, I assign/set its value. Then it will no longer be null.

The calculation methods are basic calculations:

public type Method(input,input,...){calc; return calc;}.

 class Ingredient
    {
        public string Name { get; set; }
        public decimal Percentage { get; set; }
        public bool IsFlour { get; set; }
        public decimal? Weight { get; set; }

        public Ingredient(string _Name, decimal _Percent, bool _IsFlour, decimal? _Weight)
        {
            this.Name = _Name;
            this.Percentage = _Percent;
            this.IsFlour = _IsFlour;
            this.Weight = _Weight;
        }
    }

    class Formula
    {
        public decimal Weight_Total_Dough { get; set; }
        public ArrayList Ingredients { get; set; }
        public int NumberOfIngredients { get; set; }
        public decimal? SumPercentages { get; set; }
        public decimal? SumWeights { get; set; }
        public decimal? SumWeightTotalFlour { get; set; }

        public Formula(decimal _Weight_Total_Dough, ArrayList _Ingredients, int _NumberOfIngredients, decimal? _SumPercentages, decimal? _SumWeights, decimal? _SumWeightTotalFlour)
        {
            this.Weight_Total_Dough = _Weight_Total_Dough;
            this.Ingredients = _Ingredients;
            this.NumberOfIngredients = _NumberOfIngredients;
            this.SumPercentages = _SumPercentages;
            this.SumWeights = _SumWeights;
        }
    }

Here's the code for calculating Formula.SumPercentages, which was declared as nullable, but is now assigned a value:

public void SumPercentages(Formula f)
        {
            //Interate through Formula object, which contains an ArrayList of INGREDIENT objects.
            //Extract the precentages for each ingredient.
            //Add them up.
            //Return the summation as SumOfPercentages.

            decimal SumOfPercentages;
            SumOfPercentages = 0;
            foreach (object x in f.Ingredients) //for each INGREDIENT object in the FORMULA object
            {
                Ingredient ig = (Ingredient)x; //get the INGREDIENT.Percentage
                SumOfPercentages += ig.Percentage; //add it to the other INGREDIENT.Percentages
            }

            f.SumPercentages = SumOfPercentages; //SumOfPercentages was null before, but now we assign a value (SumOfPercentages) to it.


texts: Project Euler Problem 11: Largest product in a grid

texts:
Here is my implementation to project Euler Problem 11. I did this problem a bit later, when I learned how to input from a txt file. The problem context can be seen here. I did add "\n" to the end of each line, after copying the numbers into a txt file, I'm not sure of any other way to do that. Any other improvements anyone can think of?

#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>
#include <string>

//splitting stream into ints.
std::vector<int> split(std::string line){
    std::stringstream ss (line);
    std::vector<int> result;
    std::string num;
    while(std::getline(ss, num, ' '))
        result.push_back(std::stoi(num));
    return result;
}
//comparing all int's that are horizontally next to each other
unsigned long long Horizontal(int a, int b, std::vector<std::vector<int>> grid){
    if(b < grid[a].size()-3){
        return (grid[a][b] * grid[a][b+1] * grid[a][b+2] * grid[a][b+3]);
    }
}
//comparing all int's that are vertically next to each other
unsigned long long Vertical(int a, int  b, std::vector<std::vector<int>> grid){
    if(a < grid.size()-3){
        return (grid[a][b] * grid[a+1][b] * grid[a+2][b] * grid[a+3][b]);
    }
}
//all int's that are diagonally(forward) next to each other
unsigned long long ForDiag(int a, int b, std::vector<std::vector<int>>grid){
    if (a < grid.size()-3 && b < grid[a].size()-3){
        return (grid[a][b] * grid[a+1][b+1] * grid[a+2][b+2] * grid[a+3][b+3]);
    }
}
//all int's that are diagonally(backward) next to each outher
unsigned long long BackDiag(int a, int b, std::vector<std::vector<int>>grid){
    b+=3; // b needs to be 3 larger for this function
    if(a < grid.size()-3 && b < grid[a].size()){
        return (grid[a][b] * grid[a+1][b-1] * grid[a+2][b-2] * grid[a+3][b-3]);
    }
}

//Calls the calculation functions, and compares them for the largest.
unsigned long long Largest(std::vector<std::vector<int>> grid ){
    int gwidth = grid[0].size();
    int glength = grid.size();
    unsigned long long largest = 0;

    for(int a = 0; a < gwidth; ++a){
        for(int b = 0; b < glength; ++b){
            largest = std::max(largest,Horizontal(a,b,grid));
            largest = std::max(largest,Vertical(a,b,grid));
            largest = std::max(largest,ForDiag(a,b,grid));
            largest = std::max(largest,BackDiag(a,b,grid));

        }
    }
    return largest;
}

int main(){
    std::vector<std::vector<int>> grid;

    //opening file.
    std::ifstream nums;
    nums.open("grid.txt");
    std::string row;

    //Calling function, and pushing back into the vector
    while(std::getline(nums, row, '\n')){
        grid.push_back(split(row));
    }

    std::cout << Largest(grid);

}


texts: Can my string to instance construction be improved?

texts:
I have a Dictionary<string, object> (named tableDict) that has been parsed from JSON. The string describes the intended construction of a class T which is defined within the housing class of this code. The object is the numerical probability value that pairs up with the generated reference of T.

The string can be in either of two formats. Something encased in brackets, i.e. "(arg0, arg1, arg2, ...)", will call the constructor with these arguments. Anything else is assumed to be a name of a property of type T that returns a predefined T, i.e when T is of type Color, "Black" would lead to looking for Color.Black.

I managed to get something to work however I pieced this together from googling each problem I encountered. A lot of what I have used is new to me, it's highly likely I have gone about it in an inefficient roundabout fashion.

for (int i = 0; i < tableDict.Count; i++)
{
    KeyValuePair<string, object> kvp = tableDict.ElementAt(i);
    string s = kvp.Key;

    if (Regex.IsMatch(s, @"\(([^\)]+)\)", RegexOptions.None))
    // Key is "( something )" - entry is constructor
    {
        string sCon = s.WhitespaceRemoved();
        sCon = sCon.Substring(1, sCon.Length - 2); // Remove brackets

        string[] argsAsStrings = sCon.Split(',');
        object[] args = argsAsStrings.Select(num => (object)int.Parse(num)).ToArray();
        // I have only implemented this for the Color class.
        // I assume the constructor is comprised of ints.

        T item = (T)Activator.CreateInstance(typeof(T), args);
        double prob = Convert.ToDouble(kvp.Value);

        var entry = new RawChanceTableEntry<T>(item, prob);

        list.Add(entry);
    }
    else // Parse string as a property of T instead
    {
        string sProp = s;
        Type type = typeof(T);
        PropertyInfo propInfo = type.GetProperty(sProp);

        object obj = Activator.CreateInstance(type);

        T item = (T)propInfo.GetValue(obj, null);
        double prob = Convert.ToDouble(kvp.Value);

        var entry = new RawChanceTableEntry<T>(item, prob);

        list.Add(entry);
    }
}

Note the struct RawChanceTableEntry is just a container for the item / probability pair.

Code in class: http://pastebin.com/bvJaS8Se (class is incomplete)

Parsed JSON: http://pastebin.com/HS6eSABQ


texts:
This is the updated code using all suggestions from the previous question that I made here.

I have revised the naming of the variables, and i have included the classes that this part of code is using, in order to have a better understanding.

  I'm making a game battle system, where there are 2 players.

  It is like a round based game.

  Every player can have multiple units to control, but can only use one of them each round..
  Every unit has an int CurrentSpeed variable;

  I need to have in 2 variables who attacks first (Player firstPlayer)
  and who attacks second (Player secondPlayer), based on the speed of
  the active Unit.

At the moment I have this code:

public class Player {
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Unit> Party { get; set; }
    public Unit Active { get; set; }
}

public class Unit {
    public string Name;
    public int InitialSpeed { get; set; }
    public int CurrentSpeed { get; set; }
}

public class BattleSystem {

    private void BattleTurn(){
        Player firstPlayer = null; //Player attacking first
        Player secondPlayer = null; //Player attacking second

        //Check the speed of the units, and determine who attack first
        firstPlayer = player_1.Active.CurrentSpeed > player_2.Active.CurrentSpeed ? player_1 : player_1.Active.CurrentSpeed < player_2.Active.CurrentSpeed ? player_2 : null;

        //if firstPlayer is null (active units have the same CurrentSpeed)
        if(firstPlayer == null){
            //Randomize who goes first
            System.Random rnd = new System.Random();
            int rng = rnd.Next(2);
            firstPlayer = rng == 0 ? player_1 : player_2;
            secondPlayer = rng == 0 ? player_2 : player_1;
        }else{
            secondPlayer = firstPlayer.Id == player_1.Id ? player_2 : player_1;
        }
    }
}

The part of determine the firstPlayer is ok, but I don't like the checks and assignments of the secondPlayer, like checking the ids.

I need tips on how I can code this in a better way.


texts: Basic iterator supporting vector implementation

texts:
On the fly, I just implemented this iterator supporting vector class to understand how range-based for loop works.
It's really basic but let me know what can be improved.

Vector.h

#ifndef VECTOR_H
#define VECTOR_H

#include <stdexcept>

template <typename T>
class Vector
{
public:
    /* The iterator */
    class Iterator
    {
    public:
        Iterator(const Vector<T> *vector, int nIndex);
        const T &operator*() const;
        Iterator &operator++();
        bool operator!=(const Iterator &other) const;

    private:
        const Vector<T> *m_pVector;
        int m_nIndex = -1;
    };

public:
    // constructors
    Vector() = default;
    explicit Vector(int nSize);

    ~Vector();

    void insert(const T &value);

    int size() const;
    const T &operator[](int nIndex) const;

    Iterator begin() const;
    Iterator end() const;

private:
    T *m_pData = nullptr;
    int m_nSize = 0;
    int m_nCapacity = 0;
};

/*
 * Vector methods
 **/
template <typename T>
Vector<T>::Vector(int nCapacity)
{
    m_nCapacity = nCapacity;
    m_pData = new T[m_nCapacity];
}

template <typename T>
Vector<T>::~Vector()
{
    delete m_pData;
    m_nSize = 0;
    m_nCapacity = 0;
}

template <typename T>
void Vector<T>::insert(const T &value)
{
    if (m_nSize == m_nCapacity)
    {
        if (m_nCapacity == 0)
            m_nCapacity = 1;

        m_nCapacity *= 2;

        // allocate 2x larger memory
        auto pNewMemory = new T[m_nCapacity];

        // copy data to there
        for (auto idx = 0; idx < m_nSize; ++idx)
            pNewMemory[idx] = m_pData[idx];

        delete m_pData;
        m_pData = pNewMemory;
    }

    // insert the new element
    m_pData[m_nSize] = value;
    ++m_nSize;
}

template <typename T>
int Vector<T>::size() const
{
    return m_nSize;
}

template <typename T>
const T &Vector<T>::operator[](int nIndex) const
{
    if (nIndex >= m_nSize)
        throw std::exception("Index out of range");

    return m_pData[nIndex];
}

template <typename T>
typename Vector<T>::Iterator Vector<T>::begin() const
{
    return Vector<T>::Iterator{ this, 0 };
}

template <typename T>
typename Vector<T>::Iterator Vector<T>::end() const
{
    return Vector<T>::Iterator{ this, m_nSize };
}

/*
 * Iterator methods
 **/
template <typename T>
Vector<T>::Iterator::Iterator(const Vector<T> *pVector, int nIndex)
    : m_pVector(pVector)
    , m_nIndex(nIndex)
{
}

template <typename T>
const T &Vector<T>::Iterator::operator*() const
{
    return m_pVector->operator[](m_nIndex);
}

template <typename T>
typename Vector<T>::Iterator &Vector<T>::Iterator::operator++()
{
    ++m_nIndex;
    return *this;
}

template <typename T>
bool Vector<T>::Iterator::operator!=(const Vector<T>::Iterator &other) const
{
    return m_nIndex != other.m_nIndex;
}

#endif // !VECTOR_H

main.cpp

#include <iostream>

#include "Vector.h"

int main()
{
    try
    {
        Vector<int> vector;
        vector.insert(8);
        vector.insert(3);
        vector.insert(1);
        vector.insert(7);
        vector.insert(2);

        for (auto i : vector)
            std::cout << i << std::endl;
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }

    std::cin.get();
    return 0;
}


texts: Using Biopython, I would like to optimize this code

texts:
I have the following code:

from Bio import AlignIO
import itertools

out=open("test.csv","a")
align = AlignIO.read("HPV16_CG.aln.fas", "fasta")
n=0
def SNP(line):
    result=[]
    result.append(str(n+1))
    result.append(line[0])
    result.append(align[y].id.rsplit("|")[3])
    result.append(x)
    return result

while n<len(align[0]):
  line = align[:,n]
  y=0
  for x in line:
    if line[0]!=x:
      print >> out, ','.join(map(str,SNP(line)))
      y=y+1
    else:
      y=y+1
  y=0
  n=n+1
out.close()

f=open("test.csv","rU")

out=open("test_2.csv","a")
lines=f.read().split()

for key, group in itertools.groupby(lines, lambda line: line.partition(',')[0]):
    print >>out, ','.join(group)

out.close()
f.close()

As you can see, I am currently writing two files. I really only need the second file.
Does anyone have any suggestions to combine both "subscripts" into one?

The input file "HPV16_CG.aln.fas" looks like this:

>gi|333031|lcl|HPV16REF.1| Alpha-9 - Human Papillomavirus 16, complete genome.
ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG

>gi|333031|gb|K02718.1|PPH16 Human papillomavirus type 16 (HPV16), complete genome
ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG

>gi|196170262|gb|FJ006723.1| Human papillomavirus type 16, complete genome
ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG

I really appreciate all the help/suggestions to help me improve this!


texts: Object-oriented approach to sieve of Eratosthenes

texts:
I was trying to implement the sieve of Eratosthenes entirely by myself, using only what I have learned so far. Now I'm wondering what I can do to improve my code's readability. Optimizing the algorithm is not my goal for now.

#include <iostream>
#include <cmath>

using namespace std;

class num {
private:
    static unsigned obj_count; //simplifying initialization of the array, performance is not my main concern
    unsigned n;
    bool flagged;
public:
    num();
    void setn(unsigned);
    void setflagged(bool);
    bool isflagged();
    unsigned getn();
};

void Eratosthenes_sieve(num*, unsigned);

//Initialization of static member
unsigned num::obj_count = 0;

//Implementation of member functions
num::num() {
    flagged = false;
    ++obj_count; //simply declaring an array of class num will result in initialized values for n
    n = obj_count;
}

void num::setn(unsigned n) {
    this->n = n;
}

void num::setflagged(bool flagged) {
    this->flagged = flagged;
}

bool num::isflagged() {
    return flagged;
}

unsigned num::getn() {
    return n;
}

int main()
{
    unsigned n = 100;
    num arr[n];

    Eratosthenes_sieve(arr, n);

    return 0;
}

void Eratosthenes_sieve(num *arr, unsigned n) {
    unsigned i;

    for (i = 1; i < sqrt(n); ++i) { //minor optimization, as there will be no multiples or sqrt(arr[i]) that are lower than n
        if ( !(arr[i].isflagged()) ) { //if the number is not flagged, proceed to flag it
            for (unsigned j = 1; j < ( n / (arr[i].getn()) ); ++j) {
                arr[i + j * arr[i].getn()].setflagged(true); //flags every arr[i]-th number in the array.
            }
        }
    }

    cout << "Prime numbers up to " << n << ": \n";
    for (i = 1; i < n; ++i) {
        if ( !(arr[i].isflagged()) ) {
            cout << arr[i].getn() << " ";
        }
    }
}


texts: Structuring code logic for events on laravel controller

texts:
The code below will store a base64 image on another website and create an event to display the image on a Vue page in real time. It works fine and all.
My question is, is this a good way of doing it or there's a better way to structure the code? I've thought about placing the logic in a listener but it doesn't seem that I need to use one. For queues, I'll add them later on.
Controller
public function store(Request $request)
{
    $base64 = $request->image;
    $image = str_replace('data:image/png;base64,', '', $base64);
    $imageName = 'draw'.time().'.png';
    $response = $this->guzzleClient()->post(config('archiving.api_postBase64_file'),
        [
            'multipart' => [
                [
                    'name' => 'file',
                    'contents' => $image
                ],
                [
                    'name' => 'file_name',
                    'contents' => $imageName
                ],
                [
                    'name' => 'file_folder',
                    'contents' => 'drawings'
                ],
            ],
        ]
    );
    if($response->getStatusCode() >= 500){
        return response($response->getBody(), $response->getStatusCode());
    }else{
        $drawing = Drawing::create([
            'user_id'=>Auth::id(),
            'file_name'=>$imageName,
        ]);
        event(new NewDrawing($drawing));
        return response('Drawing created!',200);
    }
}

NewDrawing Event
class NewDrawing implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $drawing;

    public function __construct(Drawing $drawing)
    {
        $this->drawing = $drawing;
    }
    public function broadcastOn()
    {
        return new Channel('channel-drawing');
    }
 }

Frontend (Vue)
<script>
export default {
    data(){
        return{
            images:'',
        }
    },
    methods:{
        listen() {
            Echo.channel('channel-drawing')
            .listen('NewDrawing', res => {
                this.images.push(res.drawing);
            })
        }
    },
    mounted() {
        this.listen()
    }
}
</script>


texts: A very basic web framework inspired by Flask

texts:
I was curious how hard it would be to implement a routing system like flask uses. As it turn's out it's actually not that hard if you understand how decorator's work.

The flask implementation has a lot of features like routes based on a regular expression. Mine just maps a path to a function.

#!/usr/bin/env python

from http.server import BaseHTTPRequestHandler, HTTPServer
import sys

DEFAULT_PORT = 8080
LOCALHOST = '127.0.0.1'
DEFAULT_ENCODING = 'utf-16'
ROUTES = None

class Routes(object):
    def __init__(self):
        self.routes = self.__dict__
        global ROUTES
        ROUTES = self

    def add(self, route, cb):
        self.routes[route] = cb()

    def get(self, route):
        return self.routes.get(route)

    def exists(self, route):
        return route in self.routes

    def __call__(self, route):
        return self.get(route)

class Route(object):
    def __init__(self, route):
        self.route = route

    def __call__(self, func):
        ROUTES.add(self.route, func)

class RequestHandler(BaseHTTPRequestHandler):
  Routes()
  def send_msg(self, msg, encoding=DEFAULT_ENCODING):
      self.wfile.write(bytes(msg, encoding))

  def do_GET(self):
      if not ROUTES.exists(self.path):
          self.send_header('content-type', 'text/html')
          self.send_response(404)
          self.end_headers()
          self.send_msg('
404
')
          return

      self.send_response(200)
      self.send_header('Content-type','text/html')
      self.end_headers()
      self.send_msg(ROUTES(self.path))
      return

def run(port=8080, server_addr=LOCALHOST):
  print('starting server...')
  server_address = (server_addr, port)
  httpd = HTTPServer(server_address, RequestHandler)
  print('running server...')
  httpd.serve_forever()

if __name__ == '__main__':
    @Route('/')
    def root():
        return '
It Works
'
    run()


texts: Insert k copies of each element in ArrayList

texts:
This method takes an ArrayList<String> s and int k , then creates k copies of each element.

public static void copyStrings(ArrayList<String> s, int k) {
        if (k <= 0) {
            s.clear();
        } else {
            int limit = s.size();
            for(int i = 0; i < limit; i++) {
                for( int j = 0; j < k; j++) {
                    s.add(s.get(i));
                }
            }
            for( int i = 0; i < limit; i++) {
                s.remove(0);
            }
    }
}


texts:
I have written a script that checks if data is known in memcached, and if not it queries it from the mysql db and stores it.

I would appreciate any inputs if i have done this the "correct" way, since i'm trying to optimize the code as much as possible.

  _query() & _rows() are simple mysqli functions

Save in memcache

// Store memcache data
function setCache($key,$value,$storage=18) {
    $memcache_obj = new Memcache;
    $memcache_obj = memcache_connect(memcache_host, 11211);

    if(is_array($key)) {
        $i = 0;
        foreach($key as $id => $storeName) {
            $memcache_obj->set($storeName, $value[$id], 0, $storage);
        }
    }else{
        $memcache_obj->set($key, $value, 0, $storage);
    }
}

Get from memcache

// Get memcache data
function getCache($key) {
    $memcache_obj = new Memcache;
    $memcache_obj = memcache_connect(memcache_host, 11211);
    $res = $memcache_obj->get($key);
    if(empty($res)) {
        $res = false;   // Expired
    }
    return $res;
}

Get data from memcache (or store in memcache if not present)

// Get data from either memcache or mysql
function _getData($userid,$table,$fields,$server) {

    $toSelect = explode(",",$fields);
    $toPush = array();
    foreach($toSelect AS &$value) {
        // Check if data is available from cache
        $key = $userid."_".$table."_".$value;
        $res[$value] = getCache($key);
        if(empty($res[$value])) {
            // Not cached, so must be pushed
            $toPush[] = $value;
        }
    }

    if($toPush) {
        // Some or all data missing from cache, so we fetch and cache it
        $fieldsToSelect = implode(",",$toPush);
        $q = _query("SELECT ".$fieldsToSelect." FROM ".$table." WHERE id = '".$userid."'",$server);
        $row = _rows($q);
        $key = array();
        $cValue = array();
        foreach($toPush AS &$value) {
            $key[] = $userid."_".$table."_".$value;
            $cValue[] = $row[$value];
            $res[$value] = $row[$value];
        }
        setCache($key,$cValue);
    }
    return $res;

}

The idea is to use the function as follows:

_getData($userid,"name_table","first_name,last_name",$dbConnection);

The above will return the data requested from memcahced first and if not present, then query it from mysql and store it in memcached.

The above works well, but how much does it hurt the eye?


texts:
I have a Tree class, defined as follows:

public class Tree<T> {
    private T value;
    protected List<Tree<T>> children = new ArrayList<Tree<T>>();
    /* ... */
}

I want to implement the toString() method in this class to show the String representation of this Tree, e.g.:

└── root
    ├── child1
    │   └── grandchild1
    └── child2

I implemented in this way:

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    buildString(sb, "", true);
    return sb.toString();
}

private void buildString(StringBuilder sb, String prefix, boolean isTail) {
    sb.append(isTail ? "└── " : "├── ").append(value).append(System.lineSeparator());
    prefix = prefix + (isTail ? "    " : "│   ");

    for (int i = 0; i < children.size() - 1; i++) {
        sb.append(prefix);
        children.get(i).buildString(sb, prefix, false);
    }
    if (children.size() >= 1) {
        sb.append(prefix);
        children.get(children.size() - 1).buildString(sb,prefix, true);
    }
}

I am looking for possible improvements or suggestions.


texts: Selecting countries with different situations

texts:
I'm trying to select two groups of countries with different situations.

SELECT cou.id,
       cou.title
FROM   continents con
       RIGHT OUTER JOIN countries cou
                     ON con.id = cou.continents_id
WHERE  con.deliver = 1
       AND con.active = 1
UNION ALL
SELECT cou2.id,
       cou2.title
FROM   countries cou2
       LEFT OUTER JOIN continents con2
                    ON con2.id = cou2.continents_id
WHERE  cou2.deliver = 1
       AND con2.deliver = 0

Continent has to be deliver = 1 and then select all countries inside it.
If Continent is deliver = 0 but there are countries with deliver = 1 inside, then select it.

What is the best way of doing this?


texts:
Implement an iterator (generic) which skips an element if it is equal to the previous element. e.g: AAABBCCCCD, produces ABCD.

Please suggest improvements.

import java.util.Iterator;

public class DeDupIterator implements Iterator {

E next = null;
Iterator<E> itr;

public DeDupIterator(Iterator<E> iter) {
    itr = iter;
    next = itr.next();
}

@Override
public boolean hasNext() {
    if(itr.hasNext())
    if (next != null) {
        return true;
    }
    return false;
}

@Override
public E next() {
    E item=null;
    while (itr.hasNext()) {
        item = (E) itr.next();
        if (!item.equals(next)) {
            E temp = next;
            next = item;
            return temp;
        }

    }
    next = item;
    return next;
}

@Override
public void remove() {
    itr.remove();
}
}


texts:
I would like to compare the min/max values of a time-series with a test time-series. Additionally, I would like to compare the time of the "peaks". However, I'm having trouble extracting these features from a Pandas DataFrame.

Given the following data:

def fake_phase_data():
    in_li = []
    sample_points = 24 * 4

    for day, bias in zip((11, 12, 13), (.5, .7, 1.)):
        day_time = datetime(2016, 6, day, 0, 0, 0)
        for x in range(int(sample_points)):

            in_li.append((day_time + timedelta(minutes=15*x),
                          bias * np.sin(2 * np.pi * x / sample_points + (1.2*bias)),
                          bias))

    fake_df = pd.DataFrame(in_li, columns=("time", "phase_sig", "bias")).set_index("time")
    return fake_df

fp = fake_phase_data()
# Convert to pivot-table with 24 hour columns
dfs = {
    col: pd.pivot_table(
        fp,
        index=fp.index.date,
        columns=fp.index.hour,
        values=col,
        aggfunc='mean',
    )
    for col in fp.columns
}
ddf = pd.concat(dfs, axis=1)

Which looks like:

for i in range(len(ddf)):
    ddf["phase_sig"].iloc[i].plot()

I process the data:

def col_peaks(df, cols, peak_func):
    return [list(getattr(df[col], peak_func)(axis=1).values) for col in cols]

def peak_vals(df, cols, t_peak):
    peak_v = []

    for c_i, col in enumerate(cols):
        vals = df[col].values
        peak_idx = t_peak[c_i]
        peak_v.append(list(vals[np.arange(len(peak_idx)), peak_idx]))

    return peak_v

# I may want to process multiple columns later
# but let's focus on the single-column case
x_cols = ["phase_sig"]

# Technically, I also want the minimum
# but let's focus on the maximum case first
orig_t_max = col_peaks(ddf, x_cols, "idxmax")
print("Orig t_max", orig_t_max)

orig_v_max = peak_vals(ddf, x_cols, orig_t_max)
print("Orig v_max", orig_v_max)

# actual test data will be a single row in a dataframe
# but this test is fine for now
test_df = ddf.iloc[[0]]
test_t_max = col_peaks(test_df, x_cols, "idxmax")
print("Test t_max", test_t_max)

test_v_max = peak_vals(test_df, x_cols, test_t_max)
print("Test v_max", test_v_max)

And get the result:

Orig t_max [[4, 3, 1]]
Orig v_max [[0.4985414229286749, 0.6989567830263389, 0.9940657122457474]]
Test t_max [[4]]
Test v_max [[0.4985414229286749]]

How do I get both of these values without the weird loops I'm doing? I know I could make them more compact by using a list-comprehension, but I'd rather get rid of them altogether. Is there a way to deal with both DataFrame and Series without the awkward if-statement I use in col_peaks and peak_vals?


texts:
I have to generate a lot of tables from different JSON files (up to 20 tables per page). Because it's a lot of data, I really want to keep loading speed in mind. I know it's better to use a non jQuery solution, but native is not in my skillset right now.

$(document).ready(function(){

  (function getPersonData(){
   $.getJSON('path/to/json', function(data){

  (function addPersonsTable1(personsData){

    var elementContainer = '';

    $.each(personsData.persons, function(key, person){
      elementContainer = elementContainer + '
' +
        '' + person.value1 + '	' +
        '' + person.value2 + '	' +
        '' + person.value3 + '	' +
        '' + person.value4 + '	' +
        '' + person.value5 + '	' +
      '
';
    });

    $('.persons-table-1').append(elementContainer);

  }(data));

  (function addPersonsTable2(personsData){

    var elementContainer = '';

    $.each(personsData.persons, function(key, person){
      elementContainer = elementContainer + '
' +
        '' + person.value1 + '	' +
        '' + person.value2 + '	' +
        '' + person.value3 + '	' +
        '' + person.value4 + '	' +
        '' + person.value5 + '	' +
      '
';
    });

    $('.persons-table-2').append(elementContainer);

  }(data));

  /*
  *
  *
  *
  *
  *  <..... And many more tables
  *
  *
  *
  *
  */

 }).done(function(){
  loadedAnimation();
});

});


texts: Evaluating algebra expression using an auxiliary VB class compiled on the fly and consumed in a C# project

texts:
I want to create algebra evaluator but I don't want to write my own parser because it takes much time to learn.
I don't like algebra expression in C# because it does not look natural compared to VB counterpart. For example, "x^2+1" in VB must be written as "Math.Pow(x,2)+1" in C#.
I am still a newbie in the world of programming and always interested to learn the best practices. I am always not confident with my code.

Minimal Working Example

Based on the 3  constraint given above, I tried to implement it as follows.

First, I create a template named template.vb as follows:

Imports System
Imports System.Math
Namespace AnyNamespace
    Public Class AnyClass
        Public Function AnyMethod(ByVal x As Double) As Double
            Return expression-in-x
        End Function
    End Class
End Namespace

where expression-in-x is just a place holder that will be replaced. See the next code how I replace it.

Second, I create a class named Parser.cs as follows:

using Microsoft.VisualBasic;
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Text;

namespace Mathematics
{
    public static class Parser
    {
        static string expression;
        static object obj;
        static MethodInfo mi;

        public static string Expression
        {
            get
            {
                return expression;
            }
            set
            {
                expression = value;

                string source;

                using (StreamReader sr = new StreamReader("template.vb"))
                {
                    source = sr.ReadToEnd().Replace("expression-in-x", expression);
                }

                CompilerParameters cps = new CompilerParameters();
                cps.GenerateExecutable = false;
                cps.GenerateInMemory = true;

                CompilerResults crs = (new VBCodeProvider()).CompileAssemblyFromSource(cps, source);

                if (crs.Errors.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CompilerError ce in crs.Errors)
                    {
                        sb.Append(string.Format("Error Number : {0}, Line : {1}, Message : {2}.\n", ce.ErrorNumber, ce.Line, ce.ErrorText));
                    }
                    throw new Exception(sb.ToString());
                }
                else
                {
                    Assembly a = crs.CompiledAssembly;
                    obj = a.CreateInstance("AnyNamespace.AnyClass");
                    mi = obj.GetType().GetMethod("AnyMethod");
                }
            }
        }

        public static double Evaluate(double x)
        {
            if (expression == null)
                throw new Exception("Unitialized expression.");
            try
            {
                return (double)mi.Invoke(obj, new object[] { x });
            }
            catch (TargetInvocationException error)
            {
                throw error;
            }
            catch (Exception error)
            {
                throw error;
            }
        }
    }
}

Last, I test the code as follows:

using Mathematics;
using System;

namespace Tester
{
    class Program
    {
        static void Main(string[] args)
        {
            Parser.Expression = "x^2+1";
            for (int x = 0; x < 10; x++)
                Console.WriteLine(Parser.Evaluate(x));
            Console.ReadKey();
        }
    }
}

Questions

Is what I did above recommended? If not, could you give me a direction or suggestion what should I improve it or whatever to make it much better?


texts: Sum of all possible concatenations of array values

texts:
Given an array of non-negative integers, we need to find the sum of concatenation of elements in the array.

For example -
given [11, 22] the result should be - 6666
i.e.,
11 + 11 = 1111
11 + 22 = 1122
22 + 11 = 2211
22 + 22 = 2222

Sum of all those numbers would result in 6666

My code is as below -

function concatenationsSum(a) {
  var sum = 0;
  for (var i = 0; i < a.length; i++)
    for (var j = 0; j < a.length; j++)
        sum += Number("" + a[i] + a[j]);
  return sum;
}

Problems like these require brute force since we need to sum each and every combination. This works sure fine for smaller inputs. But if the array is longer, say, 1 ≤ lengthOfArray ≤ 25, how can I handle such large inputs faster? Any suggestions would be appreciated.