texts:
Link To Question

Given a string, return a version without the first and last char, so
"Hello" yields "ell". The string length will be at least 2.
without_end('Hello') → 'ell'
without_end('java') → 'av'
without_end('coding') → 'odin'

This is the code I wrote as a solution to this problem. I feel that this simple of a problem can be written in one line, but I can baffled as to how I can do so; after many attempts. Any and all feedback is appreciated and considered so I can further improve my python practices.
def without_end(str):

  if len(str) <= 2:
    return ""

  no_start = str[1:]
  no_end = no_start[:len(no_start) - 1]

  return no_end


texts:
Currently I will be downloading around ~100K images. This process may run on a weekly basis, I'm considering the following factors:

HTTP Requests (Will be taken care by external LB, so same source IP won't be used)
Multi-threading (concurrent.futures.ThreadPoolExecutor library to handle multi-threading)
Writing requests (Regular open and close methods)

I'm using urllib2 to handle HTTP requests, I would like to see if this properly designed to run at scale.

Any additional comments? Suggestions?

import concurrent.futures
import urllib2
import pandas as pd

MAX_WORKERS = 5
EXECUTOR_TIMEOUT = 60
FILENAME = 'files.csv'
_IMG_EXTENSION = 'jpg'

class Image():
    def __init__(self, master_id, url):
        self.master_id = master_id
        self.url = url

def get_file(filename):
    """Get dataframe information"""
    data = pd.read_csv(filename)
    data = data.drop_duplicates(subset=['id'], keep='first')
    subset = data.head()
    return subset

# Data extraction
def extract_data(data):
    """Extract data"""
    image_list = []
    for _, url in data.iterrows():
        print url[0], url[1]
        image_list.append(Image(url[0], url[1]))
    return image_list

# Retrieve a single page and report the url and contents
def load_url(image, timeout):
    """Load URL"""
    response = urllib2.urlopen(image.url, timeout=timeout)
    return response.read()

# Save image
def save_image(image_data, filename):
    """Save Image."""
    with open(str(filename) + '.' + _IMG_EXTENSION, 'wb') as output:
        output.write(image_data)
        output.close()

def download_data(image_list):
    # We can use a with statement to ensure threads are cleaned up promptly
    with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        # Start the load operations and mark each future with its URL
        future_to_url = {executor.submit(load_url, image, EXECUTOR_TIMEOUT): image for image in image_list}
        for future in concurrent.futures.as_completed(future_to_url):
            image = future_to_url[future]
            try:
                image_data = future.result()
            except Exception as exc:
                print('%r Generated an exception: %s' % (image.url, exc))
            else:
                print('%r Page is %d bytes' % (image.url, len(image_data)))
                save_image(image_data, image.master_id)


texts:
I'm designing a security camera program.  Right now, I am just trying to set up the GUI before receiving. I am using Kivy since, in the future, I plan on designing some programs for Android.  I really like Python, and I figured I'd start learning Kivy.

My question is: am I building the GUI structure correctly?

The layout I have planned is for the core container to have a BoxLayout that will hold three containers:

The first container is on the left and will hold buttons to perform various commands.
The second container will be in the center and will hold all the video feeds.
The third container will be on the right and its purpose is still being considered.

import kivy
from kivy.config import Config
Config.set('graphics', 'fullscreen', 'auto')
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout

class camMonitor(BoxLayout):

    def __init__(self, **kwargs):
        super(camMonitor, self).__init__(**kwargs)
        self.add_widget(controlInterface())

class controlInterface(BoxLayout):

    def __init__(self, **kwargs):
        super(controlInterface, self).__init__(**kwargs)
        button1 = Button(text='action 1', size =(50,30), size_hint=(None,None))
        self.add_widget(button1)

class camMonApp(App):

    def build(self):
        return camMonitor()

if __name__ == '__main__':
    camMonApp().run()

For each container, I have created a separate class. Not every class will be a box layout; that's just what I have it set to at the moment.

Should I continue building the GUI the way it is now, or should everything be put into one class?


texts:
Project Euler #5:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Here is my solution:
class SmallestMultiple {

    private static final int MAX = 20;

    public static void main(String[] args) {
        long time = System.nanoTime();
        int result = 1;
        for(int i = 1; i <= MAX; i++) {
            result = smallestMultiple(result, i);
        }
        time = System.nanoTime() - time;
        System.out.println("Result: " + result + "\nTime used to calculate in nanoseconds: " + time);
    }

    private static int smallestMultiple(int i, int j) {
        for(int index = 2; index <= i && index <= j; index++) {
            if(i % index == 0 && j % index == 0) {
                i /= index;
            }
        }
        return i * j;
    }

}

Output:

Result: 232792560
Time used to calculate in nanoseconds: 11603

Questions:

Is is as efficient as it can be? If not, how can I improve it?
Does it smell?


texts:
I'm new here, and relatively new to coding. I wrote a method that returns an array of the n first primes. Even though my intended goal was just to find the nth prime, I ended up using an array (int[] primes) in order to minimize calculations.

My method goes iterates upwards by 2, since even numbers greater than 2 are not primes, and testing if the candidate number is a multiple of the previous primes (of course not including 2) that have been found up until the test.

Actually it does not do that test with all the previous primes, only up to the square root of the last prime found. You can take a look at my method.

public int[] primes(int n){

    int[] primes = new int[n];
    primes[0] = 2;

    int count = 1;
    int number = 3;

    boolean numberIsPrime;

    while (count < n){

        numberIsPrime = true;

        for (int i = 1; i < (int)(Math.sqrt(number)); i++) {

            if (number % primes[i] == 0){
                numberIsPrime = false;
                break;
            }

        }

        if (numberIsPrime){

            primes[count] = number;
            count++;
        }

        number = number + 2;

    }

    return primes;

}

I tested it in a main method through System.out.println(instance.primes(n)[n-1]); for n = 1 million and it took not more than 10 seconds to find the correct answer, and for n = 10 million it took no more than 4 and a half minutes to find the correct answer.

I let it run for n = 100 million, since I started writing this question, and it doesn't look like it is going to finish for an hour or so. I think mathematically I reduced calculations a lot.

Just by decreasing the test to the square root of the last prime did reduce computing time quite much.

But can it be improved, not only mathematically but also by means of code?


texts:
I have a program that makes operations on strings and this is the principal function of one of those operations.  This works perfectly, but it is not efficient:

private void printString(ArrayList<String> operations, ArrayList<String> set) {
    int numerOfStrings = 0;
    int numberOfletters = 0;
    String toPrint = operations.get(1);
    outOfLoop: for (int i = 0; i < set.size(); i++) {
        String[] toFind = set.get(i).split(" ");
        for (int k = 0; k < toFind.length; k++) {
        if (toPrint.equals(toFind[k])) {
            String[] splited = set.get(i).split(" ");
            for (int j = 0; j < splited.length; j++) {
            numberOfletters += splited[j].length();
            }
            numerOfStrings = splited.length;
            break outOfLoop;
        }
      }
    }
    System.out.println(numerOfStrings + " " + numberOfletters);
}

Explanation:

This function takes as parameter an arrayList of operations, and an arrayList of set:

For the arrayList of operations, I get always a specific position, so I don't iterate.  It is always \$O(1)\$.
For the arrayList of set, I have to iterate, or rather, as I think of that to proceed:

For example, if have as operation print foo, I have to do these steps:

First of all, I have to find where foo is:

Inside set, I can have this situation:

position 1 : {car tree hotel}
...
position n : {foo lemon coffee}

When I find the string foo, I have to print the number of strings inside that position and the number of letters of each string, so in this case, I will print:

3(number of strings) 14(sum of number of letters)

My program works as well as this function, but it is a nasty and inefficient solution.  How can I improve the efficiency of my program?


texts: Fast alternative for String.split by whitespace

texts:
After profiling of one project I've found a bottleneck in the code, specifically the line:

String columns[] = line.split("\\s+");

I've tried to find a workaround, but all ready made solutions, such as StringTokenizer and Scanner seem to be less efficient (for example, look at the answer on SO). So I decided to write a custom function.

private List<String> fastSplitWS(final String text)
{
  final List<String> result = new ArrayList<String>();

  if(text != null)
  {
    final int n = text.length();
    if(n > 0)
    {
      int index1 = 0;
      char x = 0;
      boolean y = false; // "preceding char is separator" flag
      for(int i = 0; i < n; i++)
      {
        x = text.charAt(i);

        if(x == '\t' || x == ' ') // if((x >= 9 && x <= 13) || x == ' ')
        {
          if(!y)
          {
            String token = text.substring(index1, i);
            result.add(token);
          }
          index1 = i + 1;
          y = true;
        }
        else
        {
          y = false;
        }
      }

      if(index1 < n - 1)
      {
        result.add(text.substring(index1));
      }
    }
  }

  return result;
}

The problem is that the code performs even worse than String.split() although I don't see how to improve it. According to profiler, most problematic parts are:

self (lines of the plain code in this method) - 58%
String.charAt - 21%
String.subString - 12%
ArrayList.add - 7%

Could someone suggest how to optimize the self code?


texts:
I have been using a pattern similar to this basic structure below. Can anyone please let me know if this is a correct way to code an object-oriented widget for reuse?  I am looking to make code than can also be extended easily and modular.

$(function(){
// wrap in jquery .fn wrapper so that may be called on a
function $lider(autoplay, velocity, controls){
  var $lider = [
    // props n methods, accessible through data-slider-* attributes
    {
      settings : {
        envokeBecause : $('[data-widget~="slider"]'),
        autoplay : autoplay,
        speed : velocity,
        showControls : controls,
        slideSize : '100%',// 25% will show 4 slides if the parent container is 100% width and so on
      },
      bindings : {
        slideRail : $('[data-function~="slide-rail"]'),
        slide : $('[data-function~="slide"]'),
        nextButton : $('[data-function~="next"]'),
        prevButton : $('[data-function~="prev"]'),
        playButton : $('[data-function~="play"]'),
        pauseButton : $('[data-function~="pause"]'),
        stopButton : $('[data-function~="stop"]')
        // attach this functionality to the DOM
      },
      methods : {
        slideNext :  function(){ slideRail.animate({left: '-=100%'}, velocity)   },
        slidePrev : function(){ slideRail.animate({left: '+=100%'}, velocity)  },
        slideRestart : function(){ slideRail.animate({left: '0%'}, velocity)  },
        slideStart :  function(){ window.$liderTimer = setInterval(slideNext, velocity) },
        slidesCount : function(){ slideRail.children().size()
        }
      }
    }
  ]
  $.each($lider, function(){
    //  iterate through all of the slider objects properties
    window.SliderProps = this;
    // set slider to be accessible to the global scope
  });
  // slider props stored as vars
  var $liderHook = SliderProps.settings.envokeBecause;
  var slideRail = SliderProps.bindings.slideRail;
  var slide = SliderProps.bindings.slide;
  var play = SliderProps.bindings.playButton;
  var next = SliderProps.bindings.nextButton;
  var prev = SliderProps.bindings.prevButton;
  var pause = SliderProps.bindings.pauseButton;
  var stop = SliderProps.bindings.stopButton;
  var slideCount = SliderProps.bindings.slideRail.children().size();
  var slideCounter = 0;

  function slidePrev(){
    var slidePrev = SliderProps.methods.slidePrev();
  }
  function slideStop(){
    /*slideRail.stop(); */
    window.clearInterval( $liderTimer  )
  }
  function slideRestart(){
    var slidePrev = SliderProps.methods.slideRestart();
    slideRail.stop();
  }
  function autoPlay(){
    SliderProps.methods.slideStart();
  }
  function slideNext(){
    slideCounter++
    var slideNext = SliderProps.methods.slideNext();
    console.log(slideCounter)
    console.log(slideCount)
    if (slideCounter != slideCount){
      // offset var-1 for js index compensation
      console.log('keep slidin..')
    }
    else {
      console.log('stop!')
      slideRestart();
      slideCounter = 0;
    }
  }
  // element -> event delegation type -> function()
  slideRail.hover( slideStop )
  next.click( slideNext )
  prev.click( slidePrev )
  stop.click( slideRestart )
  pause.click( slideStop )
  play.click( autoPlay )
} // close function slider()
$lider(true, 750);
});


texts:
I did a quick google search, and it didn't show up.

I haven't noticed it posted in pylint.py, or PEP8.py.

My emacs mode doesn't warn me if my imports are listed arbitrarily...does anyone do this?

import longest.modulename.first
import medium.sizename
import short
import sys
import os

from imports import go_at_the_bottom
from length import does_matter
from still import cascading

This is typically how I do it. But after a while, the list gets big!

I think this might work better, but it's kind of ugly:

import longest.modulename.first
import medium.sizename
import os
import short
import sys

from BeautifulSoup import BeautifulSoup as BS
from BeautifulSoup import BeautifulStoneSoup as BSS #froms are sorted by import
from imports import go_at_the_bottom
from length import does_matter
from mechanize import Browser as br
from still import cascading

What's the standard for this? I like the look of the cascading imports, but I also like the utility of searching for what's being used in the script quickly.

Is there another approach to this that I didn't cover that you use?


texts: A program that uses three methods to reverse and print an array

texts:
I have this code that uses three methods to do certain tasks. One creates an array, another reverses it and the other one prints it out(it was required to use three methods). A person recommended me to upload my code here as there are a few things that need to be improved.
They said that I do not need to return arrays if I modify them in-place, and GenerateNum could allocate the array itself instead of requiring an array with the correct size to be passed. However as a beginner I didn't quite catch what they were trying to tell me to change in the code. Please help me.
using System;

class Program
{
    static void Main(string[] args)
    {
        string getnums = Console.ReadLine();
        int getnum = Convert.ToInt32(getnums);
        int[] array1 = new int[getnum];

        GenerateNum(getnum,array1);
        RevArray(array1);
        PrintArray(array1);
    }
    static int[] GenerateNum(int getnums, int[] arrayy)
    {

        for (int index = 0; index < getnums; index++)
        {
            arrayy[index] = index;
        }
        return arrayy;
    }
    static int[] RevArray(int[] arrayy)
    {
        for (int index = 0; index < (arrayy.Length)/2; index++)
        {
            int a = arrayy[index];
            arrayy[index] = arrayy[arrayy.Length - index-1];
            arrayy[arrayy.Length-index-1] = a;
        }
        return arrayy;
    }
    static void PrintArray(int[] arrayy)
    {
        Console.WriteLine(string.Join(",",arrayy));
    }
}


texts:
The Locker Problem is as followed:

Twenty bored students take turns walking down a hall that contains
a row of closed lockers, numbered 1 to 20. The first student opens all the
lockers; the second student closes all the lockers numbered 2, 4, 6, 8, 10, 12, 14,
16, 18, 20; the third student operates on the lockers numbered 3, 6, 9, 12, 15, 18:
if a locker was closed, he opens it, and if a locker was open, he closes it; and so
on. For the ith student, he works on the lockers numbered by multiples of i: if a
locker was closed, he opens it, and if a locker was open, he closes it. What is the
number of the lockers that remain open after all the students finish their walks?

I decided to take this problem the extra mile and instead allow the user determine how many students were in the hallway so the number isn't always 20. In what ways can I refactor my code?
use std::io;

fn main() {
    // false = closed
    // true = opened
    let mut lockercount = String::new();
    println!("How many students?");
    io::stdin().read_line(&mut lockercount).expect("expected int");
    let lc = lockercount.trim().parse().unwrap();
    let mut lockers = vec![false; lc];

    for i in 1..(lockers.len()+1) {
        let mut j: usize = 1;
        while i*j <= lc {
            lockers[(i*j)-1] = !lockers[(i*j)-1];
            j += 1;
        }
    }

    let mut lockernum = 1;
    println!("Opened lockers:");
    for v in lockers {
        if v == true {
            print!("{}, ", lockernum);
        }
        lockernum += 1;
    }
}


texts: Generate Letter Combinations of a Phone Number

texts:
The task: Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

and my solution:

import itertools
letters_stack = list('abcdefghijklmnopqrstuvwxyz')
keypad_dict = {}
for num in range(2, 10):
    size = 3
    if num in [7, 9]:
        size = 4
    keypad_dict[str(num)] = letters_stack[:size]
    letters_stack = letters_stack[size:]

def aux(numbers):
    if len(numbers) == 1:
        return keypad_dict[numbers[0]]
    return itertools.product(keypad_dict[numbers[0]],  iletters(numbers[1:]))

def iletters(numbers):
    assert len(numbers) > 0
    return [''.join(x) for x in aux(numbers)]

print list(iletters('234'))
# ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']


texts: Code for finding repeated entries with different data

texts:
project is the data frame. For the purpose of the code, HOUSE.NO is a column of the type character, and NO..OF.FAMILY.MEMBER is another column of the type integer. My aim was to find out the house numbers which repeated, and then find out if the no of family members reported for each of the house matched, and identify the sets for which it didn't.

x<-1
matr<-NULL
matr2<-NULL
matr3<-NULL
r<-NULL
index<-NULL
repeat{

  y<-project$HOUSE.NO[-x]==project$HOUSE.NO[x]
  if (any(y)){
    r<-which(grepl(project$HOUSE.NO[x],project$HOUSE.NO))
    if(length(r)==2){
    check<-project$NO..OF.FAMILY.MEMBER[r[1]]!=project$NO..OF.FAMILY.MEMBER[r[2]]
    if(check){matr<-c(matr,r)}
    }
    if (length(r)==3){
      check2<-length(levels(factor(project$NO..OF.FAMILY.MEMBER[c(r[1],r[2],r[3])])))>1
      if(check2){matr2<-c(matr2,r)}
    }
    if (length(r)==4){
      check3<-length(levels(factor(project$NO..OF.FAMILY.MEMBER[c(r[1],r[2],r[3],r[4])])))>1
      if(check3){
      matr3<-c(matr3,r)}}
    if (length(r)>4&project$HOUSE.NO[x]!=""){index<-c(index,r)
    }
  }
  x<-x+1
  if(x>392){
    m1<-matrix(matr, ncol=2, byrow = TRUE)
    m2<-matrix(matr2, ncol=3, byrow = TRUE)
    m3<-matrix(matr3, ncol=4, byrow=TRUE)
    break
  }
}

The extra argument while computing index is to avoid a false entry when the HOUSE.NO is "", which is true in my data frame for 3 entries. There are 393 entries, hence the final caveat before break.

The concerns are:

I am an absolute beginner in R, and the functions used here are almost all I know.
This code only finds if in the case of the same number repeated more than twice, only if the entire set has the same family members. I couldn't find the row indices of only the cases which mismatched. Currently, the output includes the entire set.
Do let me know tips on how to make this simpler. As it stands, I found this code to be quite a bit complicated.

(let me know if more details specific to the data frame/variables I am working with are needed. Or if the question is not suited to the site)

ADDENDUM

 HOUSE.NO NO..OF.FAMILY.MEMBER
1    14/274                    6
2    14/259                    6
3    14/217                    5
4    14/258                    4
5    14/306                    5
6    14/300                    8
7     14/96                    4
8    14/166                    4
9     14/69                    5
10    14/68                    2

And the expected output is just the row numbers/house.no. which fulfill the aforementioned criteria. Currently, the matrix outputs are as below. The same set is repeated in the matrix again (twice in m1, thrice in m2..etc).

 m1
      [,1] [,2]
 [1,]   20  380
 [2,]   36   68
 [3,]   37  340
 [4,]   64  191
 [5,]   36   68
 [6,]   72  329
 [7,]   88  218
 [8,]  103  199
 [9,]  111  278
[10,]  125  214
[11,]  135  387
[12,]  149  196
[13,]   64  191
[14,]  149  196
[15,]  103  199
[16,]  125  214
[17,]  215  320
[18,]   88  218
[19,]  248  317
[20,]  111  278
[21,]  310  350
[22,]  248  317
[23,]  319  324
[24,]  215  320
[25,]  319  324
[26,]   72  329
[27,]   37  340
[28,]  310  350
[29,]   20  380
[30,]  135  387
> m2
      [,1] [,2] [,3]
 [1,]   43  258  354
 [2,]   65  219  269
 [3,]  169  322  323
 [4,]   65  219  269
 [5,]   43  258  354
 [6,]   65  219  269
 [7,]  169  322  323
 [8,]  169  322  323
 [9,]   43  258  354
> m3
      [,1] [,2] [,3] [,4]
 [1,]    2   84  211  347
 [2,]    2   84  211  347
 [3,]   99  100  101  363
 [4,]   99  100  101  363
 [5,]   99  100  101  363
 [6,]  180  185  260  263
 [7,]  180  185  260  263
 [8,]    2   84  211  347
 [9,]  180  185  260  263
[10,]  180  185  260  263
[11,]    2   84  211  347
[12,]   99  100  101  363


texts: Convenient way to make an UIImageView ExpressibleByStringLiteral

texts:
I want to reduce boiler-plate code and write like this when developing in iOS:

let imgView: UIImageView = "share_fareware_text_bg"

Here is implementation code:

class ImageView: UIImageView, ExpressibleByStringLiteral{
    public convenience required init(stringLiteral value: String) {
        self.init(image: UIImage(named: value))
    }
}

Then I can call:

let imgView: ImageView = "share_fareware_text_bg"

Is there any better way to do it more naturally?


texts:
I have two forms in my HTML page. Both share a set of input elements (not a part of any of the forms, but rather residing separately). Besides that, the forms have their own input elements as well. Each of them also have their own notification div.

The process of POST request for both the forms is nearly identical, except those specifically owned input elements and notification divs.

Here is what I did to remove the code duplication:

function execute(config) {
    var initiator_token = getQueryVariable(window.location.search.substring(1), 'token');
    if (!initiator_token) {
        config.notifyEle
            .removeClass('alert-info')
            .addClass('alert-warning')
            .attr('data-i18n', config.invalidTokenMessage);
        return;
    }

    var params = {
        'initiator_token': initiator_token,
        'recipient_email': config.emailEle.val()
    };

    var lang = $('#mailLangSelector').val();
    if (lang) params['lang'] = lang;

    var message = $('#message').val();
    if (message) params['message'] = message;

    resetInputs();

    var loc = window.location;
    var url = loc.protocol + '//' + loc.host + $SCRIPT_ROOT + '/social' + config.url;

    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(params),
        contentType: 'application/json',
        success: function(data, statusText, xhr) {
            config.notifyEle
                .removeClass('alert-warning')
                .addClass('alert-info')
                .attr('data-i18n', config.successMessage)
                .i18n();
        },
        error: function(xhr, statusText, errorThrown) {
            config.notifyEle
                .removeClass('alert-info')
                .addClass('alert-warning')
                .attr('data-i18n', config.failureMessage)
                .i18n();
        }
    });
}

So, the function accepts a config object, in which I pass form-specific values AND elements (I mean, jquery elements).

A config is like:

var inviteFormConfig = {
    emailEle: $('#inviteEmail'),
    notifyEle: $('#inviteInfo'),
    invalidTokenMessage: 'sharePage.descriptions.validTokenRequired',
    url: '/invitation',
    successMessage: 'sharePage.descriptions.invitationSent',
    failureMessage: 'sharePage.descriptions.invitationFailed'
};

And the usage for a given form:

$('#inviteForm').submit(function(evt) {
    evt.preventDefault();
    execute(inviteFormConfig);
});

Now, though this works well for my use, I want to know if there lies a better pattern for such a scenario.
Also, should I be passing around jQuery elements like this in config?


texts: Finding all root-to-leaf paths in a binary tree

texts:
The task is to return all root-to-leaf paths, given a binary tree (from leetcode).

This is my approach.

Take a helper array and a counter, keeping track of what has been traversed so far. If it is leaf node, print all till that point.
Reduce counter.

Please suggest improvements, if any.

import java.util.LinkedList;
import java.util.List;

public class LeafNode {

    private List<String> list;
    private int count = -1;//counts no. of element in print array
    private int[] printArray;// a helper array class to print nodes

    public List<String> binaryTreePaths(TreeNode root) {
        list = new LinkedList<>();
        if(root == null){

            return list;
        }
        printArray = new int[10000];// assuming the maximum size will be less than 10000
        printList(root);
        return list;

    }

    private void printList(TreeNode root) {
        printArray[++count] = root.val;
        if(root.left == null && root.right == null) {
            printTillNow();
        } else{
            if(root.left != null) {
                printList(root.left);
            }
            if(root.right != null){
                printList(root.right);
            }

        }
        --count;
    }

//just prints all the nodes so far
    private void printTillNow() {
        if(count < 0){
            return;
        }
        StringBuilder sb = new StringBuilder();
        int i =0;
        for(i = 0; i<count; i++){
            sb.append(printArray[i]);
            sb.append("->");
        }
        sb.append(printArray[i]);
        list.add(sb.toString());

    }

}


texts: Irreversibly hash email addresses while preserving format/entropy

texts:
I'm looking to irreversibly hash valid email addresses which have been parsed from mail log data as part of a machine learning project. I need to ensure that the processed data has been scrubbed of personally identifiable information (specific users/client domain etc).

A quick google-fu led me to pyffx and the inbuilt secrets package.

I'm looking to scrub the email addresses while retain the formatting and beginning character sequence:

#!/usr/bin/env python
# coding: utf-8

import pyffx, secrets

def ffx_encrypt(email,secret):
    raw_user, raw_domain = email.split('@')
    #retaining first few characters to test entropy of bulk sender lists
    user_chars = raw_user[:3]
    user_rem = raw_user[3:]
    #get unique characters for each string to retain entropy
    uniq_user_chars = ''.join(set(raw_user))
    uniq_dom_chars = ''.join(set(raw_domain))

    e_user = pyffx.String(secret,alphabet=uniq_user_chars,length=len(user_rem))
    e_dom = pyffx.String(secret,alphabet=uniq_dom_chars,length=len(raw_domain))

    user_encrypt = e_user.encrypt(user_rem)
    dom_encrypt = e_dom.encrypt(raw_domain)

    return user_chars + user_encrypt + '@' + dom_encrypt;

#To be generated at runtime
secret = secrets.token_hex(32).encode()

print(ffx_encrypt('test1@gmail.com',secret))
print(ffx_encrypt('firstname_surname1@mail.net',secret))
print(ffx_encrypt('username1@mail.co.uk',secret))
print(ffx_encrypt('username1@gmail.com',secret))
print(ffx_encrypt('username1@mail.net',secret))
print(ffx_encrypt('bounce-mc.uk1147123_813.721605-sue.test=mail.net@mail555.atl123.test.net',secret))

##Sample run results
#teste@limigooac
#firms_smnnueefrna_@tnmaenmi
#userersua@k.m.auuamo
#userersua@limigooac
#userersua@tnmaenmi
#bout50um7=8s_t43n07s0.6tn5knt0e366u-7c73bl3_2iio@1.eisnss5i1l32s.3.ea..3

At the moment I'm not focused on performance, elegance or robustness, it's more about avoiding stepping on a landmine if there's an obvious flaw with my implementation which could make the post-processed email addresses/domains reversible.

Feedback would be greatly appreciated.

EDIT: Clarified that input will be valid email addresses.


texts: Managing JS objects while preserving references

texts:
Scenario

I have foo:

{
    name: 'Mr. Foo',
    value: 4
}

I receive bar from the server:

{
    name: 'Mrs. Bar',
    description: 'Wife of Mr. Bar'
}

I wish to update foo to be identical to bar (containing only the same properties and values in bar, and nothing more), but I need every reference to now know about these new values. This means doing foo = bar won't work because anything that had a reference to foo still has reference to foo's original values and will keep just looking at those.

Possible Solution

I have been using angular.extend() in the cases that I know for a fact the properties will always be the same, but if I do that in this scenario, foo will wind up with name, value, and description properties, when I need only name and description.

I came up with the following "replacement" function as a part of a utility service designed to solve this problem, but I'm wondering if there's a more elegant way to do this (something that perhaps looks less prone to obscure bugs than this does).

replaceObj: function (obj, updates) {
    if (obj && !Array.isArray(obj)) {
        // Extend original object
        angular.extend(obj, updates);

        // Get object keys
        var objKeys = Object.keys(obj);
        var updatesKeys = Object.keys(updates);

        // Delete original object properties that are not included in the updates object
        objKeys.forEach(function(objKey) {
            if (updatesKeys.indexOf(objKey) === -1)
                delete obj[objKey];
        });
    } else {
        console.error('utility.replaceObj called without valid parameters.');
    }
}


texts:
I am using SignalR to send notifications to clients. I use IClientProxy which is a proxy for invoking hub methods.
It has 10 overload methods for SendAsync that takes parameters one by one as you see below, however, to handle this situation I have written a spagetti style method which is really weird to me.
Could you please give some suggestion?
private async Task InvokeNotification(string userName, string methodName, params object[] parameters)
{
    if (connections.ContainsKey(userName))
    {
        var proxy = Clients.Clients(connections[userName]);
        switch (parameters.Length)
        {
            case 0:
                await proxy.SendAsync(methodName);
                break;

            case 1:
                await proxy.SendAsync(methodName, parameters[0]);
                break;

            case 2:
                await proxy.SendAsync(methodName, parameters[0], parameters[1]);
                break;

            default:
                throw new HubException($"No method was defined with {parameters.Length} parameters in Hub");
        }
    }
}

The following code block is the definition of SendAsync which is coming from SignalR
public static class ClientProxyExtensions
{
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, object arg5, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, object arg4, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, object arg2, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, object arg1, CancellationToken cancellationToken = default);
    public static Task SendAsync(this IClientProxy clientProxy, string method, CancellationToken cancellationToken = default);
}


texts: Extract strings from nested array in Perl

texts:
Extract the strings from nested arrays in Perl.

It prints: a, b, c, d, E

use strict;
use warnings;
use feature qw(say signatures current_sub);
no warnings qw(experimental::signatures);

my $nested = [1, 'a', [2, 3, 'b'], [4, [5, 6, 7, ['c']], [7, [8, 9, [10, 'd']]], 11, 'E']];

print join ', ', @{ extract_strings($nested) };

sub extract_strings($input) {
    my @output = ();

    my $loop = sub ($val) {
        if (ref $val eq 'ARRAY') {
            __SUB__->($_) for @{ $val };
        } else {
            push(@output, $val) if $val =~ /^[a-zA-Z]/;
        }
    };

    $loop->($input);

    return \@output;
}

Any idea for improvement without not core dependencies?


texts: Beginner code for a Rock, Paper, Scissors game in Python

texts:
I am a beginner in Python and I wanted to see if I could get some feedback on my simple Rock, Paper, Scissors game. I do have previous experience in programming, as I started learning a few years ago but got happy feet and moved through the "basics" for a lot of different languages.

With that said, I plan on sticking with Python for a while until I have programmed a game that I find suitable (I am aiming to start small and end up maybe at a Mario clone).

My biggest issue with this program is that I find it very long-winded, and I am sure there is a way to shorten the code tremendously, I just do not know that solution yet. As well, I do plan on adding something to validate user input
but all I know so far are try and except clauses, which I am not sure if they could work.

# a simple game of rock, paper, scissors
import random

opponent = ["Rock", "Paper", "Scissors"]

player1Score = 0

opponentScore = 0

while (True):

    if (player1Score >=3):
        print("Player 1 Wins!!!!!!")
        print("Type 'new game' to play again. (Or type 'exit' to exit.)")
        newGame = input()
        if newGame == "new game":
            player1Score = 0
            opponentScore = 0
            continue
        if newGame == "exit":
            break

    if (opponentScore >=3):
        print("Your opponent Wins!!!!")
        print("Type 'new game' to play again. (Or type 'exit' to exit.)")
        newGame = input()
        if newGame == "new game":
            player1Score = 0
            opponentScore = 0
            continue
        if newGame == "exit":
            break

    print ("Player 1's turn." + " Please type 'Rock', 'Paper', or 'Scissors' to choose your move.")

    opponentMove = random.choice(opponent)
    player1Move = input()

    if player1Move == opponentMove:
        #print (opponentMove) // for debugging
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        print ("Tie!" + " Please go again.")
        continue

    if (player1Move == "Rock") and (opponentMove == "Paper"): # rock loses to paper
        opponentScore = opponentScore + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Paper") and (opponentMove == "Rock"): # paper beats rock
        player1Score = player1Score + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Paper") and (opponentMove == "Scissors"): # paper loses to scissors
        opponentScore = opponentScore + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Scissors") and (opponentMove == "Paper"): # scissors beats paper
        player1Score = player1Score + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Scissors") and (opponentMove == "Rock"): # scissors loses to rock
        opponentScore = opponentScore + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Rock") and (opponentMove == "Scissors"): # rock beats scissors
        player1Score = player1Score + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue


texts: Project Euler Problem 9: Special Pythagorean triplet

texts:
The problem statement is as follows:

  A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

  \$a^2 + b^2 = c^2\$
  For example, \$3^2 + 4^2 = 9 + 16 = 25 = 5^2\$.

  There exists exactly one Pythagorean triplet for which a + b + c = 1000.
  Find the product abc.

My code that follows works. I dislike the if (valuesFound) ... break;. What is a better way of structuring this?

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine(GetProductOfPythagoreanTripletsThatSumTo(1000));
    }

    static bool IsPythagoreanTriplet(int a, int b, int c)
    {
        return (a*a + b*b) == c*c;
    }

    static bool ValuesSumTo(int value, int a, int b, int c)
    {
        return value == a + b + c;
    }

    static long GetProductOfPythagoreanTripletsThatSumTo(int value)
    {
        int a=0;
        int b=0;
        int c=0;
        bool valuesFound = false;
        for (int aValue = 1; aValue <=value/2; aValue++)
        {
            for (int bValue = 1; bValue<=value/2; bValue++)
            {
                for (int cValue= 1; cValue<=value/2; cValue++)
                {
                    if (ValuesSumTo(value,aValue,bValue,cValue) && IsPythagoreanTriplet(aValue,bValue,cValue) && aValue<bValue && bValue<cValue)
                    {
                        a = aValue;
                        b = bValue;
                        c = cValue;
                        valuesFound = true;
                    }
                }
                if (valuesFound)
                    break;
            }
            if (valuesFound)
                break;
        }
        return a * b * c;
    }
}


texts: Simple customer SQL query using a class and function

texts:
I have been writing PHP for a number of years but in a procedural style. I have always shied away from object oriented PHP because I just didn't understand it. However now I'm back for another go.

I have a large web application which is written in procedural style PHP and as a learning exercise I would like to re-write it entirely in object-oriented PHP.

So before I start coding away thinking I'm doing the right thing, I would like to help, tips, and advice on what I have written so far. I don't think I need to explain what I am doing here because it is pretty simple stuff and self-explanatory.

pdo.inc.php

<?php

$host = "localhost";
$db = "dev";
$user = "dev";
$pass = "dev";
$dsn = "mysql:host=$host;dbname=$db;";

try
{
    $pdo = new PDO($dsn, $user, $pass);
} catch (PDOException $ex) {
    echo 'Connection failed: ' . $ex->getMessage();
    die();
}

?>

customer.class.php

<?php

include_once('pdo.inc.php');

class Customers
{
    function GetCustomerName($pdo, $customer_id)
    {
        $query = "SELECT first_name FROM Customers WHERE customer_id = :customer_id LIMIT 1";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':customer_id', $customer_id);
        $stmt->execute();
        return $stmt->fetchColumn();
    }
}

?>

test.php

<?php

include_once('customers.class.php');

$a = new Customers();

echo $a->GetCustomerName($pdo, 1);

?>

Having looked at a number of PHP OOP tutorials it seems people use try/catch differently. I have seen some people use the try/catch within the class's method, and some people call the method from within the try/catch. What's the recommended usage of try/catch?


texts:
I wanted to write a C function C99/POSIX compliant that read an integer from the user input. I wanted this function to be safe and robust but I feel it is way too complex for such simple task.

I am wondering whether this code is optimal.

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

/**
 * Read an integer from `stdin`.
 * @param min Minimum accepted value
 * @param max Maximum accepted value
 * @param nom Default value
 * @return captured integer
 */
int read_integer(char *text, int min, int max, int nom) {
    int n = nom;
    bool failure = false;

    do {
        printf("%s [%d] ? : ", text, nom);

        // Read user input
        char line[24];
        do {
            if (fgets(line, sizeof(line), stdin) != line || feof(stdin)) {
                exit(EXIT_FAILURE);
                break;
            }
        } while (strchr(line, '\n') == NULL);

        // Default value?
        {
            char *cursor = line;
            while ((*cursor == ' ' || *cursor == '\t') && *cursor != '\0') {
                cursor++;
            }
            if (*cursor == '\n') {
                return n;
            }
        }

        // Not a number ?
        if (sscanf(line, "%d", &n) != 1) {
            printf("Error: this is not valid entry!\n\n");
            continue;
        }

        // Not in the range ?
        if (n < min || n > max) {
            printf("Error: value should be between %d and %d!\n\n", min, max);
            continue;
        }

        return n;
    } while(true);
}

int main() {
    do {
        printf("You said %d\n",
            read_integer("What's the answer", 10, 50, 42));
    } while(!feof(stdin));
}


texts: Json Web Token-like implementation in Rust

texts:
I am new to Rust. I am making this to help me learn better. This code has two functions: ::make() and ::get_payload(). ::make() creates a signed web token to be stored on the client. The client sends that token on every request that requires authentication, and the clients information or 'claims' are verified by the signature with ::get_payload(). If ::get_payload() returns Value::Null the token is not valid (or expired).

I need 3 types of feedback.

Are there any security holes or issues with what you can see here?
Is this Rust written well, and how can I improve it?
Am I missing some important error handling?

extern crate base64;
extern crate ring;
extern crate chrono;
extern crate serde_json;

use base64::{encode, decode};
use ring::{digest, hmac};
use chrono::prelude::Utc;
use std::str;
use serde_json::Value;

static RWT_SECRET: &str = "some secret"; // this should be from an environment variable

pub fn make(payload: &str) -> String {
    let mut token = encode(&Utc::now().to_string());
    token.push_str(".");

    let payload_base64 = &encode(payload);
    token.push_str(payload_base64);

    let key = hmac::SigningKey::new(&digest::SHA256, RWT_SECRET.as_bytes());
    let signature = &encode(&hmac::sign(&key, token.as_bytes()));
    token.push_str(".");
    token.push_str(signature);

    token
}

pub fn get_payload(token: &str) -> Value {
    let parts: Vec<&str> = token.split(".").collect();
    if parts.len() != 3 {
        return Value::Null;
    }

    // todo: check timestamp for expiration

    let signed = parts[..2].join(".").to_string();
    let key = hmac::SigningKey::new(&digest::SHA256, RWT_SECRET.as_bytes());
    let signature = &encode(&hmac::sign(&key, signed.as_bytes()));

    if signature.to_string() == parts[2] {
        let utf8 = &decode(parts[1]).unwrap();

        let json = str::from_utf8(utf8).unwrap();
        let payload: Value = serde_json::from_str(json).unwrap();

        return payload;
    }

    Value::Null
}


texts: Generating DNA sequences and looking for correlations

texts:
I've written a script to generate DNA sequences and then count the appearance of each step to see if there is any long range correlation.

My program runs really slow for a length 100000 sequence 100 times replicate.  I already run it for more than 100 hours without completion.

#!/usr/bin/env python

import sys, random
import os
import math

length = 10000

initial_p = {'a':0.25,'c':0.25,'t':0.25,'g':0.25}

tran_matrix = {'a': {'a':0.495,'c':0.113,'g':0.129,'t':0.263},
               'c': {'a':0.129,'c':0.063,'g':0.413,'t':0.395},
               't': {'a':0.213,'c':0.495,'g':0.263,'t':0.029},
               'g': {'a':0.263,'c':0.129,'g':0.295,'t':0.313}}

def fl():
    def seq():
        def choose(dist):
            r = random.random()
            sum = 0.0
            keys = dist.keys()
            for k in keys:
                sum += dist[k]
                if sum > r:
                    return k
            return keys[-1]
        c = choose(initial_p)
        sequence = ''
        for i in range(length):
            sequence += c
            c = choose(tran_matrix[c])
        return sequence

    sequence = seq()
        # This program takes a DNA sequence calculate the DNA walk score.
        #print sequence
    #print len
    u = 0
    ls = []
    for i in sequence:
        if i == 'a' :
            #print i
            u = u + 1
        if  i == 'g' :
                #print i
            u = u + 1
        if  i== 'c' :
                #print i
            u = u - 1
        if  i== 't' :
                #print i
            u = u - 1
        #print u
        ls.append(u)

            #print ls
    l = 1
    f = []
    for l in xrange(1,(length/2)+1):
        lchange =1
        sumdeltay = 0
        sumsq = 0
        for i in range(1,length/2):
            deltay = ls[lchange + l ] - ls[lchange]
            lchange = lchange + 1
            sq = math.fabs(deltay*deltay)
            sumsq = sumsq + sq
            sumdeltay = sumdeltay + deltay
        f.append(math.sqrt(math.fabs((sumsq/length/2) - math.fabs((sumdeltay/length/2)*(sumdeltay/length/2)))))
        l = l + 1
    return f

def performTrial(tries):
    distLists = []
    for i in range(0, tries):
        fl()
        distLists.append(fl())
    return distLists

def main():
    tries = 10
    distLists = performTrial(tries)
    #print distLists
    #print distLists[0][0]
    averageList = []
    for i in range(0, length/2):
        total = 0
        for j in range(0, tries):
            total += distLists[j][i]
        #print distLists
        average = total/tries
        averageList.append(average)
    # print total
    return averageList

out_file = open('Markov1.result', 'w')
result = str(main())
out_file.write(result)
out_file.close()


texts: Query to get number of related records in 2 child tables

texts:
I have a category table (brands) and 2 other tables (Pens and Pencils) that have parent-child relation with this table through a field CatID.  Now I want to get a list of Brandsand number of records in child tables.

I use this query:

Select
  B.* ,COUNT(P.ID) as PensCount, COUNT(Pc.ID) as PencilsCount
from
  Brands B
left outer join
  Pens P on B.ID=P.CatID
left outer join
  Pencils Pc on B.ID= Pc.CatID
group by
  B.ID,B.Title;

Is this correct?  Is there any way to make this query better?


texts:
I have this method in my service layer

    public ModuleResponse GetModules(ModuleRequest request)
    {
        var response = new ModuleResponse(request.RequestId);
        try
        {
            response.Modules = Mapper.ToDataTransferObjects(ModuleDao.GetModules());
            return response;
        }
        catch (Exception ex)
        {
            Log.Error(ex);
            response.Acknowledge = AcknowledgeType.Failure;
            response.Message = "An error occured.";
            return response;
        }
    }

I've written a unit test like this

    [Fact]
    public void GetModulesTest()
    {
        //Arrange
        var mockModuleDao = Mock.Create<IModuleDao>();
        var mockLog = Mock.Create<ILog>();
        var mockAuditDao = Mock.Create<IAuditDao>();

        var moduleList = new List<ModuleItem>
        {
            new ModuleItem {Id = 100, Category = "User Accounts", Feature = "Users"},
            new ModuleItem {Id = 101, Category = "User Accounts", Feature = "Roles Permissions"}
        };

        mockModuleDao.Arrange(dao => dao.GetModules()).Returns(moduleList);

        IUserManagementService userService = new UserManagementService(mockModuleDao, mockLog, mockAuditDao);

        var request = new ModuleRequest().Prepare();

        //Act
        var actualResponse = userService.GetModules(request);

        //Assert
        Assert.Equal(AcknowledgeType.Success, actualResponse.Acknowledge);
        Assert.Equal(2, actualResponse.Modules.Count);
    }

My question is... are such methods worth testing? I have a whole other bunch of retrieve methods that just return me lists of data.

Are there any other ways to improve the unit test in this particular example?

The first assert basically checks if the method has been executed without any error.

Is the 2nd Assert of my test redundant?


texts: Implementation of OAuth2 device flow using Python

texts:
Please review this program because I wrote something in Python for the first time. This code is to be used for device authorization in oauth2 device flow.

import requests
import webbrowser
import time

API_ENDPOINT = "<url>"
RESPONSE_TYPE = "device_code"
GRANT_TYPE = "device"
CLIENT_ID = "<client_id>"

data = {'response_type':RESPONSE_TYPE,
        'client_id':CLIENT_ID}

response = requests.post(url = API_ENDPOINT, data = data) # sending post request and saving response as response object
json_response = response.json()
print("The user_code is:%s"%json_response['user_code'])

DEVICE_CODE = json_response['device_code']
webbrowser.open(json_response['verification_uri']) # open browser with idenity screen

data = {'grant_type':GRANT_TYPE,
        'client_id':CLIENT_ID,
        'code': DEVICE_CODE}

while True:
    response = requests.post(url = API_ENDPOINT, data = data)
    if response.status_code == 200:
        json_response = response.json()
        print("The access_token is:%s"%json_response['access_token'])
        break
    else:
        print(response.text)
        time.sleep(json_response['interval'])


texts:
This is more of a 'model' of TicTacToe, as you'll see it's not "gameified" in the sense that it will allow for inputs and outputs nor will it record any "active" state of the game but those things are trivial to implement.

I'm cheating a little bit on the functional paradigm in my function to rotate the grid, but this is on purpose, it's just easier to rotate the grid by mutation than by going pure functional style, in the end, the state is only manipulated in a local function anyhow so I think it's neglible.

Also there are many times where I have ignored optimizations over conciseness. One might imagine that this would not be an area where optimal performance is key so I have prioritized getting as concise and readable code as possible.

module TicTacToe

type Mark = None | Cross | Nought
type Outcome = None | NoughtWon | CrossWon | Draw

let emptyGrid = (None, Array2D.init 3 3 (fun _ _ -> Mark.None))

let flatten (x: 'a [,]) = x |> Seq.cast<'a>

let rotateCw (grid: 'a [,]) =
    let out = Array2D.zeroCreate 3 3
    for y in 0..2 do
        for x in 0..2 do
            out.[x,y] <- grid.[0 + y, 2 - x]
    out

let checkOutcome grid =
    let checkSeg seg =
        seq { for i in 0..2 do
                let count =
                    seg i |> Array.sumBy
                        (function Cross -> 1 | Nought -> 2 | _ -> 0)
                if count = 6 || count = 3 then
                    yield (if count = 6 then NoughtWon else CrossWon) }
        |> Seq.tryFind ((<>)None)
    let vertical =
        let rot = grid |> rotateCw
        (fun x -> rot.[x, 0..2])
    let horizontal = (fun y -> grid.[0..2, y])
    let diagonal (m:_[,]) = (fun _ -> [| for i in 0..2 -> m.[i,i] |])
    let diagonal2 = grid |> rotateCw |> diagonal
    let checks =
        [checkSeg vertical; checkSeg horizontal;
         checkSeg (diagonal grid); checkSeg diagonal2]
    if checks |> List.exists (Option.isSome) then
        checks |> List.find (Option.isSome) |> Option.get
    elif grid |> flatten |> Seq.forall ((<>)Mark.None) then Draw
    else None

let placeMark pos mark (_, grid: Mark [,]) =
    let res =
        Array2D.init 3 3 (fun x y ->
            if (x,y) = pos then mark else grid.[x,y])
    (checkOutcome res, res)


texts:
I use NodeJS along with the MongoDB NodeJS Driver to store tweets into my local MongoDB server. In the following setup, mongos insertOne method gets invoked quite often by a socket event.

const MongoClient   = require('mongodb').MongoClient;
const TwitterClient = require('node-tweet-stream');

const twitter = new TwitterClient({
    consumer_key: '',
    consumer_secret: '',
    token: '',
    token_secret: ''
});

MongoClient.connect('mongodb://localhost:27017/', { useNewUrlParser: true }).then(client => {
    /**
     * Version 1
     */
    twitter.on('tweet', tweet => {
        client.db('twitter').collection('tweets').insertOne(tweet).then(rs => {
            console.log('tweet received', tweet);
        });
    });

    /**
     * Version 2
     */
    const tweetsCol = client.db('twitter').collection('tweets');

    twitter.on('tweet', tweet => {
        tweetsCol.insertOne(tweet).then(rs => {
            console.log('tweet received', tweet);
        });
    });
});

In version 1 client.db('twitter').collection('tweets').insertOne(tweet) is executed on every tweet event. Whereas in Version 2 the reference of the collection is stored in a variable.

Does the mongodb driver handle such repetitive calls like in version 1 and should I care changing the code structure to version 2 in terms of performance?


texts: Transform a MongoDb parent reference tree into a deep nested tree

texts:
Given a mongodb collection that stores trees as nodes with parent references this methods returns a deep nested tree where every child nodes are stored in a property childs[Seq]

  def getTree(rootId: BSONObjectID): Future[CategoryTreeNode] = {

    def collect(parent: CategoryTreeNode): Future[CategoryTreeNode] = {

      // Query the database - returns a Future[Seq[CategoryTreeNode]]
      getChilds(parent._id.get).map {

        // Seq[CategoryTreeNode]
        childs =>
          Future.sequence(
            childs.map(child => collect(child)) // Recursion
          ).map(childSeq => parent.copy(childs = Some(childSeq)))

      }.flatMap(x => x).map(y => y)

    }

    // Find the root node and start the recursion
    findOne[CategoryTreeNode](Json.obj("_id" -> rootId)).map(maybeNode => maybeNode match {
      case None => throw new RuntimeException("Current node not found by id!")
      case Some(node) => collect(node)
    }).flatMap(x => x)

  }


texts: Insertion sort with binary search in Python

texts:
I have a bit of trouble simplifying the binary search code. This is different from the traditional binary search because we effectively want to find the location for which A[j] is the least element larger than the current unsorted value.

Thoughts?

def binary_search(A, value, start, end):
    # we need to distinugish whether we should insert
    # before or after the left boundary.
    # imagine [0] is the last step of the binary search
    # and we need to decide where to insert -1
    if start == end:
        if A[start] > value:
            return start
        else:
            return start+1

    # this occurs if we are moving beyond left's boundary
    # meaning the left boundary is the least position to
    # find a number greater than value
    if start > end:
        return start

    mid = (start+end)/2
    if A[mid] < value:
        return binary_search(A, value, mid+1, end)
    elif A[mid] > value:
        return binary_search(A, value, start, mid-1)
    else:
        return mid

def insertion_sort(A):
    for i in xrange(1, len(A)):
        value = A[i]
        j = binary_search(A, value, 0, i-1)
        A = A[:j] + [value] + A[j:i] + A[i+1:]
    return A

print insertion_sort([0,1,-1])
print insertion_sort([0,1,2,3,9,-1])
print insertion_sort([1,2,3,4,5,6,7,8,11,10,0])


texts: Updating HTML table (Userlist) with Node.js

texts:
I currently have an HTML
 with all the socket.io-rooms. Client-side, the table gets fetched if you visit the page. If some room gets created or deleted, it get updated with the following code. There's also a button that gets updated to show if the room is full or not.

Now I want to know if there's any "better" way. The argument is room_list (array with objects for each room). Should I split it into two functions (fetchRoomList and updateRoomList) or use "pure" JavaScript instead of jQuery? Any other ideas?

socket.on( 'updateRoomsList', function ( room_list ) {
    var i;
    for (i = room_list.length - 1; i >= 0; i -= 1) {
        var r = room_list[ i ];
        var el = $( '.room-' + r.id ).length;
        var parts = [];

        // Create Row
        if( !el ) {
            parts.push( '
' );
            parts.push( '' + r.id + '	' );
            parts.push( '' + r.name + '	' );
            parts.push( '' + r.players.length + ' / ' +r.slots + '	' );
            parts.push( 'JOIN	' );
            $( '.lobby-container .room-list tbody' ).prepend( parts.join() );
        }
        else // Update Row
        {
            $( '.lobby-container .room-list tbody .room-' + r.id + ' .room-players' ).text( r.players.length + ' / ' +r.slots );
            if( r.players.length >= r.slots ) { // Full Room
                $( '.lobby-container .room-list tbody .room-' + r.id + ' .room-button .btn' )
                    .text( 'FULL' )
                    .addClass( 'btn-warning' )
                    .removeClass( 'btn-success' )
                    .addClass( 'disabled' );
            } else { // Not full
                $( '.lobby-container .room-list tbody .room-' + r.id + ' .room-button .btn' )
                    .text( 'JOIN' )
                    .addClass( 'btn-success' )
                    .removeClass( 'btn-warning' )
                    .removeClass( 'disabled' );
            }
        }
    }
} );


texts: Service layer for course student registration

texts:
I have this piece of code in my service layer and registers and student for a course.
As you can see if have alot of if statements and i was wondering if any could suggest a nicer way of writing this code?
    public async Task<bool> RegisterStudentForCourseAsync(RegisterStudentForCourseRequest registerStudent)
    {
        var student = await _studentRepository.GetStudentInformationAsync(registerStudent.StudentId);

        if (student == null)
        {
            throw new StudentCourseRegistrationException("Student Not Found");
        }

        var alreadyRegistered = student.Enrollments.Any(x => x.CourseId == registerStudent.CourseId);

        if (alreadyRegistered)
        {
            throw new StudentCourseRegistrationException("Student is Already Registered for Course");
        }

        //change this to a config setting
        if (student.SubjectCount >= 5)
        {
            throw new StudentCourseRegistrationException("Cannot Register Amount of Courses");
        }

        var course = _courseRepository.GetCourseInformation(registerStudent.CourseId);

        if(course == null)
        {
            throw new StudentCourseRegistrationException("Course Not Found");
        }

        if(course.Enrolled >= course.Capacity)
        {
            throw new StudentCourseRegistrationException("Course is fully Booked");
        }

        return await _courseRepository.SaveRegisterationOfStudentForCourse(course, registerStudent, student);
    }
}


texts:
I have to made an accordion-, respectively "zippy"-component using Angular 7.

I'm new to Angular. Just started with it a few weeks ago. But with some Google-usage I was able to implement the required feature.

Here's the way it looks.

In collapsed state:

In expanded state:

Here's the code which I wrote for the accordion-component:

import {
  Component,
  OnInit,
  Input
} from '@angular/core';
import {
  Title
} from '@angular/platform-browser';

@Component({
  selector: 'zippy',
  templateUrl: './zippy.component.html',
  styleUrls: ['./zippy.component.css']
})
export class ZippyComponent implements OnInit {
  @Input() title;
  isExpanded = false;
  buttonCaption = "Expand";

  constructor() {}

  ngOnInit() {}

  onClickButton() {
    this.isExpanded = !this.isExpanded;
    this.buttonCaption = this.isExpanded ? "Collapse" : "Expand";
  }
}
.container {
  font-family: Arial, Helvetica, sans-serif;
  max-width: 800px;
  width: 100%;
  margin: auto 2rem;
  padding: 3rem 2rem;
  border: 1px solid #555;
  border-radius: 6px;
  text-align: left;
  font-size: 2rem;
  margin-bottom: 1rem;
}

nav {
  display: flex;
  justify-content: space-between;
}

.container a {
  text-decoration: none;
  padding: 0.4rem 0.6rem;
  font-size: 2rem;
  color: #555;
}

.container a:hover {
  cursor: pointer;
}

main {
  padding: 0.25rem 1rem;
  margin-top: 3rem;
  background-color: #eee;
  border-radius: 6px;
  font-size: 1.4rem;
}

{{ title }}

      <ng-content></ng-content>

The code of 'app.component.html':

  <zippy title="Shipping Details">

Duo dolore sit et clita amet, aliquyam clita sed duo nonumy amet et et et. Rebum amet lorem stet est.

Prose and thy of have days heavenly. Parasites the not unto in so. Delphis yet friend drop cell caught mote, companie a gild favour and.

De quille inouies pieds blonds béni crépuscule les ravie fermentent, béhémots rutilements mer couleurs des de maries pénétra fortes folle. Je de dévorés suivi de. Impassibles liens a a papillon..

  </zippy>

  <zippy title="Billing Details">

Großer teuren gar im wie freunde du sanft wo, in du wo gar denkst weh liebe so ich dir. Kleinem zu spät du dann ort ort. Nun der denkst gesellschaft.

  </zippy>

The functionality works but currently it just changes from collapsed to expanded state at once. It would be cool to have some animation or something similar when it changes. So that one has a "soft" transition.

If someone knows how to transition that I would love to read his / her answer.

All other hints, recommendations and critiques concerning my implementation welcomed as well.


texts:
Following is my code for implementing basic symbol table in C. Please review my code and tell where I can improve my program.

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

#define BUFFER_SIZE 1024
#define TOKEN_SIZE 32

typedef struct symbol
{
    char* identifierName;
    char* datatype;
    int offset;
    struct symbol* next;
}symbol;

void insert(symbol** headRef,char* identifier,char* type)
{
    symbol* newnode = (symbol*) malloc(sizeof(symbol));
    static symbol* prevnode;
    newnode->identifierName = (char*) malloc((strlen(identifier)+1)*sizeof(char));
    newnode->datatype = (char*) malloc((strlen(type)+1)*sizeof(char));

    if(*headRef==NULL)
    {
        newnode->offset=0;
        prevnode = newnode;
    }

    strcpy(newnode->identifierName,identifier);
    strcpy(newnode->datatype,type);

    if(strcmp(newnode->datatype,"int") == 0)
        (newnode->offset) = (prevnode->offset) + sizeof(int);
    else if(strcmp("float",newnode->datatype) == 0)
        (newnode->offset) = (prevnode->offset) + sizeof(float);
    else if(strcmp("char",newnode->datatype) == 0)
        (newnode->offset) = (prevnode->offset) + sizeof(char);
    else if(strcmp("double",newnode->datatype) == 0)
        (newnode->offset) = (prevnode->offset) + sizeof(double);

    prevnode = newnode;
    newnode->next = (*headRef);
    (*headRef) = newnode;
}

void display(symbol* node)
{
    while(node!=NULL)
    {
        printf("%s %s %d \n",node->identifierName,node->datatype,node->offset);
        node = node->next;
    }
}

bool isIdentifier(const char* token)
{
    if(isalpha(token[0]) || token[0]=='_')
    {
        for(int i=1;token[i]!=(char)NULL;i++)
        {
            if(!isalnum(token[i]))
                return false;
        }
        return true;
    }
    return false;
}

bool isDatatype(const char* token)
{
    const char *datatype[]={"char","double","float","int"};
    for(size_t i=0;i<(sizeof(datatype)/sizeof(char*));i++)
    {
        if(strcmp(token,datatype[i])==0)
            return true;
    }
    return false;
}

void isDeclaration(char* statement,symbol** head)
{
    char *delimiters = " ,;\t";
    char *token = strtok(statement,delimiters);
    if(!isDatatype(token))
        return;
    char *datatype = token;
    while((token=strtok(NULL,delimiters)))
        if(isIdentifier(token))
            insert(head,token,datatype);
}

FILE* openFile(int param1,char* param2[])
{
    if(param1<2)
    {
        fprintf(stderr,"No file specified to read. \n");
        exit( EXIT_FAILURE );
    }

    if(param1>2)
    {
        fprintf(stderr,"Too many arguments for read to perform. \n");
        exit( EXIT_FAILURE );
    }

    FILE *fp = fopen(param2[1],"r");

    if(fp==NULL)
    {
        fprintf(stderr,"File access denied on read. \n");
        exit( EXIT_FAILURE );
    }
    return fp;
}

int main(int argc, char *argv[])
{
    FILE *fp = openFile(argc,argv);

    char string[BUFFER_SIZE];
    symbol* head = NULL;

    while(fgets(string,sizeof string, fp))
        isDeclaration(string,&head);

    display(head);
    return 0;
}


texts: Printing out relative date from current time

texts:
Here is some code of mine that prints out the relative date according to the current time:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (int argc, char *argv[])
{
  int i = 1;
  struct tm date = {0};
  char relativeDays[80];

  char* temp = strtok(argv[1], "/");
  while(temp != 0)
  {
    switch(i++)
    {
                case 1:
                        date.tm_mon  = atoi(temp) - 1;
                        break;
                case 2:
                        date.tm_mday = atoi(temp);
                        break;
                case 3:
                        date.tm_year = atoi(temp) - 1900;
    }
    temp=strtok(NULL, "/");
  }
  i = (int) difftime(time(NULL), mktime(&date))/86400;
  sprintf(relativeDays, "%d", abs(i));
  if (i > 0) printf("%s\n", strcat(relativeDays, " days ago."));
  else if (i < 0) printf("%s\n", strcat(relativeDays, " days from now."));
  else printf("Today\n");
  return 0;
}

Sample input and output:

$ ./date 12/8/2013
2 days ago.
$ ./date 12/10/2013
Today
$ ./date 12/24/2013
13 days from now.

Any thoughts on how to improve the code, specifically how to make it shorter?


texts:
I'm working on a city building simulation game, and I have reached the point where I need to check whether tiles are connected to a power source.  I decided on a flood fill for this, since it seemed simple enough to implement.  For reference, I used this flood fill algorithm, and I also found this question on code review about flood fill in java.  My code is largely similar to the code in those links, but it is slightly different because I am not filling an image with color but rather marking tiles connected to power plants as isPowered.

I know that recursion is dangerous, and the efficiency of the code may be suspect.  With the map mostly filled up, this method gets called a couple of thousand times per cycle. With just a snaky path, about 200 times.

Here is an example to show that the algorithm is working:

The visible tiles are powered.

Here is the code:

private void calculatePower() {
    for (Tile tile : this.tilesForSort) {
        tile.hasBeenSearched = false;
    }
    for (Tile tile : this.tilesForSort) {
        if (tile.getBuildingType() == IsoTileType.POWER) {
            this.powerFill(tile.getPosition().x, tile.getPosition().y);
        }
    }
}
public void powerFill(int x, int y) {

    if (this.isNotInsideGrid(x, y)) {
        return;
    }

    Tile tile = this.levelData[x][y];

    if (tile.hasBeenSearched || tile.zoneType.getLevel() < 1) {
        return;
    }

    tile.isPowered = true;
    tile.hasBeenSearched = true;

    this.powerFill(x - 1, y);
    this.powerFill(x + 1, y);
    this.powerFill(x, y - 1);
    this.powerFill(x, y + 1);
}
private boolean isNotInsideGrid (int x, int y) {
    return x < 0 || y < 0 || x >= World.WORLD_WIDTH || y >= World.WORLD_HEIGHT;
}


texts: Counting Hamiltonian triangulations (OEIS 3122)

texts:
I'm trying to translate formulas from the 3122th sequence in OEIS database, in particular this one:

B(s, m) = sum((m! / m_1! ... m_s!) * r(1)^{m_1} ... r(s)^{m_s})
where the sum is over all partitions of s such that
s = m_1 + 2*m_2 + ... + s*m_s and m = m_1 + m_2 + ... + m_s.

My complete solution is available at GitHub.
First question.  What the b(s,m) function really does isn't important, all that matters here is that I would like to store already computed values. Can one perform the memoisation in an elegant and smarter way (like Haskell here achieves)? It speeds up the computation a lot.

memoB = [[-1 for x in range(100)] for y in range(100)]

def b(s, m):
    if memoB[s][m] == -1:
        # some calculations
        memoB[s][m] = total
    return memoB[s][m]

Second (algorithmic) question.
The slowest part of my code generates all integer partitions m = m_1 + m_2 + ... + m_s such that s = m_1 + 2*m_2 + ... + s*m_s. For example, if s = 10, m = 5, these are:

[4, 0, 0, 0, 0, 1, 0, 0, 0, 0]
[3, 1, 0, 0, 1, 0, 0, 0, 0, 0]
[3, 0, 1, 1, 0, 0, 0, 0, 0, 0]
[2, 2, 0, 1, 0, 0, 0, 0, 0, 0]
[2, 1, 2, 0, 0, 0, 0, 0, 0, 0]
[1, 3, 1, 0, 0, 0, 0, 0, 0, 0]
[0, 5, 0, 0, 0, 0, 0, 0, 0, 0]

The current algorithm (coded below) finds the partitions that I am looking for, but is inefficient. Can it be improved? If yes, how?

def partitions(s, m):
    stack = [] # contains partial partitions
    matches = [] # stores good partitions
    for i in range(1 + min(s, m)):
        stack.append(([i], s - i, m - i))

    while len(stack) > 0:
        seq, s_sum, m_sum = stack.pop()
        # seq - initial section of a partition
        # s_sum - difference between s and partial sum of seq
        # m_sum - difference between m and partial sum of seq

        # if seq has already s summands and both partial sums agree,
        # it is marked as a good partition
        if len(seq) == s:
            if s_sum == 0 and m_sum == 0:
                matches.append(seq)
            continue

        # if one of the partial sums drops below zero,
        # the seq can't be continued
        if min(s_sum, m_sum) < 0 and max(s_sum, m_sum) > 0:
            continue

        # we extend the stack by all "one step continuations" of seq
        factor = len(seq) + 1
        bound = max(1, 1 + min(s_sum // factor, m_sum))
        stack.extend([(seq + [i], s_sum - i * factor, m_sum - i) for i in range(bound)])
    return matches

I know that one shouldn't name functions with single letters, but these are taken from the OEIS description directly.


texts:
In simulating physical equations (such as fluid dynamics) it is common to write an application that deals with 1, 2, and 3 dimensions. A common C/Fortran approach is to make all vectors (for example) have a size of 3, and then to carry around a global constant to say how many elements are valid.

We have tried to use C++11 templating to serve the same purpose and the majority of our application is now templated by int DIM.

There are times that the difference between API for different dimensions requires entirely new classes. For this, we have come up with the following selector pattern -- it seems to be working well, but I was wondering if we have reinvented the wheel and missed something along the way?

In order to construct the pattern, we need several files:

ClassName_fwd.h:

This allows the user to reference the specific implementation of the dimension specific classes in a way that is consistent for all dimensions.

// forward decs
class ClassName_1;
class ClassName_2;
class ClassName_3;
template<int DIM>
struct ClassNameSelector { };
// 1D
template<>
struct ClassNameSelector<1> {
using ClassName = ClassName_1;
};
// 2D
template<>
struct ClassNameSelector<2> {
using ClassName = ClassName_2;
};
// 3D
template<>
struct ClassNameSelector<3> {
using ClassName = ClassName_3;
};
// typedef
template<int DIM>
using ClassName = typename ClassNameSelector<DIM>::ClassName;

ClassName.h

#include <path/to/ClassName_fwd.h>
#include <path/to/ClassName_1.h>
#include <path/to/ClassName_2.h>
#include <path/to/ClassName_3.h>

ClassName.cpp

// explicit instantiations
template struct ClassNameSelector<1>;
template struct ClassNameSelector<2>;
template struct ClassNameSelector<3>;

ClassName_N.h/cpp [optional]

Holds all of the functionality that can be implemented without care for dimension, in addition to pure virtual methods that should be overridden by the dimension-specific implementations. This class sets the dimensionless API for ClassName. In the cpp file, there should be explicit instantiations of this class. This class might be excluded to avoid pure virtual function calls.

/**
* All of the functions that have a constant implementation
* for all dimensions
*/
template<int DIM>
class ClassName_N {
    // non-dimensional functions, i.e.
    void somethingDimensionless(
        const std::array<double, DIM>& dblArray
    ) const;
};

ClassName_[1,2,3].h/cpp

Implements the [1,2,3] dimension version of the class. This should implement the pure virtual functions of ClassName_N in addition to any functions specific to the particular dimension. These addition functions can only be called from other dimensionally specific implementations, otherwise the compiler will complain.

/**
* The dimensionally specific API's
*/
class ClassName_1 : public ClassName_N<1> {
    // dimensional functions, i.e.
    void somethingIn1D() const;
};

Usage

#include <path/to/ClassName.h>

template<int DIM>
void useAnyDimension(const ClassName<DIM>& c) {
    std::array<double, DIM> arr;
    c.somethingDimensionless(arr);
}

void doSomethingIn1D(const ClassName<1>& c) {
    c.somethingIn1D();
}

int main (int argc, char *argv[]) {
    ClassName<1> oneD;
    ClassName<2> twoD;

    // dimension-less
    useAnyDimension(oneD);
    oneD.somethingDimensionless({0.1});
    twoD.somethingDimensionless({0.1, 0.5});

    // dimension specific
    doSomethingIn1D(oneD);
    oneD.somethingIn1D();

    // the following would give compile-time errors
    //doSomethingIn1D(twoD);
    //twoD.somethingIn1D();

    return 0;
}


texts:
If I have to loop results of a query echoing first all fields of a column, then echoing something not to loop, then fields of another column.

<?php
$con = mysqli_connect();
echo 'Latest users who tried our test
';
//select the fields of the first column
$query1 = mysqli_query($con,"SELECT user FROM ris_uinversita LIMIT 0,10");
//loop the results
while($assoc1=mysqli_fetch_assoc($query1)){echo $assoc1['user'].'
';}
//echo something not to loop
echo 'Users got the following scores
';
//select the fields of the second column
$query2 = mysqli_query($con,"SELECT score FROM ris_universita LIMIT 0,10");
//loop the results
while($assoc2=mysqli_fetch_assoc($query2)){echo $assoc2['score'].'
';}
?>

Is it possible to use just one query like this

mysqli_query($con,"SELECT * FROM ris_universita LIMIT 0,10");

to select both fields just once?

If it could be helpful, table ris_universita has just the two columns: "score" (tinyint) and "user" (varchar 30).  There aren't so many records for now, but I hope in there will be in the future.


texts: Check if a value exists or catch an exception

texts:
I am parsing a response from server, and in case it contains the fields "chunk_number"(J_ID_CHUNK_NUMBER) and "total_chunk_number"(J_ID_CHUNK_TOTAL), I want to check whether I should request another chunk or not. Not a complicated task. Yet I doubt what would be a better way to implement?

Option 1 - using try catch:

private int getNextChunkNumber(JSONObject jUpdate) {
    try {
        int current;
        int total;
        current = jUpdate.getInt(J_ID_CHUNK_NUMBER);
        total = jUpdate.getInt(J_ID_CHUNK_TOTAL);
        if (current < total) {
            return current + 1;
        }
    }
    catch(JSONException e) {
        // This is an empty exception because it merges with the default result (-1)
    }
    return -1;
}

Option 2 - using the has method:

private int getNextChunkNumber(JSONObject jUpdate) {
    int current;
    if (jUpdate.has(J_ID_CHUNK_NUMBER) &&
        jUpdate.has(J_ID_CHUNK_TOTAL)) {
        current = jUpdate.getInt(J_ID_CHUNK_NUMBER);
        if (current < jUpdate.getInt(J_ID_CHUNK_TOTAL)) {
            return current + 1;
        }
    }
    return -1;
}


texts: Converting Roman numerals to integers and vice versa

texts:
def int_to_roman (integer):

    returnstring=''
    table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]

    for pair in table:

        while integer-pair[1]>=0:

            integer-=pair[1]
            returnstring+=pair[0]

    return returnstring

def rom_to_int(string):

    table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]
    returnint=0
    for pair in table:

        continueyes=True

        while continueyes:
            if len(string)>=len(pair[0]):

                if string[0:len(pair[0])]==pair[0]:
                    returnint+=pair[1]
                    string=string[len(pair[0]):]

                else: continueyes=False
            else: continueyes=False

    return returnint


texts:
I have a PDO class below:

class DB {

        private $dbh;
        private $stmt;

        static $db_type;
        static $connections;

        public function __construct($db, $id="") {

             switch($db) {
                case "db1":
                      try{

                          $this->dbh = new PDO("mysql:host=localhost;dbname=ms".$id, 'root', '', array( PDO::ATTR_PERSISTENT => true ));
                      }  catch(PDOException $e){
                          print "Error!: " . $e->getMessage() . "
";
                          die();
                      }
                break;
                case "db2":
                      try{
                          $this->dbh = new PDO("mysql:host=localhost;dbname=users", 'root', '', array( PDO::ATTR_PERSISTENT => true ));
                      } catch(PDOException $e){
                          print "Error!: " . $e->getMessage() . "
";
                          die();
                      }
                break;
            }
            self::$db_type = $db;
        }

        static function init($db_type = "", $id){

            if(!isset(self::$connections[$db_type])){
                self::$connections[$db_type] = new self($db_type, $id);
            }

            return self::$connections[$db_type];
        }

        public static function query($query) {

            self::$connections[self::$db_type]->stmt = self::$connections[self::$db_type]->dbh->prepare($query);
            return self::$connections[self::$db_type];
        }

        public function bind($pos, $value, $type = null) {

            if( is_null($type) ) {
                switch( true ) {
                    case is_int($value):
                        $type = PDO::PARAM_INT;
                        break;
                    case is_bool($value):
                        $type = PDO::PARAM_BOOL;
                        break;
                    case is_null($value):
                        $type = PDO::PARAM_NULL;
                        break;
                    default:
                        $type = PDO::PARAM_STR;
                }
            }

            self::$connections[self::$db_type]->stmt->bindValue($pos, $value, $type);
            return self::$connections[self::$db_type];
        }

        public function execute() {
            return self::$connections[self::$db_type]->stmt->execute();
        }
    }

Is it ok for multiple DB connections or not?


texts: Setting and clearing JavaScript intervals depending on browser state

texts:
I'm trying to build an application which automatically refreshes the page with fresh stuff from the server. I was trying out the approach with something basic like printing out the time, to test out my approach. I go to the page, and it starts printing the time every 5 seconds in the console. When I switch to offline mode, the auto-printing should stop, and when I come back to online mode, the auto-printing should resume again. So far, I have this:

timing = setInterval(function() {
    urlToBeCalled = '/autoupdate/';
    var d = new Date();
    console.log(d.toLocaleTimeString());
    /*$.ajax(url: urlToBeCalled);*/
}, 5000);

window.addEventListener("offline", function(e) { console.log("offline"); clearInterval(timing);});

window.addEventListener("online", function(e) { console.log("online"); timing = setInterval(function() {.... blah... blah... blah...}, 5000)

(The "blah"s are the same code from the timing variable above)

It works, but I don't think this is a very proper way to do things. Is there any better way to accomplish this?


texts: Scale the ingredients of a recipe up/down

texts:
I wrote a React app to adjust the serving size of a recipe. For example, if the recipe serves 4 people and requires 4 eggs, scaling it down to serve only 1 person should only require 1 egg. I try to also keep the units singular/plural accordingly while converting units when they become too big or too small. These features are written in plain JS, but I'd be curious to hear if it would be more appropriate to do this in React and how.

Relevant code snippets:

const RECIPES = [{
  id: 'pasta-dough',
  name: 'Pasta Dough',
  serves: 4,
  ingredients: [
    {quantity: '4', unit: 'eggs'},
    {quantity: '4', unit: 'cups', item: 'flour'},
    // Note that the quantity below would normally be '1/4'.
    {quantity: '.25', unit: 'cup', item: 'olive oil'},
    {quantity: '1', unit: 'tablespoon', item: 'salt'}
  ]
}];

const Recipe = React.createClass({
  getInitialState: function() {
    return {
      serves: this.props.serves,
      scale: 1
    };
  },
  onChange: function(e) {
    const serves = Math.floor(Math.abs(e.target.value));
    this.setState({
      serves: serves,
      scale: serves / this.props.serves
    });
  },
  render: function() {
    return (

{this.props.name}

          Serves
          <input
            type="number" min="0"
            value={this.state.serves}
            /* TODO: Smarter default step. */
            step={this.props.serves / 4}
            onChange={this.onChange} />

        <Ingredients ingredients={this.props.ingredients} scale={this.state.scale} />

    );
  }
});

const Ingredients = React.createClass({
  render: function() {
    return (

        {this.props.ingredients.map((ingredient, i) =>
          <Ingredient key={i} scale={this.props.scale} {...ingredient} />
        )}

    );
  }
});

const Ingredient = React.createClass({
  render: function() {
    // Commenting out the code that depends on other code libraries.
    // Want to keep this code review as simple as possible.
    // const quantity = new Quantity(this.props.quantity).multiply(this.props.scale);
    const unit = this.props.unit;
    // const measurement = new Measurement(quantity, unit).convertUnits();
    const quantity = this.props.quantity * this.props.scale;
    const measurement = `${quantity} ${unit}`
    return(

{measurement.toString()} {this.props.item}

    );
  }
});

RECIPES.forEach((recipe, i) => {
  ReactDOM.render(
    <Recipe key={recipe.id} index={i} {...recipe}/>,
    document.getElementById(recipe.id));
});

document.querySelector('h2 input').focus();

Demo: https://rviscomi.github.io/scale-recipe-react/
Source: https://github.com/rviscomi/scale-recipe-react

I'm new to React and would really appreciate advice on writing more semantic React. Some specific areas I'm interested in:

use of state vs props
mounting
component organization
static methods

Things I'm not interested to get feedback on:

general JS style
ES6, unless it directly affects React
markup semantics


texts:
Just for fun, I created a script called TinyBF which can compress Brainfuck programs into a format half their size. For example, take a famous hello world program clocking in at 78 bytes:

--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+.

When put into TinyBF format, it is only 39 bytes:

7#!00"7!'!7?,,,?#B!?.>!$,.>?!.

The steps for encoding are:

Translate all characters in the input using the following dictionary: {'>': '2', '<': '3', '+': '4', '-': '5', '.': '6', ',': '7', '[': '8', ']': '9'}.
Split the string into chunks of two characters each - pad the last item with a trailing zero if it is only one digit long.
Make a string using the resultant charcodes of the previous list.

Without further ado, here's the compress and decompress methods (tinybf.py):

def compress(code):
    """compress(code): Compress a string of Brainfuck code into TinyBF format."""
    translated = code.translate({62: 50, 60: 51, 43: 52, 45: 53, 46: 54, 44: 55, 91: 56, 93: 57})
    return "".join(chr(int(translated[pos:pos + 2].ljust(2, "0"))) for pos in range(0, len(translated), 2))

def decompress(code):
    """decompress(code): Decompress a string of TinyBF code into Brainfuck format."""
    translated = "".join(str(ord(c)) for c in code).translate({50: 62, 51: 60, 52: 43, 53: 45, 54: 46, 55: 44, 56: 91, 57: 93})
    return translated.rstrip("0")

And here's the script/output I used to test it:

import tinybf

original_code = "--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+."
compressed_code = tinybf.compress(original_code)

print(compressed_code) # 7#!00"7!'!7?,,,?#B!?.>!$,.>?!.
print(len(original_code), len(compressed_code)) # 78 39

new_code = tinybf.decompress(compressed_code)
print(new_code == original_code) # True

Any advice on the code or improvements I could make? I'm also looking for name advice if possible - I settld on TinyBF for this question, but I also considered Braincrunch and Tinyfuck, so if you have thoughts on those, that'd be great.


texts: LeetCode: Best Time to Buy and Sell Stock II

texts:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

Please review for performance.

  Say you have an array for which the i-th element is the price of a
  given stock on day i.

  Design an algorithm to find the maximum profit. You may complete as
  many transactions as you like (i.e., buy one and sell one share of the
  stock multiple times).

  Note: You may not engage in multiple transactions at the same time
  (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.
Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/564/
    /// </summary>
    [TestClass]
    public class BestTimetoBuyandSellStockII
    {
        [TestMethod]
        public void AnswerIs7()
        {
            int[] prices = {7, 1, 5, 3, 6, 4};
            Assert.AreEqual(7, MaxProfit(prices));
        }

        public int MaxProfit(int[] prices)
        {
            int max = 0;
            for (int i = 0; i < prices.Length-1; i++)
            {
                if (prices[i] < prices[i + 1])
                {
                    max += prices[i + 1] - prices[i];
                }
            }
            return max;

        }
    }
}


texts: Defining a finite set of instances of a class to check against

texts:
I have a Type class that will have many instances. I get the instances from a web service. The Type class has a code instance field that uniquely ids an instance:
@Data
@AllArgsConstructor
public class Type {

 private String code;

}

Ten of these instances identify a special type. I have several places where I need to check if a Type is one of these special types:
aType.equals(new Type("specialType1")) || aType.equals(new Type("specialType2")) ||...

In other places, I need to find where aType is not a special type. To centralize these specialized types and the check, I put it in the Type class as follows:
@Data
@AllArgsConstructor
public class Type {

  private static final List<Type> specialTypes = Arrays.asList(new Type("specialType1"),...);
  private String code;

  public boolean isSpecialType() {
    return specialTypes.contains(this);
  }
}

Should specialTypes and the logic to compare a type to special types be in the Type class? Or would this type of logic be better in a service class? Should the special types be defined as enums?
Update
Type instances are created via use of open feign:
import org.springframework.cloud.openfeign.FeignClient;

@FeignClient(name="type-service")
public interface TypeClient {

   @GetMapping("/type")
   List<Type> getTypes();
}


texts: Deciding between four user statuses based on two flags

texts:
I think that the following code isn't really nice. I can't see however another way (other than a switch statement) to better implement this. Especially since I don't think replacing this with the strategy pattern for instance is a better way.

String status;
if(userHasContact&&contactHasUser) {
    status = "HAS_CONTACT";
} else if(userHasContact&&!contactHasUser) {
    status = "PENDING";
} else if(!userHasContact&&contactHasUser) {
    status = "ACCEPT_REQUEST";
} else {
    status = "ADD_CONTACT";
}

I want to return the value of status to the view (this code is from the controller) of the page to show to the user whether that profile he is seeing is already a contact, pending (he already sent a status), accept (it was sent to him), or remove (he already has him as contact).


texts:
Challenge can be found here

  Problem Statement

  Watson gives Sherlock an array A of length N. Then he
  asks him to determine if there exists an element in the array such
  that the sum of the elements on its left is equal to the sum of the
  elements on its right. If there are no elements to the left/right,
  then the sum is considered to be zero.  Formally, find an i, such
  that, A1+A2...Ai-1 =Ai+1+Ai+2...AN.

  Input Format:  The first line contains T, the number of test cases. For
  each test case, the first line contains N, the number of elements in
  the array A. The second line for each test case contains N
  space-separated integers, denoting the array A.

  Output Format:  For each test case print YES if there exists an element
  in the array, such that the sum of the elements on its left is equal
  to the sum of the elements on its right; otherwise print NO.

  Constraints:

  \$1 \le T \le 10\$
  \$1 \le N \le 10^5\$
  \$1 \le Ai \le 2×10^4\$
  \$1 \le i \le N\$

I'm having timeout issues on 2 of the test cases

I have tried two different approaches. Both is of \$O(n^2)\$

First was a recursive approach:

public static boolean isEven(int[] arr, int index, int leftSum, int rightSum) {
        int i = index-1;
        int j = index+1;

        while(i > -1) {
            leftSum += arr[i--];
        }

        while(j < arr.length) {
            rightSum += arr[j++];
        }
        return (leftSum == rightSum) ? true : (index == arr.length-1) ? false : isEven(arr, index+1, 0, 0);
    }

Other one was with the use of Navigable map:

public static boolean isEven(NavigableMap<Integer, Integer> map) {
       int left = 0;
       int right = 0;
       int n = map.size();
       while(n-- > 0) {
           left = right = 0;
           for(Integer i : map.tailMap(n+1).values())  right += i;
           for(Integer j : map.headMap(n).values()) left += j;
           if (left == right) return true;
       }
       return false;
   }

Here is how I read the input:

public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        final int N = s.nextInt();

        for(int i = 0; i < N; i++) {
            int NN = s.nextInt();
            int[] arr = new int[NN];
            for(int j = 0; j < NN; j++) {
                arr[j] = s.nextInt();
            }
            System.out.println(isEven(arr, 0, 0, 0) ? "YES" : "NO");
        }
    }

To avoid an \$O(n^2)\$ solution, I can't check every element in the array, or can I?


texts: Whiteboarding - Multiply all values in array except at the index for each

texts:
Consider this interview question:

  You have an array of integers, and for each index you want to find the
  product of every integer except the integer at that index.

  Write a method get_products_of_all_ints_except_at_index() that takes
  an array of integers and returns an array of the products.

  For example, given:

[1, 7, 3, 4]

  your method would return:

[84, 12, 28, 21]

  by calculating:

[7 * 3 * 4,  1 * 3 * 4,  1 * 7 * 4,  1 * 7 * 3]

  Here's the catch: You can't use division in your solution!

And here's my solution:

def get_products_of_all_ints_except_at_index(arr)
    products = []
    (0...arr.length).each do |index|
        product = 1
        arr.each do |num|
            if num != arr[index]
                product *= num
            end
        end
        products << product
    end
    products
end