texts: Wrapping a node.js module using elasticsearch

texts:
I need to use elasticsearch in my node.js project, whose API looks like the following:

var elasticsearch = require('elasticsearch');
return new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'trace'
}));

However, my elasticsearch host is stored in zookeeper, so I first need to fetch it before returning the client. This is what I've come up with so far, which seems to work:

var elasticsearch = require('elasticsearch');
var zookeeper = require('node-zookeeper-client');

var zookeeperClient = zookeeper.createClient('localhost:2181');
zookeeperClient.connect();

var exportedClient = new Promise((resolve, reject) => {
  zookeeperClient.once('connected', () => {
    zookeeperClient.getChildren('/databases/elasticsearch', function (error, children, stats) {
      if (error) {
        console.log(error.stack);
        reject(error);;
      }
      resolve(elasticsearch.Client({
        host: children[0],
        log: 'trace'
      }));
    });
  });
});

exportedClient.get = function(args) {
  return exportedClient.then((client) => {
    return client.get(args);
  });
}

exports.client = exportedClient;

And then to use it:

var elasticClient = require('./myElasticClient').client;

var get = function(id) {
  return elasticClient.get({
    index: 'product',
    type: 'products',
    id: id
  }).then(function(response) {
    return response._source;
  });
}

exports.execute = get;

I'm very new to node, but there seems like there must be a better way to do this.


texts:
This is my first question here and this is my working Body Mass Index Swing Calculator.
Any improvement or recommendation is welcome.

// Metric units
// Weight in kg
// Height in meters

import javax.swing.*;
import java.awt.*;

public class MainProgram {

    public static void calculateIMC(DataPanel in){
        String salida = in.weight.getText();
        System.out.print(salida);
    }

    public static void main(String[] args) {

        JFrame frame = new JFrame("BMI");

        DataPanel in = new DataPanel();

        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setBounds(150,150,500,400);
        frame.setLayout(new GridLayout(0,2));
//        frame.pack();
        frame.add(in);
        System.out.println(Grade.getGrade(33.4));
    }
}

This is an enum example

public enum Grade {
    INS("Insuficient Weight",18.5),
    NRM("Normal Wight",24.9),
    SBR1("Overweight Grade 1",26.9),
    SBR2("Overweight Grade 2: Probesity",29.9),
    OBS1("Obesity Grade 1",34.9),
    OBS2("Obesity Grade 2",3.9),
    OBS3("Obesity Grade 3: Morbid",49.9),
    OBS4("Obesity Grade 4: Extreme",50);

    private final String title;
    private final double lim;

    public String getTitle() {
        return title;
    }

    public double getLim() {
        return lim;
    }

    Grade(String s, double i) {
        title = s;
        lim = i;
    }

    public static String getGrade(double value){
        for (int i=0; i < Grade.values().length;i++){
            if(value > Grade.OBS4.getLim()){
                return Grade.OBS4.getTitle();
            } else if(value < Grade.INS.getLim()){
                return Grade.INS.getTitle();
            } else if(value > Grade.values()[i].getLim() && value < Grade.values()[i+1].getLim()){
                return Grade.values()[i+1].getTitle();
            }
        }
        return null;
    }
}

And the Panel

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DataPanel extends JPanel {
    JTextField weight = new JTextField(10);
    JTextField height = new JTextField(10);
    JButton calculate = new JButton("Calculate");

    DataPanel(){
        initialize();
    }

    private void initialize() {
        add(new JLabel("Weight: "));
        add(weight);
        add(new JLabel("Height: "));
        add(height);
        add(calculate);

        calculate.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double w=Double.parseDouble(weight.getText());
                double h=Double.parseDouble(height.getText());
                double bmi=w/(h*h);
                JOptionPane.showMessageDialog(null,"Your BMI is: "+String.format("%.2f",bmi));
                JOptionPane.showMessageDialog(null,"Your Grade is: "+Grade.getGrade(bmi));

            }
        });

        setVisible(true);
        setBorder(BorderFactory.createTitledBorder("BMI"));
//        setBounds();
//        setLayout(new GridLayout(0,2));
        setMaximumSize(new Dimension(30,100));
    }

}


texts: Finding maximum length of continuous string which has same characters

texts:
I'm solving this problem from codeforces. I've a solution which has complexity of O(n²). But the time limit exceeds on some of the test cases. The problem statement is:

  High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.

  Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?

  Input

  The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change.

  The second line contains the string, consisting of letters 'a' and 'b' only.

  Output

  Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.
  Examples

  Sample Input/Output:

  8 1

  aabaabaa

  Output

  5

My solution is:

import java.util.Scanner;
public class CF676C {
public static void main(String args[]){
    Scanner in = new Scanner(System.in);
    int n = in.nextInt(), max = in.nextInt(),a=0,b=0;

    String s = in.next();
    int i,j;
    for(i=0;i<n;i++){
        if(s.charAt(i) == 'a'){
            ++a;
        }
        else{
            ++b;
        }
    }
    char z;
    if(a<=b){
        z='a';
    }
    else{
        z='b';
    }
    int max1;
    int count=0;
    int temp=0;
    for(i=0;i<s.length();i++)
    {
        max1=max;
        count=0;
        for(j=i;j<s.length()&&max1!=-1;j++)
        {
            if(s.charAt(j)==z&&max1!=-1)
            {
                max1--;
            }
            if(max1!=-1)
            {
                count++;
            }
        }
        if(count>temp)
        {
            temp=count;
        }
    }
    System.out.println(temp);
}
}

I can't understand how to reduce time taken by the code. Is there any other solution or approach available?


texts: Simple class exercise - min, max, and average of vector items

texts:
This program calculates the min and the max value and the average of the items of a vector. It's an exercise from a book so I can't change the header file.

Is this code proper?

sales.h

#include <vector>

class Sales
{
    private:
        std::vector<double> sales;
        double average;
        double maximum;
        double minimum;
        double calcAvg();

    public:
        Sales(const std::vector<double> ar);
        void setSales();
        void showSales() const;
};

sales.cpp

#include "sales.h"
#include <iostream>
#include <algorithm>

Sales::Sales(const std::vector<double> ar)
{
     sales = ar;
     minimum = *std::min_element(sales.begin(), sales.end());
     maximum = *std::max_element(sales.begin(), sales.end());
     average = calcAvg();
}

void Sales::setSales()
{
    std::vector<double> temp;
    std::cout << "Enter values separated by a space: ";
    for (int i = 0; i < 4; i++)
    {
        int item;
        std::cin >> item;
        temp.push_back(item);
    }
    *this = Sales(temp);
}

void Sales::showSales() const
{
    for(std::size_t i = 0; i < sales.size(); i++)
        std::cout << "Item " << i <<" = " << sales.at(i) << std::endl;
    std::cout << "Average: " << average << std::endl;
    std::cout << "Min, max: " << minimum << " , " << maximum << std::endl;
}

double Sales::calcAvg()
{
    double sum;
    for(std::size_t i = 0; i < sales.size(); i++)
       sum += sales.at(i);
    return sum/sales.size();
}

program.cpp

#include "sales.h"
#include <vector>

int main()
{
    std::vector<double> ar;
    ar.push_back(4);
    ar.push_back(5);
    ar.push_back(23);

    Sales s1(ar);
    s1.showSales();

    Sales s2;
    s2.setSales();
    s2.showSales();
    return 0;
}


texts: How can I better test whether the player won in my tic-tac-toe?

texts:
I created a tic-tac-toe using java and I would like to know if there are any practices that I can improve and make the code cleaner and more performative
import java.util.Scanner;
public class Main {
    public static boolean test(String[] values){
        //Check diagonals
        if((values[0].equals("X") && values[4].equals("X") && values[8].equals("X")) || (values[0].equals("0") && values[4].equals("0") && values[8].equals("0"))){
            System.out.print(values[0] + " win");
            return true;
        }
        if((values[2].equals("X") && values[4].equals("X") && values[6].equals("X")) || (values[2].equals("0") && values[4].equals("0") && values[6].equals("0"))){
            System.out.print(values[2] + " win");
            return true;
        }
        //Check verticals
        for(int x = 0;x < 9;x+=3){
            if((values[0+x].equals("X") && values[1+x].equals("X") && values[2+x].equals("X")) || (values[0+x].equals("0") && values[1+x].equals("0") && values[2+x].equals("0"))){
                System.out.print(values[0+x] + " win");
                return true;
            }
        }
        //Checks horizontal
        for(int x = 0;x < 3;x++){
            if((values[0+x].equals("X") && values[3+x].equals("X") && values[6+x].equals("X")) || (values[0+x].equals("0") && values[3+x].equals("0") && values[6+x].equals("0"))){
                System.out.print(values[0+x] + " win");
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        String[] game = {" ", " ", " ", " ", " ", " ", " ", " ", " "};
        String[] players = {"X", "0"};
        for(int x = 0;x < 9;x++){
            System.out.print(players[x%2] + ": ");
            int currentPlay = read.nextInt();
            while(currentPlay < 1 || currentPlay > 9 || game[currentPlay -1] != " "){
                System.out.print("Invalid, play again: ");
                currentPlay = read.nextInt();
            }
            if(x % 2 == 0){
                game[currentPlay -1]  = "X";
            }
            else{
                game[currentPlay -1] = "0";
            }
            System.out.printf("%s | %s | %s\n%s | %s | %s\n%s | %s | %s\n", game[0], game[1], game[2], game[3], game[4], game[5], game[6], game[7], game[8]);
            if(test(game)){
                break;
            }
            if(!test(game) && x == 8){
                System.out.print("Tie");
            }
        }
    }
}


texts: A custom error to be thrown when numeric values are out of bounds

texts:
Why did I make this? I'm building an interactive data structure visualization, and when certain errors are thrown from certain parts of the code, they are displayed on screen for the user. I have not included that displaying logic.

The if checks seem somewhat smelly to me, but they might be simple enough to the point that they're fine. I'm interested in best practices, ANY criticism is welcome.

export class OutOfBoundsError extends AppError {
// AppError code is not included, but it is just an extremely simple
//abstract class I needed so I could instanceof to check whether a caught
// error was thrown by my own code
// If you want, pretend I'm extending JS's RangeError instead

constructor(valueName: 'length' | 'index' | 'position', value: number,
              bounds?: {
                lowerBoundInclusive?: number;
                upperBoundInclusive?: number
              }) {
    super();
    const lower = bounds?.lowerBoundInclusive;
    const upper = bounds?.upperBoundInclusive;
    if (lower === undefined) {
      if (upper === undefined) {
        this.message = `${valueName} of ${value} is out of bounds`;
      } else {
        this.message = `${valueName} must be less than or equal to ${upper} but\
         ${value} was given`;
      }
    } else {
      if (upper === undefined) {
        this.message = `${valueName} must be greater than or equal to ${lower}\
         but ${value} was given`;
      } else {
        this.message = `${valueName} must be between ${lower} and ${upper} but\
         ${value} was given`;
      }
    }
  }
}
```


texts: Similar statements need duplication removed

texts:
How would you refactor this?

ExpensiveQuery must only run when necessary.

DECLARE @city VARCHAR(10)
DECLARE @status INT

IF @status = 5
BEGIN
    SELECT c.Name, c.Phone
    FROM Customers c
    WHERE c.City = @city
    AND c.Status = 5
END
ELSE IF @status = 10
BEGIN
    SELECT c.Name, c.Phone
    FROM Customers c
    WHERE c.City = @city
    AND c.Status = 10
    AND c.SignUpDate NOT IN (EXEC ExpensiveQuery)
END


texts: JavaScript canvas animation slowing down and hogging memory

texts:
I'm experimenting with moving shapes in JavaScript with a canvas tag.

I have one half circle (only stroked) which rotates on set intervals.

I've written the code so many more can be added. I can give starting rotations and a lot of other handy parameters.

I've tried this with twelve circles and it looks exactly like I want. Problem is, the animation slows down and the framerate goes down quite fast. And it uses heaps and heaps of memory. Any ideas on how to optimize this code to not consume so much?

Demo: http://jsfiddle.net/xaddict/fLE8z/

JS code:

var kin;
var canvas;
var context;
var pi = Math.PI;
var linearSpeed = 0.5*pi; // pixels / second
var linearDistEachFrame;
var myCircle;

function Circle(x, y, rot, radius, borderWidth, strokestyle){
    this.x = x;this.y = y;
    this.radius = radius;
    this.borderWidth = borderWidth;
    this.rot = rot
    this.goalrot = rot;
    this.strokestyle = strokestyle;
}

function randomizeThis(object){
    object.goalrot += pi;
}

function updateCircle(object){
    if(object.goalrot > object.rot){ //if goal rotation is bigger than current rotation
        object.rot += linearDistEachFrame;
    }else{ // if goal rotation is equal or smaller than current
            if(object.goalrot >= 2* pi){object.goalrot -= 2* pi;}
            object.rot = object.goalrot;
    }
}

function drawCircle(object){
    context.beginPath();
  context.arc(object.x, object.y, object.radius, object.rot, object.rot+pi, false);
  context.fillStyle = "none"; context.fill();
  context.lineCap = "round";
  context.lineWidth = object.borderWidth;
  context.strokeStyle = object.strokestyle;context.stroke();
}

function drawCirc(context,x,y,radius,clip){
    context.beginPath();
    context.arc(x,y,radius, 0, 2*pi, false);
    if(clip == true){context.clip();}
}

window.onload = function(){
    kin = new Kinetic_2d("canvas");
    canvas = kin.getCanvas();
    context = kin.getContext();

    myCircle =         new Circle(421,320,1.0*pi,    153,    12,"#FAA61A");//FAA61A

    kin.setDrawStage(function(){
        //update
        linearDistEachFrame = linearSpeed * kin.getTimeInterval() / 1000;
        updateCircle(myCircle);

        //clear
        kin.clear();

        //draw
        context.save();
        drawCirc(context,281,222,58,true);
        drawCircle(myCircle);
        context.restore();
    });

    kin.startAnimation();

    setTimeout(function(){randomizeThis(myCircle);setInterval("randomizeThis(myCircle)",4000);clearTimeout(this);},6000);
};

Thanks for all help!


texts:
I've implemented a class to perform a couple of tasks through a web service. I'll be really keen if you can take a look at, give me your professional opinion.

using MWM.NavisionWebService.WebReferenceTest;
using NLog;
using System;
using System.Net;
using System.Configuration;

namespace MWM.NavisionWebService
{
    public class WebServiceAccess : IDisposable
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly string _user;
        private readonly string _pass;
        private readonly NSO _nsoWebService;

    public WebServiceAccess()
    {
        _nsoWebService = new NSO { Credentials = GetCredentials() };
        _user = ConfigurationManager.AppSettings["CghWebServiceUserName"];
        _pass = ConfigurationManager.AppSettings["CghWebServicePassword"];
    }

    public void UpdateTechnician(string serviceOrderId, string technicianErpId)
    {
        try
        {
            int errorCode = _nsoWebService.UpdateResource(serviceOrderId, technicianErpId);

            if (errorCode != 0)
                HandleErrors(errorCode);
            else
                _logger.Trace(String.Format("Navision Technician updated to {0} for service order {1}.", technicianErpId, serviceOrderId));
        }
        catch (Exception ex)
        {
            _logger.Error("Error updating a technician in Navision. Error: " + ex.Message);
            throw;
        }
    }

    public void UpdateAppointmentDate(string serviceOrderId, DateTime startDate)
    {
        try
        {
            int errorCode = _nsoWebService.UpdateTime(serviceOrderId, startDate, startDate);

            if (errorCode != 0)
                HandleErrors(errorCode);
            else
                _logger.Trace(String.Format("Navision appointment updated to {0} for service order {1}.", startDate, serviceOrderId));
        }
        catch (Exception ex)
        {
            _logger.Error("Error updating an appointment in Navision. Error: " + ex.Message);
            throw;
        }
    }

    private ICredentials GetCredentials()
    {
        return new NetworkCredential(_user, _pass);
    }

    private void HandleErrors(int errorCode)
    {
        _logger.Error("Error updating Navision through the web service. Code: " + errorCode + " Message: " + GetErrorCodeDescription(errorCode));
    }

    private string GetErrorCodeDescription(int errorCode)
    {
        switch (errorCode)
        {
            case 0:
                return "OK";
            case 1:
                return "Could not find CCC Order No.";
            case 51:
                return "Could not write table.";
            default:
                return "Error code not found.";
        }
    }

    public void Dispose()
    {
        // Dispose from unmanaged resources
        _nsoWebService.Dispose();
    }
}
}


texts: Plotting quadratic equations with varying parameters

texts:
On Wikipedia, there is a graph shown:

It shows the quadratic \$y = ax2 + bx + c\$, varying each coefficient separately while the other coefficients are fixed (at values a = 1, b = 0, c = 0)

As a learning experience I decided to replicate these plots in Matplotlib as follows:

import numpy as np
import matplotlib.pyplot as plt
import math

#Plot the quadratic function y = ax2 + bx + c
#Varying each coefficient [a, b, c] separately while the other coefficients are fixed (at values a = 1, b = 0, c = 0)

#Iterate these 5 coeficients and plot each line
coefs = [-2, -1, 0, 1, 2]

#set up the plot and 3 subplots (to show the effect of varying each coefficient)
f, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(18, 6))

#some x values to plot
x = np.linspace(-2, 2, 30)

for idx, val in enumerate([ax1, ax2, ax3]):

    for v in coefs:
        a, b, c = 1, 0, 0

        if idx == 0:
            a = v
        elif idx == 1:
            b = v
        else:
            c = v

        y = a * (x**2) + (b * x) + c

        val.plot(x, y, label="Coeficient is " + str(coefs[i]))

        val.axhline(y=0, color='k')
        val.axvline(x=0, color='k')
        val.grid()
        val.legend(loc='lower center')

plt.show()

It works fine:

but I am new to programming and I have an uneasy feeling that using if statements isn't optimal. It feels like I should be iterating over something rather than using ifs.

What other ways could I iterate over the coefficients a, b & c to produce the 3 different subplots?


texts:
CellDrawableProvider is an Android class used in the game Tic-Tac-Toe. It provides drawables for cells of game board (drawables for figures X and O, and "Fire" if the cell is in the firing line). To save memory, this class uses a map to store the already created drawables.

class CellDrawableProvider {
    private final Map<Object, Drawable> drawables;
    private final Resources resources;

    CellDrawableProvider(Resources resources) {
        this.resources = resources;
        this.drawables = new HashMap<Object, Drawable>();
    }

    Drawable getCellDrawable(int moveIconId, int fireIconId) {
        if (fireIconId == android.R.color.transparent) {
            return getDrawable(moveIconId);
        } else {
            return getLayerDrawable(moveIconId, fireIconId);
        }
    }

    private Drawable getLayerDrawable(int moveIconId, int fireIconId) {
        Object layerDrawableKey = Pair.create(moveIconId, fireIconId);
        Drawable layerDrawable = drawables.get(layerDrawableKey);
        if (layerDrawable == null) {
            layerDrawable = createLayerDrawable(moveIconId, fireIconId);
            drawables.put(layerDrawableKey, layerDrawable);
        }
        return layerDrawable;
    }

    private Drawable createLayerDrawable(int moveIconId, int fireIconId) {
        Drawable[] layers = new Drawable[2];
        layers[0] = getDrawable(moveIconId);
        layers[1] = getDrawable(fireIconId);
        return new LayerDrawable(layers);
    }

    private Drawable getDrawable(int iconId) {
        Drawable drawable = drawables.get(iconId);
        if (drawable == null) {
            drawable = resources.getDrawable(iconId);
            drawables.put(iconId, drawable);
        }
        return drawable;
    }
}

I do not like the class name CellDrawableProvider and method name getCellDrawable().

Can you suggest better names?


texts: Can it be shorter?: DNA Sequence Analyzer from CS50 written in Python

texts:
This is my first time requesting a code review. This is code I wrote in Python to create a DNA sequence analyzer. This is for the Harvard CS50 course.
I was really hoping to get some constructive criticism on this code I finished for the DNA problem in Problem Set 6. This code passed all tests and is fully functional as far as I am aware.
I was mainly wondering if there were any more succinct ways to rewrite parts of it. I spent several hours writing this and my brain is pretty exhausted, so near the end I just went for whatever worked.
Any input is appreciated! (Also, sorry if this is an excessive amount of comments, but they help me keep everything clear in my head.)
import re
import csv
from sys import argv

# Checks for correct number of command-line arguments
if not len(argv) == 3:
    print("Incorrect number of command-line arguments.")
    exit(1)

# Declares a dictionary containing STR counts
str_counts = {
    "AGATC": "0",
    "TTTTTTCT": "0",
    "AATG": "0",
    "TCTAG": "0",
    "GATA": "0",
    "TATC": "0",
    "GAAA": "0",
    "TCTG": "0"
}

# Opens the csv and txt files to read (and closes them later)
with open(argv[1], "r", newline="") as csv_file, open(argv[2], "r") as sequence:
    # Reads the database into a dict and the sequence into a string
    db = csv.DictReader(csv_file)
    sq = sequence.read()

    # Stores the fieldname of the dictionary and stores the keys in STRS, skipping first line
    keys = db.fieldnames
    key_len = len(keys)
    # Skips first row of headers
    STRs = keys[1:key_len]

    # Bool to signal if match was found
    matched = False

    # Checks for STR matches and length of those matches, then stores those values in str_counts
    for STR in STRs:
        # Executes following code only if there are 1 or more matches
        if re.search(rf"(?:{STR}+)", sq):
            # Creates a list of matches
            matches = re.findall(rf"(?:{STR})+", sq)
            # Finds the longest match
            longest = max(matches, key = len)
            # Stores that value in corresponding dict key
            str_counts[STR] = len(longest) / len(STR)
            # Compares str_counts values to database to find match

    # Compares the match count values to the database values
    for row in db:
        # Declares a counter to later check if all STR values are matched
        # Resets counter to zero every iteration
        match_count = 0
        # Declares a temporary dictionary with only int match values to compare STR counts to
        compare = {}
        # Stores the names field for use later
        match_name = row['name']
        # Deletes the names field so we only have ints in our compare dict
        del row['name']
        # Converts values to integers for easy comparison
        for key, value in row.items():
            compare[key] = int(value)
        # Increments match count
        for STR in STRs:
            if compare[STR] == str_counts[STR]:
                match_count += 1
        # If all fields are matched, print match name, switch bool to true
        if match_count == len(STRs):
            matched = True
            print(match_name)

    if not matched:
        print("No Match")


texts:
This code creates a text file and writes a given number of characters to it. Is this a good method, or is there a faster method?

#include <fstream>
#include <iostream>

std::ofstream file;

int main() {
    int size = 10000000; //~10MB
    file.open("text_file.txt");
    for (int i = 0; i < size; i++) {
        file << "a";
    }
    return 0;
}


texts:
I'm trying to learn linked lists so I can answer interview questions. Even though I've seen plenty of tutorials to understand how they supposedly work, I don't know if I am doing a good job because I have no one to get feedback from.

class Node(object):

    def __init__(self, data, next_node = None):
        self.data = data
        self.next = next_node

    def __str__(self):
        return str(self.data)

class SinglyLinkedList(object):

    def __init__(self):
        self.head = None

    def prepend(self, data):
        '''
        Creates a new node and inserts it at the front, making it the head
        of the list
        '''
        self.head = Node(data, next_node=self.head)

    def append(self, data):
        '''
        Creates a new node and inserts it at the very end of the list
        '''
        new_node = Node(data)
        if self.head == None:
            self.head = new_node
        else:
            iter_node = self.head
            while iter_node.next:
                iter_node = iter_node.next
            iter_node.next = new_node

    def insert(self, after_node, data):
        '''
        A new node is created containing the passed data, and then inserted
        right after the node called after_node in the list
        '''
        new_node = Node(data)
        new_node.next = after_node.next
        after_node.next = new_node

    def delete(self, node):
        '''
        Removes the given node from the list. If the node is at the tail already,
        it is set to None. Otherwise it is "de facto" removed by having it mirror the next
        node's data, and then link to that mirror's next node.
        '''
        if node.next == None:
            node = None
        else:
            node.data = node.next.data
            node.next = node.next.next

    def reverse(self):
        '''
        Reverses the entire linked list.
        '''
        if self.head:
            prev = None
            current = self.head
            while current:
                future = current.next
                current.next = prev
                prev = current
                current = future
            self.head = prev

    def __iter__(self):
        '''
        Yields each node in the list over a loop
        '''
        iter_node = self.head
        while iter_node:
            yield iter_node
            iter_node = iter_node.next

    def __str__(self):
        return "[" + ", ".join(str(node) for node in self) + "]"


texts:
For a programming challenge I was doing, I needed to traverse a list of lists, and while writing the standard 2D traversal function, I thought why not generalise it, so I did. Here's my best effort:

My Code

def rTraverse(lst, f = lambda x: x):        #Traverse a list and any of its (non self referential) sublists recursively.
    for item in lst:
        if isinstance(item, list):
            if "..." in str(item):  #Skip self-referential lists.
                continue
            traverse(item, f)   #Traverse the sublist.
        else:
            f(item)


texts: Activity Selection to maximize the number of activity executions

texts:
I solved this problem from a challenge.The problem is as below:-

Problem Statement:

Given N activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.

Note : The start time and end time of two activities may coincide.

Input:
The first line contains T denoting the number of testcases. Then follows description of testcases. First line is N number of activities then second line contains N numbers which are starting time of activies.Third line contains N finishing time of activities.

Output:
For each test case, output a single number denoting maximum activities which can be performed in new line.

Constraints:

1<=T<=50
1<=N<=1000
1<=A[i]<=100

Example:

Input:

2
6
1 3 2 5 8 5
2 4 6 7 9 9
4
1 3 2 5
2 4 3 6

Output:

4
4

C++ code for the problem:-

#include<iostream>
void swap(int a[],int i,int j)
{
    int temp=a[i];
    a[i]=a[j];
    a[j]=temp;
}
int activitySelection(int start[], int end[], int n){

    long i,j,count=1,pointer;
    for(i=0;i<n;i++)         //sorting both arrays in the order of the end array
    {
        for(j=i+1;j<n;j++)
        if(end[j]<end[i])
        {
            swap(end,i,j);
            swap(start,i,j);
        }

    }
    pointer=end[0];  //pointer set to end time of the first activity
    for(i=1;i<n;i++)
    {
        if(start[i]>=pointer) //if
        {
            count++;

            pointer=end[i];
        }

    }
    return count;
}
int main()
{
  int t;
  std::cin>>t; /*number of testcases*/
  while(t--)
  {
    int n;
    std::cin >> n;
    int start[n], end[n];
    for(int i=0;i<n;i++)
        std::cin>>start[i];
    for(int i=0;i<n;i++)
        std::cin>>end[i];

   std:: cout << activitySelection(start, end, n) << std::endl;
  }
}

The code works as I intended to.But there are few openings that i feel could be improved in the code.The above code basically sorts the both arrays according to the end[] array.Then it checks if the starting time of the current activity is greater or equal to the end time of the previous activity,if yes then count increments and the pointer is set to the end time of the current activity for comparing the next activity.Two things i want to know:

1.Is there a better approach than sorting arrays and comparing?

2.What is a better way to sort the two arrays on the basis of the second array?

Please suggest changes to improve.Thanks for reading ;-)


texts:
I'm working on a piece of code in my MVC3 application and I'm struggling to decide if what I plan to do is a bad idea or not.

I have a snippet of JavaScript that calls an MVC action that in turn returns an HTML partial that I then insert into a div element on my page. Nothing complicated there.

However, things have changed and I now need to pass back a possible error message as well. I propose to send this back with the HTML partial as part of a JSON object.

It would look something like this:

{
     errorMessage: "things have gone wrong!",
     partial : "
Test	0MB

Test2	1MB
"
}

This seems pragmatic but maybe a little dirty to me, so I'd like the thoughts of the community, please.

Now the obvious alternative would be to pass the table data back as JSON as well, and parse it client-side. But this will be a pain, even with something like jQuery templates (the example I've put up is simplified).


texts: To assign objects from array of objects to mulitple arrays in JavaScript

texts:
Suppose I have this array that contains objects:

       var purchasedSeats =[ {
            FlightNumber: '1',
            Price: 25,
          },
          {
            FlightNumber: '1',
            Price: 10,
          },
          {
            FlightNumber: '2',
            Price: 25,
          },
          {
            FlightNumber: '2',
            Price: 25,
          }]

purchasedSeats can be in any order any order
Also I have another array which is shown below:

 var Passengers=[{SelectedSeats:[]},{SelectedSeats:[]}];

my  goal is to get the output as:

Passengers=[
  {SelectedSeats:[{FlightNumber: '1',Price: 25},{FlightNumber: '2',Price: 25,}]},
  {SelectedSeats:[{FlightNumber: '1',Price: 10},{FlightNumber: '2',Price: 25,}]}
]

Each SelectedSeats shouldn't  have same flightnumber.

Below is the code which I have implemented and is working.Is there a better way?

          for (let i = 0; i < Passengers.length; i++) {
          for (let seat = 0; seat < purchasedSeats.length; seat++) {
              console.log(seat)
              if (Passengers[i].SelectedSeats.length === 0) {
                  Passengers[i].SelectedSeats.push(purchasedSeats[seat])
                  purchasedSeats.splice(seat, 1);
              } else {
                  const flightExists = Passengers[i].SelectedSeats.some(function (el) {
                      return el.FlightNumber === purchasedSeats[seat].FlightNumber;
                  });
                  console.log(flightExists);
                  if (!flightExists) {
                      Passengers[i].SelectedSeats.push(purchasedSeats[seat]);
                      purchasedSeats.splice(seat, 1);
                  }
              }
          }
      }


texts: HTTP request for a single URL or list of URLs based on arguments provided

texts:
I have the following code that includes a simple class AioRequest. I would like to be able to call an instance of this class directly with a single URL or a list of URLs and return the results.

request = AioRequest()
single_response = request('get', 'http://httpbin.org/get')

or

url_list = ['http://httpbin.org/get', 'http://google/some_json']
list_of_responses = request('get', url_list)

I'm wondering what the best practice is for two strategies I am using:

Determining if the argument is a list of URLs or a string with a single URL. Should it be two separate arguments like __call__ or should I type check like __call__2?
I would like to use the __call__ method as the main API for the AioRequest instance, but is returning two different types based on the arguments given a good idea? Is is safe to rely on the user to determine the return type (example: give a single string get a single response, give a list of strings, get a list of responses)?

import asyncio
from aiohttp import ClientSession
from collections import namedtuple

Response = namedtuple(
    "Response",
    ["url", "status_code", "json"]
)

class AioRequest:

    def __init__(self, session=None):
        self._loop = asyncio.get_event_loop()
        self._session = session or ClientSession(loop=self._loop)

    def __call__(self, method, url=None, url_list=None, **kwargs):
        urls = url_list or []
        urls.append(url)
        requests = [self._request(method, url, **kwargs)
                    for url in urls
                    if url is not None]
        return self._run(*requests)

    def __call__2(self, method, url_or_list_of, **kwargs):
        if type(url_or_list_of) is str:
            return self._run(method, url_or_list_of, **kwargs)
        else:
            requests = [self._request(method, url, **kwargs)
                        for url in url_or_list_of]
            return self._run(*requests)

    async def _request(self, method, url, **kwargs):
        response = await self._session.request(method, url, **kwargs)
        return Response(url, response.status, await response.json())

    def _run(self, *tasks):
        task_group = asyncio.gather(*tasks)
        results = self._loop.run_until_complete(task_group)  # results = list of responses
        if len(results) == 1:
            return results[0]
        return results

    def __del__(self):
        self._session.close()


texts: An algorithm that finds a sequence of numbers to fill a square grid

texts:
Given numbers 1,2,3,4,5,6,7,8 I need them to replace the x's so that each side adds up to the number in the centre.

*-*---*-*
|x| x |x|
*-*---*-*
|x| 12|x|
*-*---*-*
|x| x |x|
*-*---*-*

As a start I have looped over the numbers to find all of the possible combinations.

var range = [1,2,3,4,5,6,7,8];
var target = 12;
var matches = [];

for (x = 0; x < range.length; x ++){
    for (y = 0; y < range.length; y ++){
        if (y === x){
            continue;
        }
        for (z = 0; z < range.length; z ++){
            if (z === y || z === x){
                continue;
            }

            if (range[x] + range[y] + range[z] === target){
              matches.push([range[x], range[y], range[z]]);
            }
        }
    }
}

Next I have joined the numbers together end to end

for (j=0; j < matches.length; j++){
  for (k=0; k < matches.length; k++){
    if (j==k) continue;
    //if (matches[j][2] != matches[k][0]) continue;
    for (l=0; l < matches.length; l++){
      if (l==j || l==k) continue;
      //if (matches[k][2] != matches[l][0]) continue;
      for (m=0; m < matches.length; m++){
        if (m==j || m==k || m==l) continue;
        if (matches[l][2] != matches[m][0]) continue;
        if (matches[m][2] != matches[j][0]){
          console.log(matches[j], matches[k], matches[l], matches[m]);
        }

      }
    }
  }
}

I have not currently put a check in to make sure each combination of numbers is only used once, which is how I would solve this.

I really would like to know an overall better approach to solving this problem.

A solved cube would look like:

*-*---*-*
|1| 5 |6|
*-*---*-*
|8| 12|4|
*-*---*-*
|3| 7 |2|
*-*---*-*


texts:
$(document).ready(function() {

  $('#state-list, #major-list').hide();

  $('#state').bind('click', function() {
    $('#state-list').toggle();
  });

  $('#major').bind('click', function() {
    $('#major-list').toggle();
  });

});

All links and lists will follow the naming convention of:

link, link-list, like seen below:

Link

...

Is there a way listen for all links and toggle their respective lists, instead of creating a bind click for every link?


texts: Storing and retrieving student scores in three subjects

texts:
This is written to find percentages of three subjects. Original HackerRank practice problem is here.

  Input Format

  The first line contains the integer N, the number of students. The next  N lines contains the name and marks obtained by that student separated by a space. The final line contains the name of a particular student previously listed.

  Output Format

  Print one line: The average of the marks obtained by the particular student correct to 2 decimal places.

This code is working but I need better way of writing this code.

a = input()
a = int(a)
dict = {}
f = []
n = {}
for i in range(a):
        f = input().split()
        name = f[0]
        n['phy'] = float(f[1])
        n['che'] = float(f[2])
        n['math'] = float(f[3])
        f = []
        dict[name] = n
        n ={}
nam = input();
per = (dict[nam]['phy']+dict[nam]['che']+dict[nam]['math'])/3
print("%.2f"%per)


texts:
I was browsing Stack Overflow recently and saw a PHP question about rearranging an array of arrays for printing. The initial data structure looked like this:

$array1 = array(
    array("type01",1995),
    array("type03",1996),
    array("type01",1995),
    array("type09",1998),
    array("type09",1995),
    array("type02",1997),
    array("type01",1995),
    array("type02",1999),
    array("type09",1995)
);

For printing, the number of occurrences of each pairing--type and year--had to be counted and a table of frequencies made with type as columns and the years as the rows, i.e.

Year    type01    type02    type03    type09
1995    3         0         0         2
1996    0         0         1         0
1997    0         1         0         0
1998    0         0         0         1
1999    0         1         0         0

(the actual table formatting was not critical)

Someone else answered the question, and used the following code:

$sorted = array();
$types = array();
array_walk($array1, function($v) use (&$sorted, &$types){
   if( !isset($sorted[$v[1]]) )
       $sorted[$v[1]] = array();
   $sorted[$v[1]][] = $v[0];
   $types[] = $v[0];
});

// filter types
$types = array_unique($types);
sort($types);

// sort year
ksort($sorted);

echo '----' . implode(' ,', $types) . "\r\n";
foreach($sorted as $year => $data)
{    echo $year . ' - ';
    $count = array_count_values($data);

   foreach($types as $type)
   {
      if( !isset($count[$type]))
      {
          echo '0,';
      } else {
          echo $count[$type].',';
      }
   }
   echo "\r\n";
}

I come from a Perl background, and I would use the following code to solve the problem:

$finalArray = array();
$years = array();

foreach ($array1 as $ix) {
    // $ix[0] is typeNN, $ix[1] is year.
    // index by type and then year.
    // the accumulator will count the number per type per year
    $finalArray[ $ix[0] ][ $ix[1] ]++;
    // keep an array of years
    $years[ $ix[1] ]++;
}

// sort arrays by key
ksort($finalArray);
ksort($years);

// print out the column headings
echo "Year\t" . implode("\t", array_keys($finalArray) ) . "\n";

// now add the data
foreach (array_keys($years) as $y) {
    echo $y;
    // for each type, check the frequency for the year
    // print '0' if the year does not exist
    foreach ($finalArray as $type => $year) {
        if (array_key_exists($y, $year)) {
            echo "\t" . $year[$y];
        } else {
            echo "\t0";
        }
    }
    echo "\n";
}

Granted, the two pieces of code format the table slightly differently, but is one approach "better"--more efficient, more in line with standard PHP coding practices--than the other?

I'm also aware that my code generates notices about undefined index/offsets because I'm used to Perl's autovivification of data structures. Is this something to worry about or not?


texts: React component to animate planets on a canvas

texts:
I wrote some JavaScript to generate some graphics on a canvas, on a regular HTML page.

I now want the same code to run in a component that is part of a React app. I've done this:

  componentDidMount() {
    const canvas = this.refs.firstCanvas
    const ctx = canvas.getContext('2d')
    const bgCanvas = this.refs.firstbgCanvas
    const bgCtx = bgCanvas.getContext('2d')

    function generateStarfield() {
      bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height)
      for (let i = 0; i < 2000; i++) {
        bgCtx.beginPath()
        const x = Math.random()*bgCanvas.width
        const y = Math.random()*bgCanvas.height
        bgCtx.arc(x, y, 0.35, 0, 2*Math.PI, 'anticlockwise')
        bgCtx.closePath()
        bgCtx.fillStyle = 'white'
        bgCtx.fill()
      }
    }
    generateStarfield()

    const origin_x = 1000
    const origin_y = 1000
    const scale = 1000

    class planet {
      constructor(orbital_velocity, offset_theta, orbital_radius, radius, colour) {
        this.orbital_velocity = orbital_velocity
        this.orbital_radius = orbital_radius
        this.colour = colour
        this.radius = radius
        this.offset_theta = offset_theta
        this.draw()
      }

      draw() {
      const theta = this.offset_theta + (t*this.orbital_velocity)
      const x = origin_x + (this.orbital_radius*Math.cos(theta))
      const y = origin_y + (this.orbital_radius*Math.sin(theta))
      ctx.beginPath()
      ctx.arc(x, y, this.radius, 0, 2*Math.PI, 'anticlockwise')
      ctx.closePath()
      ctx.fillStyle = this.colour
      ctx.fill()
      }
    }

    let t = 0

    const a = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.1, 10, 'white')
    const b = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.2, 16, 'white')
    const c = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.3, 18, 'white')
    const d = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.4, 14, 'white')
    const e = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.5, 12, 'white')
    const f = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.6, 28, 'white')
    const g = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.7, 22, 'white')
    const h = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.8, 20, 'white')

    setInterval(function() {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.beginPath()
      a.draw()
      b.draw()
      c.draw()
      d.draw()
      e.draw()
      f.draw()
      g.draw()
      h.draw()
      t += 0.05
    }, 40)
  }

Now, this works (!), but I've just lifted it directly from the original JavaScript, and modified the document.getElementByID calls to use refs. Is it bad practice to stick all of this stuff into componentDidMount?

Note - I'm aware that the code itself could be tidied up, I'm mainly asking about putting all of this (especially the definitions for planet and generateStarField) into componentDidMount.


texts: Searching a Word Document from Excel - v2.0

texts:
My first question:

Searching a Word Document from Excel

Since then I have implemented most of the suggestions by @RubberDuck and @Comintern. I have also added functionality for different-sized spreadsheets (horizontal and vertical), read multiple files in during a single run of the macro, and a bunch of constants.

This is what I currently have:

Global lineCount As Integer

Sub LoadWordFromExcel()

    Const ONE As Integer = 1
    Const FIRST_ROW As Integer = 2
    Const PATH_TO_FOLDER As String = "C:\Users\<user>\Desktop\Macro folder\"
    Const LAST_NAME As Integer = 3
    Const CHOP_LEFT As Integer = 21
    Const CHOP_RIGHT As Integer = 11

    Dim r As Integer
    Dim k As Integer
    Dim c As Integer
    Dim filePath As String
    Dim file As String
    Dim lastRow As Integer
    Dim lastColumn As Integer
    Dim sheet As Worksheet
    Set sheet = ActiveSheet

    'Finds last row and column with valid data
    With ActiveSheet
        lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
        lastColumn = ActiveSheet.Cells(ONE, Columns.Count).End(xlToLeft).Column
    End With

    For c = ONE To lastColumn
        file = Dir$(PATH_TO_FOLDER & sheet.Cells(ONE, c).Value & ".docx")
        If (Len(file) > 0) Then
            filePath = PATH_TO_FOLDER & file
            Dim entries As Scripting.Dictionary
            Set entries = LoadWordToDictionary(filePath)
            For r = FIRST_ROW To lastRow
                For k = 1 To lineCount
                    If InStr(entries(k), sheet.Cells(r, LAST_NAME).Value) <> 0 Then
                        sheet.Cells(r, c).Value = Left(Right(entries(k), CHOP_LEFT), CHOP_RIGHT)
                        Exit For
                    Else
                        sheet.Cells(r, c).Value = ""
                    End If
                Next
            Next
        End If
    Next
    MsgBox ("I'm Finished")
End Sub

'Loads data from word document and adds it to a dictionary
Private Function LoadWordToDictionary(file As String) As Scripting.Dictionary

    Dim host As New Word.Application
    Dim doc As Word.Document
    Dim lines() As String

    'loads data from Word doc into lines'
    Set doc = host.Documents.Open(file)
    lines = Split(doc.Content.Text, vbCr)
    doc.Close
    host.Quit

    Dim output As New Scripting.Dictionary
    Dim items() As String
    Dim i As Integer

    'Loads data from lines(array) to output(scripting.dictionary)
    For i = 0 To UBound(lines)
        Call output.Add(i + 1, lines(i))
    Next i

    lineCount = UBound(lines)
    Set LoadWordToDictionary = output

End Function

Questions:

Am I still unwittingly using Hungarian Notation? I read the article but it brought up more questions than answers.
Is there anything that I'm overthinking and could simplify? I'm looking at my nested for loop and can't help but think there's another way to do it.

So far, this script is FAST. It can enter over 5,000 cells of information in under 30s instead of the 5-10 minutes for 300 cells that the first version did.


texts: Binary Search Tree implementation in Python 3

texts:
Please review my BST Code

1. Class node

class Node:

2. Constructor

def __init__(self, data):
    self.left = None
    self.right = None
    self.data = data

3. Insert node

def insert(self, data):
    if self.data:
        if data < self.data:
            if not self.left:
                self.left = Node(data)
            else:
                self.left.insert(data)
        elif data > self.data:
            if not self.right :
                self.right = Node(data)
            else:
                self.right.insert(data)
    else:
        self.data = data

4. Node in delete any value

def getMinValue(self,node):
    current = node
    while(current.left is not None):
        current = current.left
    return current
def delValue(self,data):
    if data < self.data:
        self.left = self.left.delValue(data)
    elif data > self.data:
        self.right = self.right.delValue(data)
    else:
        if self.left is None:
            temp = self.right
            self = None
            return temp
        elif self.right is None:
            temp = self.left
            self = None
            return temp
        temp = self.getMinValue(self.right)
        self.data = temp.data
        self.right = self.right.delValue(temp.data)
    return self

5. Node in search any value

def getSearchValue(self,data):
    if data == self.data:
        return print(self.data,"True")
    if data < self.data:
        if self.left:
            self.left.getSearchValue(data)
    if data > self.data:
        if self.right:
            self.right.getSearchValue(data)

6. Print tree

def print_tree(self):
    if self.left:
        self.left.print_tree()
    print(self.data)
    if self.right:
        self.right.print_tree()


texts:
I wanted to center some text in my commandline application, so I came up with this function.

centerText(){
textsize=${#1}
spacecount=$(tput cols)
spacecount=$((($spacecount-$textsize)/2))
while [ $spacecount -gt 0 ]
do
        printf " "
        spacecount=$((spacecount-1))
done
printf "$1"
echo
}

If you have suggestions on how to improve the code, and/or know a better way of centering text, please let me know.


texts:
I have wrote a program that lets the user open up their text file that would look something like this:

1
2
3
4
5
6

It would then let the user enter a name for the list such as "numbers" The program would then let the user choose where they want to save the list. The user would then click go and the program would turn their input into a list like this:

numbers = ['1', '2', '3', '4', '5', '6']

This is the code that I wrote:

import tkinter
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
from tkinter import filedialog
import sys

def program():
    global saveName
    with open(fname) as input_file:
        longList = [line.strip() for line in input_file.readlines()]
        finListName = listName.get()
        finList = (finListName) + (" = ") + str(longList)
        txtFile = open((saveName),"w")
        txtFile.write(finList)

#Window
window = tkinter.Tk()
window.title("Python List Maker")
window.geometry("300x170")

#Label
fileSelectLBL = tkinter.Label(window, text="Please select your file:")
fileSelectLBL.pack()

#Button
def load_file():
    global fname
    fname = askopenfilename(filetypes=(("Text files", "*.txt"),
                                       ("All files", "*.*") ))
filename = tkinter.Button(window, text="Browse", command = load_file)
filename.pack()

#List Name
listNameLBL = tkinter.Label(window,text="Please enter what you want to call the list:")
listNameLBL.pack()
listName = Entry(window)
listName.pack()

#Save List
saveListLBL = tkinter.Label(window,text="Please select where you want to save the list:")
saveListLBL.pack()
def save_file():
    global saveName
    saveName = asksaveasfilename(filetypes=(("Text files", "*.txt"),
                                       ("All files", "*.*") ))
Savename = tkinter.Button(window, text="Browse", command = save_file)
Savename.pack()

#Go
goBTN = tkinter.Button(window, text="GO!", command = program)
goBTN.pack()

#Main Loop
window.mainloop()

Now although this code works, it is really messy. I am not that new to Python but my code is much longer and complex than what it could/should be. This was my first ever go at a program with a GUI, all of my other programs have just been run through the shell.

I am just looking for some general feedback on how I can improve this, and make it shorter and more efficient.


texts: Inserting two rows that are almost identical to each other

texts:
I'm trying to make test data for an application I'm writing, and some of my test data is very repetitive, involving inserting a row and then inserting another row that is identical except for one column. As such, I have very repetitive INSERT statements that make the file longer than I think it needs to be.

INSERT INTO [dbo].[InvoiceItem] (invoice_item_name, amount, invoice_id) VALUES
  ('TUITION',
    (SELECT tuition_amount FROM [dbo].[Grade] WHERE grade_id =
      (SELECT grade_id FROM [dbo].[Student] WHERE first_name = 'Murdoch')),
    (SELECT invoice_id FROM [dbo].[Invoice] WHERE student_id =
      (SELECT student_id FROM [dbo].[Student] WHERE first_name = 'Murdoch' AND invoice_date = '2019-09-05'))),
  ('TUITION_SERVICE_FEE',
    (SELECT tuition_amount FROM [dbo].[Grade] WHERE grade_id =
      (SELECT grade_id FROM [dbo].[Student] WHERE first_name = 'Murdoch')) * 0.03,
    (SELECT invoice_id FROM [dbo].[Invoice] WHERE student_id =
      (SELECT student_id FROM [dbo].[Student] WHERE first_name = 'Murdoch' AND invoice_date = '2019-09-05'))),
  ('TUITION',
    (SELECT tuition_amount FROM [dbo].[Grade] WHERE grade_id =
      (SELECT grade_id FROM [dbo].[Student] WHERE first_name = 'Hartwell')),
    (SELECT invoice_id FROM [dbo].[Invoice] WHERE student_id =
      (SELECT student_id FROM [dbo].[Student] WHERE first_name = 'Hartwell' AND invoice_date = '2019-09-05'))),
  ('TUITION_SERVICE_FEE',
    (SELECT tuition_amount FROM [dbo].[Grade] WHERE grade_id =
      (SELECT grade_id FROM [dbo].[Student] WHERE first_name = 'Hartwell')) * 0.03,
    (SELECT invoice_id FROM [dbo].[Invoice] WHERE student_id =
      (SELECT student_id FROM [dbo].[Student] WHERE first_name = 'Hartwell' AND invoice_date = '2019-09-05'))),

Is there a way to clean this up by any chance?


texts:
I've recently picked up OOP in Java and I'm trying to use it for my PHP user system.

I've come up with the following generic.class. On my main site, I'll simply put include('generic.class.php'); at the top of the file before my content.

<?php
include_once('connect.class.php');

class User {

    private $id;
    private $username;
    private $email;

    public function __construct(){
        $this->id = $_SESSION['id'];
        $this->username = $_SESSION['username'];
        $this->email = $_SESSION['email'];
    }

}

class Generic {

    private $maintenance = false;

    public function __construct() {
        // Start session
        session_start();

        // Check maintenance status
        if($this->maintenance){
            include('maintenance.php');
            die();
        }

        if(user_logged_in()){
            $user = new User();
        }
    }
}

function user_logged_in(){
    if (isset($_SESSION['username'], $_SESSION['id'])){
        return true;
    } else {
        return false;
    }
}

$generic = new Generic();
$conn = new Conn();
?>

Echoing $user->username doesn't seem to work. Or is there no need to use a User class at all? (most PHP user systems I see don't have a User class)

Is this the right approach to using OOP and classes with a user system? If not, how should my classes be like?


texts: Finding all pairs of elements in an array that sum to a target value

texts:
Is there a shorter way and does not involve nested for loops?

const checkIfSumFromTwoNumbers = (arrayOfNum, targetValue) => {
    let found = [];
    let result = [];

    for (let value of arrayOfNum) {
        if (found[targetValue - value] === true ) {
            result.push({[arrayOfNum.indexOf(value)]: value, [arrayOfNum.indexOf(targetValue-value)]: targetValue - value});
        }
        found[value] = true;
    }
    return result;
};


texts:
I was practicing python on codewars.com with this question:
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
But when I attempted my solution it said it was not optimized enough
Can someone say why it said that?
from itertools import permutations
def next_bigger(n):
    per = list(permutations(str(n)))
    result = []
    for j in per:
        result.append(int("".join(j)))
    for i in sorted(result):
        if i > n:
            return i


texts: Click handler for setting the active color and shape button in a drawing program

texts:
public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source.equals(jbColor1))
            color = getBlue();
        else if (source.equals(jbColor2))
            color = getRed();
        else if (source.equals(jbColor3))
            color = getGreen();
        else if (source.equals(jbColor4))
            color = getBlack();
        else if (source.equals(jbColor5))
            color = getYellow();
        else if (source.equals(jbColor6))
            color = getPink();
        else if (source.equals(btnRectangle)) {
            isSelectedReactangle = true;
            isSelectedCircle = false;
            isSelectedLine = false;
            btnRectangle.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
            btnLine.setBorder(UIManager.getBorder(defaultbtnLable));
            btnCircle.setBorder(UIManager.getBorder(defaultbtnLable));
            count = 0;
        } else if (source.equals(btnCircle)) {
            isSelectedReactangle = false;
            isSelectedCircle = true;
            isSelectedLine = false;
            btnCircle.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
            btnLine.setBorder(UIManager.getBorder(defaultbtnLable));
            btnRectangle.setBorder(UIManager.getBorder(defaultbtnLable));
            count = 0;
        } else if (source.equals(btnLine)) {
            isSelectedReactangle = false;
            isSelectedCircle = false;
            isSelectedLine = true;
            btnLine.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
            btnRectangle.setBorder(UIManager.getBorder(defaultbtnLable));
            btnCircle.setBorder(UIManager.getBorder(defaultbtnLable));
            count = 0;
        } else if (source.equals(btnClear)) {
            btnLine.setBorder(UIManager.getBorder(defaultbtnLable));
            btnRectangle.setBorder(UIManager.getBorder(defaultbtnLable));
            btnCircle.setBorder(UIManager.getBorder(defaultbtnLable));
            panelContent.repaint();
        }
}

I have some code but i would avoid if else statement.
for example this snippet code is repeating few times.

btnLine.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
btnRectangle.setBorder(UIManager.getBorder(defaultbtnLable));
btnCircle.setBorder(UIManager.getBorder(defaultbtnLable));

Some tips and tricks how to avoid if condition so many times


texts:
The following function sets a query for MongoDB, but that's not very important. It takes 2 arguments key can be either - which comes from an empty search by the user in the front end, or any other string. Select can be either sample or all
So it's a switch like this:
                            |
                          /   \
                         /\   /\

In my head at least.
But the code looks terribly bad, so something may be wrong, any tip or trick is welcome:
function setQuery(key, select){
  const project = {"$project":{"_id":0, "quote":1} }
  if (key==="-"){
   return select==="sample"
      ? [{"$sample":{"size":5}}, project ]
      : [{$match:{quote:{$ne:null}}}, project] } else {
        //if key is not - (is a word)
        const reg = new RegExp(key, 'i')
        const userText =  { "$match":{"quote":{ "$regex": reg } }}
      return select==="sample"
        ? [userText, {"$sample":{"size":5}}, project]
        : [userText, project]
    }
  }


texts: Retrieving the Currently Logged in User's Department

texts:
I hope this is the right place for this. I basically wrote the below script for a SharePoint 2013 where I needed to get the department of the currently logged in user.

I was finally able to get it working, but I am not happy with the structure at all:

    // globals
    var currentUser;
    var currentUserName;
    var property = "Department";
    // ctx
    var clientContext = new SP.ClientContext.get_current();
    var oWeb = clientContext.get_web();
    currentUser = oWeb.get_currentUser();
    clientContext.load(currentUser);

    GetCurrentUserProperty();

    // This function first gets the current user's firstname.lastname username (e.g. Joe.Bloggs).
    // If this is successful, it calls the LoadPropertyForUser function, which will retrieve the user's
    // property which was defined in the global "property" variable.
    function GetCurrentUserProperty(){
        clientContext.executeQueryAsync(onQueryUserSuccess, onQueryUserFail);
    }
    function onQueryUserSuccess() {
        // If the query is successful, extract the first.last username and then call LoadPropertyForUser
        window.currentUserName= currentUser.get_loginName().split("\\")[1];
        LoadPropertyForUser(window.currentUserName);
    }
    function onQueryUserFail(sender, args) {
        alert('Failed to retrieve user name');
    }

    function LoadPropertyForUser(userName){
        //Get Instance of People Manager Class
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
        //If you are on On-Premise:
        var targetUser = "DOMAIN1\\" + userName;
        //Create new instance of UserProfileProperty
        departmentProperty = peopleManager.getUserProfilePropertyFor(targetUser, window.property)

        //Execute the Query. (No load method necessary)
        clientContext.executeQueryAsync(onPropertyLoadSuccess, onPropertyLoadFail);
    }
    function onPropertyLoadSuccess() {
        var messageText = window.property + " is " + departmentProperty .get_value();
        alert(messageText);
    }
    function onPropertyLoadFail(sender, args) {
        alert("Error: " + args.get_message());
    }

</script>

As you can see, the GetCurretUserProperty method actually continues on in the onQueryUserSuccess function by calling LoadPropertyForUser. While this does work, I felt that this sort of layout would make a lot more sense :

function Main (property) {
    var property = "Department"
    var username = GetCurrentUserName();
    LoadPropertyForUser(username, property);
}

But I was having trouble with this because whenever I started passing variables from GetCurrentUserProperty to it's success method, I would get errors about loginName not being properly loaded.

If anyone could give me some insight as to how this would be structured I will be very grateful. I also welcome and other feedback people may have - thank you!


texts: Python Expertise Needed for RFID Door Lock

texts:
I have a project that runs an image until an accepted rfid card is scanned. At this point, a video is played and an unlock signal is sent. Before and after the accepted card runs, an image is displayed. Right now when script runs the image is displayed, when card is scanned nothing happens. Alt-Tab into code, enter cursor to shell and scan accepted card, the program works without the background image. Please help....????
Accepted cards are checked against a txt file.
Here is my code:
#!/usr/bin/env python3
from evdev import InputDevice
from select import select
import RPi.GPIO as GPIO
import time
from time import sleep
import subprocess
from subprocess import run
import datetime
import os
import sys
import re
import pygame
from pygame.locals import *

#def main():

def check_if_string_in_file(file_name, string_to_search):
    """Check if any line in the file contains given string"""
    with open(file_name,'r') as read_obj:
        for line in read_obj:
            if string_to_search in line:
                return True
    return False

keys = "X^1234567890asdfghjklXXXXXycbnmXXXXXXXXXXXXXXXXXXXXXXX"
dev = InputDevice('/dev/input/event0')

pygame.init()
windowSurface = pygame.display.set_mode ((1024, 600), pygame.NOFRAME)
img = pygame.image.load("/home/pi/Access/New Phone Wallpaper copy.jpg")
pygame.mouse.set_cursor((8,8),(0,0), (0,0,0,0,0,0,0,0), (0,0,0,0,0,0,0,0))
windowSurface.blit(img, (0,0))
pygame.display.flip()
pygame.event.clear()

while True:
        r,w,x = select([dev], [],[])
        for event in dev.read():
                if event.type==1 and event.value==1:
                    if event.code==28:
                        rfid_presented=input()
                        e = rfid_presented
                        if check_if_string_in_file("/home/pi/Access/Loaded_Cards.txt", e):
                            videoPath = "/home/pi/Access/18 Test_1.mp4"
                            omx = run(["omxplayer", '--win', '1,1,1024,600', videoPath])
                            GPIO.setmode(GPIO.BCM)
                            GPIO.setwarnings(False)
                            GPIO.setup(26, GPIO.OUT, initial=GPIO.LOW)
                            GPIO.output(26, GPIO.HIGH)
                            time.sleep(0.5)
                            GPIO.output(26, GPIO.LOW)

                        else:
                            rfid_presented = ""

else:
            rfid_presented += keys[event.code]
del e
root.mainloop()
#main()


texts:
I wrote a little wrapper for Google Static Maps API so that I do not pull down from Google Maps if I have already retrieved the address. The below code works, but I wrote it in a quick fashion - not really paying attention to the best practices of golang.

Several questions I have about this code:
 - How can I improve the v := url.Values{} section?
 - Is there a better method to the for i := 0; i < 30; i++ loop?

package main

import (
    "crypto/md5"
    "encoding/hex"
    "errors"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "os"
)

var apiKey = os.Getenv("API_KEY")

// loadMap generates a new map or returns a cached one
func loadMap(address string, title string) ([]byte, error) {
    mapHost := "http://maps.googleapis.com/maps/api/staticmap"

    v := url.Values{}
    v.Add("center", address)
    v.Add("zoom", "15")
    v.Add("scale", "2")
    v.Add("size", "400x350")
    v.Add("markers", address)
    v.Add("sensor", "false")
    v.Add("key", apiKey)
    mapURL := mapHost + "?" + v.Encode()

    filename := title + ".png"
    for i := 0; i < 30; i++ {
        body, err := ioutil.ReadFile(filename)
        if err == nil {
            return body, nil
        }

        if i == 0 {
            fmt.Println("Getting map for " + address + " and saving it to " + filename)
            fmt.Println("Map URL: " + mapURL)
            httpClientGetMap, _ := http.Get(mapURL)
            body, _ := ioutil.ReadAll(httpClientGetMap.Body)
            ioutil.WriteFile(filename, []byte(body), 0600)
        }

        i++
    }

    return nil, errors.New("Failed to get an image")
}

// viewHandler returns the map image
func viewHandler(w http.ResponseWriter, r *http.Request) {

    address := r.URL.Query().Get("address")

    md5 := md5.Sum([]byte(address))
    title := hex.EncodeToString(md5[:])
    p, err := loadMap(address, title)

    if err != nil {
        fmt.Println(err)
        w.WriteHeader(http.StatusGatewayTimeout)
        return
    }

    w.Header().Set("content-type", "image/png")
    w.Write(p)
}

func main() {
    http.HandleFunc("/getmap", viewHandler)

    http.ListenAndServe(":8080", nil)
}


texts:
I made this little library that makes the title of a webpage scroll so you can see the entire string. I'm not sure if this is the best way to accomplish this so if anyone has any input that'd be great.

title-scroll.js

var start = 3000;
var speed = 250;

function getParams(startAttr, speedAttr) {
    var params = window.document.getElementsByTagName('script');

    for (var i = 0; i < params.length; i++) {
        if (params[i].src.indexOf('title-scroll.js') !== -1) {
            if (params[i].getAttribute(startAttr) !== null && params[i].getAttribute(startAttr) !== "") {
                start = params[i].getAttribute(startAttr);
            }

            if (params[i].getAttribute(speedAttr) !== null && params[i].getAttribute(speedAttr) !== "") {
                speed = params[i].getAttribute(speedAttr);
            }

            return;
        }
    }
}

window.onload = function(e) {
    getParams('data-start', 'data-speed');
    var title_ref = window.document.getElementsByTagName('title')[0];
    var title = title_ref.text;
    var i = 0;

    setTimeout(function() {
        setInterval(function () {
            title_ref.text = title.substr(i, title.length) + "  ---  " + title.substr(0, i);
            i++;

            if (i === title.length) {
                i = 0;
            }
        }, speed);
    }, start);
}

HTML to properly load the file

<script src="title-scroll.js" data-start="3000" data-speed="250"></script>

Edit:

data-start: Time between page load and when the title starts to scroll.

data-speed: Time between each character movement.


texts: A safer way to return a generic indicator object indicating failure

texts:
I'm writing a singly-linked list that implements the List interface. I decided going in that I'd try to implement every method as an exercise; even the optional ones.

I started writing the ListIterator, and found the need to return the node previous to a given node for operations like add. Unfortunately, I didn't anticipate this scenario prior to writing the rest of the list, and have no way of indicating failure (failure being that the given node doesn't exist in the list), since null is a valid return if the root node is supplied. I decided to allow the caller to pass in an indicator node that would be returned if the node wasn't found. I wasn't sure the best way to handle this thought, since Node is generic.

I ended up making the indicator of type Node<Object>, and casting it prior to returning. I know this is dangerous though, so I made it very clear in the documentation that the method isn't safe (plus, of course, it's private).

I'd like to know if there's a less hack-ish way of dealing with this scenario though.

I didn't think including the full implementation was necessary. The names should be obvious enough (I hope).

/**
 * Dangerous.
 * Returns the node that comes before the given node, or badNode if the
 *  node doesn't exist in the list.
 * The return must be checked against badNode prior to use!
 *
 * @param node The node to find the predecessor of
 * @param badNode The indicator that will be returned if node isn't in the list
 * @return The predecessor of node, or badNode if node doesn't exist.
 */
@SuppressWarnings("unchecked")
private Node<E> getNodeBefore(Node<E> node, Node<Object> badNode) {
    Node<E> curNode = getRootNode();
    Node<E> prevNode = null;

    while (curNode != null) {
        if (curNode == node) {
            return prevNode;
        }

    prevNode = curNode;
    curNode = curNode.getNextNode();
    }

    return (Node<E>)badNode;
}


texts: Displaying Video file from storage with MediaStore in android Java

texts:
I Used MediaStore to scan and display media files from my storage using below code
private void displayAllVideos() {
    Uri uri;
    Cursor cursor;
    VideoAdapter videoAdapter;
    int column_index_data,thum;

    String absolutePathThumb;
    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};

    final String orderBy = MediaStore.Video.Media.DATE_ADDED + " DESC";
    cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy);
    column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);

    while (cursor.moveToNext()){
        Log.d("VIDEO", cursor.getString(0));
        absolutePathThumb = cursor.getString(column_index_data);
        Uri thumbUri = Uri.fromFile(new File(absolutePathThumb));
        //String cursorThumb = cursor.getString(thum);
        String fileName = FilenameUtils.getBaseName(absolutePathThumb);
        String extension = FilenameUtils.getExtension(absolutePathThumb);
        String duration = getDuration(absolutePathThumb);
        VideoModel videoModel = new VideoModel();
        videoModel.setDuration(duration);
        videoModel.setVideo_uri(thumbUri.toString());
        videoModel.setVideo_path(absolutePathThumb);
        videoModel.setVideo_name(fileName);
        videoModel.setVideo_thumb(cursor.getString(thum));
        if (extension!=null){
            videoModel.setVideo_extension(extension);
        }else {
            videoModel.setVideo_extension("mp4");
        }
        if (duration!=null){
            videoModel.setDuration(duration);
        }else {
            videoModel.setDuration("00:00");
        }
        arrayListVideos.add(videoModel);
    }

with above code i can able to get and display video file, Is there anything i need to improve in my code.
Your help in need thanks in advance.android


texts:
I'm aware standard delegate method declaration should include the object that triggers the method, usually of the class that declared the protocol.

That's fine when the delegate method includes further arguments down the line, but what if it doesn't?

Example:

@protocol MyObjectDelegate <NSObject>

- (void)myObject:(id)object didPerformActionWithResult:(NSObject*)resul;
- (void)myObject:(id)object didPerformActionWithoutResult;
@end

I know the second method isn't accepted, its missing an argument, but what do I put there? A BOOL that I know will always be true?

Do I change |didPerformActionWithoutResult| to performedAction:(BOOL)yesOrNo?

Or move the object reference to the end?


texts:
The following function removes text inside parenthesis, also checks for balanced brackets. Example:
RemoveTextInsideParenthesis('Yahoo (Inc)') will return 'Yahoo'
Any suggestions in how to improve readability/simplify it?

def RemoveTextInsideParenthesis(text: str) -> str:
  """Remove text inside brackets or nested brackets.

  Creates an array: ['(',')'...], then for each character in text string
  we compare if character is a bracket, if it is we update a status array.
  Based on status array we can evaluate if brackets are open and close correctly
  and then capture text outside parenthesis.
  Using divmod function we extract index of brackets array.
  Take two (non complex) numbers as arguments and return a pair of numbers
  consisting of their quotient and remainder.
  Documentation for brackets:
  https://www.unicode.org/charts/nameslist/n_2000.html

  Args:
    text: Text to be clean up.

  Returns:
    Text inside parenthesis
  """

  openers = (u'(<[{\u0f3a\u0f3c\u169b\u2045\u207d\u208d\u2329\u2768'
             u'\u276a\u276c\u276e\u2770\u2772\u2774\u27c5\u27e6\u27e8\u27ea'
             u'\u27ec\u27ee\u2983\u2985\u2987\u2989\u298b\u298d\u298f\u2991'
             u'\u2993\u2995\u2997\u29d8\u29da\u29fc\u2e22\u2e24\u2e26\u2e28'
             u'\u3008\u300a\u300c\u300e\u3010\u3014\u3016\u3018\u301a\u301d'
             u'\u301d\ufd3e\ufe17\ufe35\ufe37\ufe39\ufe3b\ufe3d\ufe3f\ufe41'
             u'\ufe43\ufe47\ufe59\ufe5b\ufe5d\uff08\uff3b\uff5b\uff5f\uff62'
             u'\xab\u2018\u201c\u2039\u2e02\u2e04\u2e09\u2e0c\u2e1c\u2e20'
             u'\u201a\u201e\xbb\u2019\u201d\u203a\u2e03\u2e05\u2e0a\u2e0d'
             u'\u2e1d\u2e21\u201b\u201f')
  closers = (u')>]}\u0f3b\u0f3d\u169c\u2046\u207e\u208e\u232a\u2769'
             u'\u276b\u276d\u276f\u2771\u2773\u2775\u27c6\u27e7\u27e9\u27eb'
             u'\u27ed\u27ef\u2984\u2986\u2988\u298a\u298c\u298e\u2990\u2992'
             u'\u2994\u2996\u2998\u29d9\u29db\u29fd\u2e23\u2e25\u2e27\u2e29'
             u'\u3009\u300b\u300d\u300f\u3011\u3015\u3017\u3019\u301b\u301e'
             u'\u301f\ufd3f\ufe18\ufe36\ufe38\ufe3a\ufe3c\ufe3e\ufe40\ufe42'
             u'\ufe44\ufe48\ufe5a\ufe5c\ufe5e\uff09\uff3d\uff5d\uff60\uff63'
             u'\xbb\u2019\u201d\u203a\u2e03\u2e05\u2e0a\u2e0d\u2e1d\u2e21'
             u'\u201b\u201f\xab\u2018\u201c\u2039\u2e02\u2e04\u2e09\u2e0c'
             u'\u2e1c\u2e20\u201a\u201e')

  # Interleave openers and closers: ['(',')'...]
  brackets = [value for pair in zip(openers, closers) for value in pair]
  count = [0] * (len(brackets) // 2)  # Count open/close brackets as array.
  clean_string = []
  for character in text:
    for i, bracket in enumerate(brackets):
      if character == bracket:  # Found a bracket in text.
        # Take index(i) of brackets and 2 as arguments, return a tuple
        # consisting of their quotient and remainder (a, b).
        # When index is even, reminder = 0 is an open bracket.
        # ['(',')','[',']',...] = [0, 1, 2, 3,...]
        bracket_kind, is_close = divmod(i, 2)
        # Keep track of brackets in string via count array by adding 1 when an
        # open bracket is seen or substracting 1 when is closed.
        # (-1)**0 = 1, (-1)**1 = -1. Balanced brackets, sum will be 0.
        count[bracket_kind] += (-1)**is_close
        if count[bracket_kind] < 0:  # Unbalanced bracket.
          count[bracket_kind] = 0
        break
    else:  # Character is not a bracket.
      if not any(count):  # Outside brackets.
        clean_string.append(character)
  # Return text outside brackets or text if after removing brackets is empty.
  return ''.join(clean_string).strip() if clean_string else text.strip()


texts:
I wanted to ask this here because what I wanted to originally do felt like a really Pythonic method. I want to be able to use the syntax:

d = {'apple':{'cranberry':{'banana':{'chocolate':[1,2,3,4,5,6]}}},'b':2}
with d['apple']['cranberry']['banana']['chocolate'] as item:
    for i in item:
        print(i)

    item.append('k')

but found that Python doesn't allow for using lists, dicts, etc. as context managers.

So I implemented my own:

def context_wrap(target):
    class ContextWrap:
        def __init__(self, tgt):
            self._tgt = tgt

        def __enter__(self):
            return self._tgt

        def __exit__(self, type, value, traceback):
            pass

    return ContextWrap(target)

if __name__ == '__main__':
    with context_wrap({'a':1}) as item:
        print(item['a'])

    with context_wrap([1,2,3,4,5]) as item:
        print(item[1])

    with context_wrap(3) as item:
        print (item)

In the above code, you can take any random object and wrap it inside an object that acts as a context manager controlling the underlying object. This means that inside any with clause, you can simply use the object with it's alias. I feel like it looks a lot cleaner and clearer than something like:

alias = d['apple']['cranberry']['banana']['chocolate']
for i in alias:
    print(i)

alias.append('k')

I wanted to know if there was a more "Pythonic" way to do it. So the improvement that I'm looking for is in terms of better reliance on the standard Python library and/or in terms of my syntax.


texts: Python program to get the longest substring of the same character

texts:
Given a word the program outputs the length of the longest substring with the same letters. For example:

long_repeat('sdsffffse') == 4
long_repeat('ddvvrwwwrggg') == 3
long_repeat('abababaab') == 2
long_repeat('') == 0

The code is:

def long_repeat(line):

    substrings = []
    current_substring = ""
    for i, letter in enumerate(line):
        if i == 0:
            current_substring = letter
        else:
            if letter == current_substring[len(current_substring) - 1]:
                current_substring += letter
                if(i == len(line)- 1):
                    substrings.append(current_substring)
            else:
                substrings.append(current_substring)
                current_substring = letter

    lengths = []
    for substring in substrings:
        lengths.append(len(substring))

    if len(lengths) > 0:
        return  max(lengths)
    else:
        return 0

What could be improved?


texts:
I was referring to the book Computational Physics by Nicholas J. Giordano and was studying the simple Random Walk model. (Pg. 169 - 173)

I consider a 3D Random Walk where the probability of moving in the positive direction is p and in the negative direction is q, in all the 3 coordinates and p + q = 1. In my model I assume:

$$ p_x=q_x =0.5,\space p_y=q_y=0.5 \space and \space p_z=q_z=0.5$$
$$l_x = l_y=l_z=\pm 1$$

where l is the step length. In my program I consider total number of walkers = N and total number of random steps taken by each walker is s. My goals are:

Plot a scatter plot : $$<x_s^2> \space vs. \space t$$
Find the slope from the regression line.

Here is my R code:

randomWalk <- function(N, s) {
  S <- 1:s
  av <- numeric(s)
  for (r in 1:N) {
    x <- 0
    y <- 0
    z <- 0
    for (i in 1:s) {
      if (runif(1)<0.5) x <- x+1
      else x <- x-1
      if (runif(1)<0.5) y <- y+1
      else y <- y-1
      if (runif(1)<0.5) z <- z+1
      else z <- z-1
      av[i] <- av[i] + (x^2+y^2+z^2)
    }
  }
  av <- av/N
  plot(S, av,xlab="No. of steps(t)", ylab="<r^2>", main="Random Walk",cex=0.4, pch=15)
  abline(lm(av~(S)-1))
  print(lm(av~(S)-1))
}
randomWalk(500, 100)

In the code I consider N=500 and s=100.

The plot I get is

with value of slope approximately 3. But in page 173 there is a plot with the same condition but slope approximately 1.

My question is, Is there something wrong with my code or am I misunderstanding the plot given in page 173? A review will be helpful.


texts:
I have a REST library. These are the abstractions. Have I missed anything that a developer would need to use this in a dependency injection / IoC Container scenario? Anything that bothers you about this?

All Code Here

public interface IRestClient
{
    IRestHeadersCollection DefaultRequestHeaders { get; }
    TimeSpan Timeout { get; set; }
    Task DeleteAsync(Uri queryString);
    Task DeleteAsync(Uri queryString, CancellationToken cancellationToken);
    Task<RestResponse<TReturn>> GetAsync<TReturn>();
    Task<RestResponse<TReturn>> GetAsync<TReturn>(Uri queryString);
    Task<RestResponse<TReturn>> GetAsync<TReturn>(Uri queryString, CancellationToken cancellationToken);
    Task<RestResponse<TReturn>> PatchAsync<TReturn, TBody>(TBody body, Uri queryString);
    Task<RestResponse<TReturn>> PatchAsync<TReturn, TBody>(TBody body, Uri queryString, CancellationToken cancellationToken);
    Task<RestResponse<TReturn>> PostAsync<TReturn, TBody>(TBody body, Uri queryString);
    Task<RestResponse<TReturn>> PostAsync<TReturn, TBody>(TBody body, Uri queryString, CancellationToken cancellationToken);
    Task<RestResponse<TReturn>> PutAsync<TReturn, TBody>(TBody body, Uri queryString);
    Task<RestResponse<TReturn>> PutAsync<TReturn, TBody>(TBody body, Uri queryString, CancellationToken cancellationToken);
}

public interface IRestClientFactory
{
    IRestClient CreateRestClient(Uri baseUri);
    IRestClient CreateRestClient();
}

public interface IRestHeadersCollection : IEnumerable<KeyValuePair<string, IEnumerable<string>>>
{
    void Add(string name, string value);
    void Add(string name, IEnumerable<string> values);
    void Clear();

    IEnumerable<string> this[string name]
    {
        get;
    }

    bool Contains(string name);
}

public partial interface ISerializationAdapter
{
    /// <summary>
    /// Takes an object of Type T and converts it to binary data
    /// </summary>
    Task<byte[]> SerializeAsync<T>(T value);

    /// <summary>
    /// Takes binary data and converts it to an object of type T
    /// </summary>
    Task<T> DeserializeAsync<T>(byte[] data);
}

public interface ITracer
{
    void Trace(HttpVerb httpVerb, Uri baseUri, Uri queryString, byte[] body, TraceType traceType, int? httpStatusCode, IRestHeadersCollection restHeadersCollection);
}

public class RestResponse<TBody> : RestResponse
{
    public TBody Body { get; }

    public RestResponse(TBody body, IRestHeadersCollection restHeadersCollection, int statusCode, object underlyingResponse) : base(restHeadersCollection, statusCode, underlyingResponse)
    {
        Body = body;
    }

    #region Implicit Operator
    public static implicit operator TBody(RestResponse<TBody> readResult)
    {
        return readResult.Body;
    }

    public TBody ToTBody()
    {
        return Body;
    }
    #endregion
}

public class RestResponse
{
    #region Public Properties
    public int StatusCode { get; }
    public object UnderlyingResponse { get; }
    public IRestHeadersCollection Headers { get; }
    #endregion

    #region Constructor
    public RestResponse(IRestHeadersCollection restHeadersCollection, int statusCode, object underlyingResponse)
    {
        StatusCode = statusCode;
        UnderlyingResponse = underlyingResponse;
        Headers = restHeadersCollection;
    }
    #endregion
}

Originally I thought it might be useful to allow task async calls for serialization/deserialization but I've come to think that this is a bit redundant... Any thoughts on this?


texts:
I have been following the advice to make tiny methods that does just one thing and does it well. I also have been keen on reducing or eliminating duplication as much as possible.

But when a very experienced developer friend reviewed my code, he mentioned I was taking it too far. And, in short, my code was unreadable as it jumped too much killing the flow. Though I too feel I am pretty bad in naming my methods, I feel such tiny methods are helping me break down the problem and letting me solve it easily.

Challenge: Matrix Rotation (Move each matrix element to the neighboring position along concentric rectangular paths. The dimensions of the matrix are guaranteed to be even.)

Solution: matrix_rotator.rb

class Matrix
  def initialize(two_d_array: nil)
    @data = two_d_array
  end

  def rotate!(anti_clockwise: 0)
    rotated = layers
      .map { |layer| layer.map { |row, column| @data[row][column] } }
      .map { |layer| layer.rotate(anti_clockwise) }

    coordinates.zip(rotated.flatten).each do |(row, column), n|
      @data[row][column] = n
    end

    self
  end

  def to_s
    @data
      .map { |row| row.join(' ') }
      .join("\n")
  end

  def coordinates
    layers.each_with_object([]) { |layer, a| a.push(*layer) }
  end

  def height
    @height ||= @data.length
  end

  def width
    @width ||= @data.first.length
  end

  def layers
    number_of_layers.times.map do |index|
      top(index) + right(index) + bottom(index) + left(index)
    end
  end

  def horizontal_segment(index)
    (width - (2 * index) - 1).times
  end

  def vertical_segment(index)
    (height - (2 * index) - 1).times
  end

  def top(index)
    horizontal_segment(index)
      .map { |w| [index, w + index] }
  end

  def right(index)
    vertical_segment(index)
      .map { |h| [h + index, width - index - 1] }
  end

  def bottom(index)
    horizontal_segment(index)
      .map { |w| [height - index - 1, width - index - w - 1] }
  end

  def left(index)
    vertical_segment(index)
      .map { |h| [height - 1 - index - h, index] }
  end

  def number_of_layers
    [height, width].min / 2
  end
end

class MatrixRotator
  def initialize(source: nil)
    parse(source.readlines)
  end

  def result
    Matrix
      .new(two_d_array: two_d_array)
      .rotate!(anti_clockwise: @shift)
      .to_s
  end

  def parse(lines)
    parameters, *@content = lines.map(&:strip)
    @shift = parameters.split.map(&:to_i).last
  end

  def two_d_array
    @content.map { |line| line.split.map(&:to_i) }
  end
end

puts MatrixRotator.new(source: STDIN).result


texts: Add 5 strong types to an object as properties

texts:
This is a small object that allows you to pass an obj and a property name using its helper functions to create a typed var that won't save a value to the property if it isn't the right type.

This was just for fun, and I am interested on getting some feedback on what I could have done better/cleaner.

/* JSTypes is the constructor to append all prototype methods to and can be invoked using the new keyword
 * * * */

function JSTypes(){}

/* validType this replaces the setter method of the object and makes sure it is valid before returning it.
 *    @if   valid type then return the type
 *    #else console.error return the original type
 * * * */

JSTypes.prototype.validType = function(val, original, type){
  if(typeof(val) === type)
    return val;
  console.error('must be passed a type of ' + type + ' instead was passed: ' + typeof(val));
  return original;
};

/* plainGet will just return the value of the property.  This can be replaced by any sort of
 *          validation function before returning the value
 * * * */

JSTypes.prototype.plainGet = function(val, original, type){
  return val;
};

/* Currently only five supported types. Number, String, Object, Booleal, and Undefined
 *
 * * * */

JSTypes.prototype.num = function(obj, name){
  JSTypes.prototype.setProp(obj, name, JSTypes.prototype.validType, JSTypes.prototype.plainGet, 'number');
};

JSTypes.prototype.str = function(obj, name){
  JSTypes.prototype.setProp(obj, name, JSTypes.prototype.validType, JSTypes.prototype.plainGet, 'string');
};

JSTypes.prototype.obj = function(obj, name){
  JSTypes.prototype.setProp(obj, name, JSTypes.prototype.validType, JSTypes.prototype.plainGet, 'object');
};

JSTypes.prototype.bool = function(obj, name){
  JSTypes.prototype.setProp(obj, name, JSTypes.prototype.validType, JSTypes.prototype.plainGet, 'boolean');
};

JSTypes.prototype.und = function(obj, name){
  JSTypes.prototype.setProp(obj, name, JSTypes.prototype.validType, JSTypes.prototype.plainGet, function(){}());
};

/* setProp will append a property name to a passed object and call get and set callbacks
 *         when a value is requested or assigned to it
 *
 *         The object will never publicly have this value as it is hidden in the closure
 *         of the invoking function. As long as the property remains on the object this private
 *         value will be available to the program.
 * * * */

JSTypes.prototype.setProp = function(obj, name, set, get, type){

/* @propVal - Private placeholder for the actual value of the property */
  var propType = type;
  var propVal;

/* Object.defineProperty applies the property name to the object passed with options passed
 *   see MDN docs.
 * * */

  Object.defineProperty(obj, name, {

    __proto__: null,
    configurable: true,
    enumerable: true,
    writeable: true,

    /* By returning the value of their get function you can allow them
     * to validate the request to get the private variable
     * * * */

    get: function(){
      return get(propVal, propVal, type);
    },

    /* Set runs the callback functions passed
     *
     * * * */

    set: function(value){
      propVal = set(value, propVal, type);
    }
  });

};

/* Code below is example of using this object
 * * * */
var type = new JSTypes();

var Person = {};

type.num(Person, 'age');
type.str(Person, 'name');
type.obj(Person, 'friends');
type.bool(Person, 'alive');
type.und(Person, 'future');

Person.age = 12;  // valid and saves the value
console.log(Person.age) // 12
Person.age = "100" // not valid and logs an error with a stacktrace
console.log(Person.age) // still 12


texts: Finding minimal spanning tree of a graph using Kruskal's algorithm

texts:
I am doing some practice interview questions for class, one of the questions is:

  Given an undirected graph G, find the minimum spanning tree. Function should take in and output an adjacency list.

Here is the code that I have which works using Kruskal's algorithm:

### Question 3 main function and helper functions.
# Within code v = vertice, r = root, e = edge, u = union, m = make, f = find.

# Global Variables for simplifying code.
parent = dict()
rank = dict()

# Find vertices.
def f(v):
    if parent[v] != v:
        parent[v] = f(parent[v])
    return parent[v]

# Make vertices.
def m(v):
    parent[v] = v
    rank[v] = 0

# Creates union between vertices.
def u(v1, v2):
    r1 = f(v1)
    r2 = f(v2)
    if r1 != r2:
        if rank[r1] > rank[r2]:
            parent[r2] = r1
        else:
            parent[r1] = r2
            if rank[r1] == rank[r2]: rank[r2] += 1

# Main Function.
def Question3(G):
    for v in G['vertices']:
        m(v)

    edges = list(G['edges'])
    MST = set()

    for e in edges:
        v1, v2, weight = e
        if f(v1) != f(v2):
            u(v1, v2)
            MST.add(e)
    return MST

G = {
    'vertices': [0, 1, 2, 3, 4, 5, 6, 7],
    'edges': set([
        (1, 6, 5),
        (3, 5, 2),
        (5, 4, 9),
        (4, 2, 3),
        (1, 1, 8),
        (0, 2, 1),
        (2, 3, 6),
        (2, 5, 4),
        (2, 4, 9),
        (2, 1, 7),
        ])
    }

print "Minimum Spanning Tree of G:"
print Question3(G)

# Expected Output.
# Minimum Spanning Tree of G:
# set([(1, 6, 5), (2, 4, 9), (2, 5, 4), (2, 1, 7), (2, 3, 6), (0, 2, 1)])
print """---End Question 3---
"""

Are there any unnecessary bits of code in my solution and/or is there a more efficient way I could be going about this problem?


texts: Find the sum along root-to-leaf paths of a tree

texts:
Most of you already know me, please be brutal, and treat this code as if it was written at a top tech interview company.

Question:

  Given a binary tree and a sum, find all root-to-leaf paths where each
  path's sum equals the given sum.

  For example: Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

  return

[
   [5,4,11,2],
   [5,8,4,5]
]

Time taken: 26 minutes (all 110 test cases passed)

Worst case: \$O(n^2)\$?
Since when I add to resList, it copies all the elements again which can take \$O(n)\$ and I traverse \$O(n)\$ nodes.

Space complexity: \$O(n)\$

My code:

ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> curList = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
    if(root==null){
        return res;
    }
    curList.add(root.val);
    if(root.left==null && root.right==null){
        if(sum - root.val==0){
            res.add(new ArrayList<Integer>(curList));
        }
    }
    if(root.left!=null){
        pathSum(root.left, sum-root.val);
    }
    if(root.right!=null){
        pathSum(root.right, sum-root.val);
    }
    curList.remove(new Integer(root.val));
    return res;
}


texts:
I am new to python, I made a calculator but I need to make it calculating unlimited numbers and to shorten the code more, how can I improve it?
Any help is appreciated.
while(True):
    print()
    try:
        nums = int(input("How many numbers you want to calculate?\n"))
    # x = float(input("Enter the first number: "))
    # y = float(input("Enter the second number: "))
    # z = float(input("Enter the third number: "))
    # w = float(input("Enter the forth number: "))
    # v = float(input("Enter the fifth number: "))

        if nums == 2:
            x = float(input("Enter the first number: "))
            y = float(input("Enter the second number: "))
            print()
            func = int(input('''What do you want to do?
            1 to add
            2 to subtract
            3 to multiply
            4 to divide
            '''))
            if func == 1:
                print(x+y)
            if func == 2:
                print(x-y)
            if func == 3:
                print(x*y)
            if func == 4:
                print(x/y)
        if nums == 3:
            x = float(input("Enter the first number: "))
            y = float(input("Enter the second number: "))
            z = float(input("Enter the third number: "))
            print()
            func = int(input('''What do you want to do?
            1 to add
            2 to subtract
            3 to multiply
            4 to divide
            '''))
            if func == 1:
                print(x+y+z)
            if func == 2:
                print(x-y-z)
            if func == 3:
                print(x*y*z)
            if func == 4:
                print(x/y/z)
        if nums == 4:
            x = float(input("Enter the first number: "))
            y = float(input("Enter the second number: "))
            z = float(input("Enter the third number: "))
            w = float(input("Enter the forth number: "))
            print()
            func = int(input('''What do you want to do?
            1 to add
            2 to subtract
            3 to multiply
            4 to divide
            '''))
            if func == 1:
                print(x+y+z+w)
            if func == 2:
                print(x-y-z-w)
            if func == 3:
                print(x*y*z*w)
            if func == 4:
                print(x/y/z/w)
        if nums == 5:
            x = float(input("Enter the first number: "))
            y = float(input("Enter the second number: "))
            z = float(input("Enter the third number: "))
            w = float(input("Enter the forth number: "))
            v = float(input("Enter the fifth number: "))
            print()
            func = int(input('''What do you want to do?
            1 to add
            2 to subtract
            3 to multiply
            4 to divide
            '''))
            if func == 1:
                print(x+y+z+w+v)
            if func == 2:
                print(x-y-z-w-v)
            if func == 3:
                print(x*y*z*w*v)
            if func == 4:
                print(x/y/z/w/v)
        if nums > 5:
            print("The calculator handles 5 numbers maximum!")
    except(ZeroDivisionError):
        print("You can never divide by Zero!")
    except(ValueError):
        print("Check your input.")