texts: Changing element visibility based on multiple checkbox states

texts:
I am writing a script in JavaScript & HTML and have some optimization problems. In the for, loop I check a variable named visible in every if clause. I think it's meaningless because once I know that the variable value is false there is no need to check the remaining if clauses but skip to the last line. I thought about goto but don't want to use it, and don't know how to fix it.

<script>
function filterServices(){
    var download = document.getElementById('download').checked;
    var free = document.getElementById('free').checked;
    var pay = document.getElementById('pay').checked;
    var audio = document.getElementById('audio').checked;
    var video = document.getElementById('video').checked;
    var offline = document.getElementById('offline').checked;

    for (i = 0; i < serwisy.length; i++) {

        var serwis = serwisy[i];
        var el = document.getElementById(serwis[0]);
        var visible = true;

        if(download && visible){    visible = serwis[2] == 1 ? true : false;}
        if(audio && visible){   visible = (serwis[3] & (1 << 1)) != 0 ? true : false;}
        if(video && visible){   visible = (serwis[3] & (1 << 2)) != 0 ? true : false;}
        if(offline && visible){ visible = (serwis[3] & (1 << 3)) != 0 ? true : false;}
        if(free && visible){    visible = (serwis[4] & (1 << 1)) != 0 ? true : false;}
        if(pay && visible){ visible = (serwis[4] & (1 << 2)) != 0 ? true : false;}

        el.style.visibility = visible ? "visible" : "hidden";
        }
    }

Here's my attempt to fix it. However, it was not approved because I am allowed to use only logical operators and no reference to the HTML code.

<script>
function filterServices(){
    var download = document.getElementById('download').checked;
    var free = document.getElementById('free').checked;
    var pay = document.getElementById('pay').checked;
    var audio = document.getElementById('audio').checked;
        var video = document.getElementById('video').checked;
    var offline = document.getElementById('offline').checked;

    for (i = 0; i < serwisy.length; i++) {

        var serwis = serwisy[i];
        var el = document.getElementById(serwis[0]);

        if(download){
            if(serwis[2] != 1){ el.style.visibility = "hidden"; continue;}}
        if(audio){
            if((serwis[3] & (1 << 1)) != 0){    el.style.visibility = "hidden"; continue;}}
        if(video){
            if((serwis[3] & (1 << 2)) != 0){    el.style.visibility = "hidden"; continue;}}
        if(offline){
            if((serwis[3] & (1 << 3)) != 0){    el.style.visibility = "hidden"; continue;}}
        if(free){
            if((serwis[4] & (1 << 1)) != 0){    el.style.visibility = "hidden"; continue;}}
        if(pay){
            if((serwis[4] & (1 << 2)) != 0){    el.style.visibility = "hidden"; continue;}}

        el.style.visibility = "visible" : "hidden";
        }
    }

Does anyone have any idea how to improve this code?


texts: Speed optimization for transparent gradient blend algorithm

texts:
The following algorithm works correctly for the purposes that I need, which is to set the top side of an image with a transparent gradient blend. Any tips to optimize it for speed?

void ImageUtil::sectionAlphaGradient(uint32_t* pixelBuffer, const int width, const int gradientHeight)
{
    unsigned int pixelOffsetY, pixelIndex;
    uint8_t A, R, G, B;

    const unsigned short OPAQUE = 255;

    const uint32_t BACKCOLOR = 0x00000000;
    const uint8_t backR = (BACKCOLOR & 0x00FF0000) >> 16;
    const uint8_t backG = (BACKCOLOR & 0x0000FF00) >> 8;
    const uint8_t backB = (BACKCOLOR & 0x000000FF);

    for (unsigned int y = 0; y < gradientHeight; y++)
    {
        A = (uint8_t)((OPAQUE * y) / gradientHeight);

        pixelOffsetY = y * width;

        for (unsigned int x = 0; x < width; x++)
        {
            pixelIndex = pixelOffsetY + x;
            uint32_t pixelValue = pixelBuffer[pixelIndex];

            R = (pixelValue & 0x00FF0000) >> 16;
            G = (pixelValue & 0x0000FF00) >> 8;
            B = (pixelValue & 0x000000FF);

            R = (R * A + backR * (OPAQUE - A)) / OPAQUE;
            G = (G * A + backG * (OPAQUE - A)) / OPAQUE;
            B = (B * A + backB * (OPAQUE - A)) / OPAQUE;

            pixelBuffer[pixelIndex] = (uint32_t)((A << 24) | ((R & 0xFF) << 16) | ((G & 0xFF) << 8) | (B & 0xFF));
        }
    }
}


texts:
I've written a script in python to scrape e-mail addresses from different pizza shops located in los-angeles available in yellowpage traversing multiple pages. It is able to go one-layer deep and dig out email addresses. I believe, this crawler has got the ability to parse all the emails from any link no matter how many pages it has spread across. Just needed to adjust the last page number in the crawler.

Here is what I've written:

import requests
from lxml import html

link = "https://www.yellowpages.com"
for page_num in range(1,10):
  for item in html.fromstring(requests.get("https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=Los%20Angeles%2C%20CA&page={0}".format(page_num)).text).cssselect('div.info h2.n a:not([itemprop="name"]).business-name'):
    for data in html.fromstring(requests.get(link + item.attrib['href']).text).cssselect('a.email-business'):
      print(data.attrib['href'].replace("mailto:",""))


texts:
I'm learning Java concurrency by a TDD approach. Therefore I wrote a basic test case in JUnit to test the behaviour / expected results of 2 threads. I'm looking for feedback for this code. In particular, the feedback for using CountDownLatch. I'm not sure if it is used correctly.

package io.mincongh.concurrency;

import static org.junit.Assert.assertEquals;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Mincong Huang
 */
public class BasicConcurrencyTest {

  private CountDownLatch countDownLatch;
  private Map<Integer, Integer> map;

  @Before
  public void setUp() {
    countDownLatch = new CountDownLatch(2);
    map = new ConcurrentHashMap<>();
  }

  @After
  public void tearDown() {
    countDownLatch = null;
    map = null;
  }

  private class CounterThread extends Thread {

    @Override
    public void run() {
      for (int i = 0; i < 10; i++) {
        int prev = map.getOrDefault(i, 0);
        map.put(i, prev + 1);
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      countDownLatch.countDown();
    }
  }

  @Test
  public void testCounterThread() throws InterruptedException {
    CounterThread t1 = new CounterThread();
    CounterThread t2 = new CounterThread();
    t1.start();
    t2.start();
    int tries = 0;
    while (countDownLatch.getCount() > 0 && tries < 3) {
      countDownLatch.await(1, TimeUnit.SECONDS);
      tries++;
    }
    assertEquals(2, (int) map.get(1));
  }

}


texts:
I've been using flask-jwt-extended for my application and one of the problems I had was logging a session out and making sure the token is not usable anymore.

I've based my solution on the Blacklist and Token Revoking documentation page with a custom RevokedToken model:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class RevokedToken(db.Model):
    """
    Model is used as a storage to keep invalid/revoked tokens.
    Currently used for log out functionality.
    """
    __tablename__ = 'revoked_tokens'

    id = db.Column(db.Integer, primary_key=True)
    jti = db.Column(db.String(120))

    @classmethod
    def is_jti_blacklisted(cls, jti):
        query = cls.query.filter_by(jti=jti).first()
        return bool(query)

Logout resource:

class LogoutResource(Resource):
    @jwt_required
    def post(self):
        jti = get_raw_jwt()['jti']

        # invalidate access token
        revoked_token = RevokedToken(jti=jti)
        session.add(revoked_token)
        session.commit()

        return {}, 200

And the token_in_blacklist_loader() jwt function:

from flask_jwt_extended import JWTManager

jwt = JWTManager(app)

@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
    jti = decrypted_token['jti']
    return models.RevokedToken.is_jti_blacklisted(jti)

This looks straightforward enough, but, as we are talking about authentication, I thought I would ask if anyone sees any flaws or potential improvements to this approach?


texts:
In my nested for loops below, it is sometimes necessary to exit the outer loop and then continue program execution. Since loop labels and other goto-like constructions are heavily discouraged, I'm a bit afraid of raptors. Is this usage OK? Is there a better way to structure the program?

my @objects = load_objects();
OUTER: for my $obj ( @objects ) {
    for my $element ( @{$obj->elements} ) {
        if ( is_case_1( $element ) ) {
            ...
        } elsif ( is_case_2( $element ) ) {
            ...
        } else {
            warn "invalid element: $element";
            last OUTER;
        }
        stuff_that_assumes_valid_element( $element );
    }
    stuff_that_assumes_valid_object( $obj );
}
store_objects( @objects );


texts: SQL GROUPING SETS in Python using Pandas

texts:
The code below is intended to provide SQL's GROUPING SETS functionality in Python with the aid of Pandas.

Background on SQL GROUPING SETS

There are at least two advantages to doing this in Python:

it is less verbose than SQL, and
it provides a non-redundant set of aggregations without the need to manually specify them.

There is at least one disadvantage to doing this in Python:

memory usage is quite likely higher than would be in SQL.

I am posting this question in the hopes that the code can be cleaned up. Secondarily I am posting to determine if anyone would find this useful. The example below has been tested with Python 2.7.6 and Pandas 0.15.1.

from __future__ import division, print_function

import itertools as it
import pandas as pd

from pandas.util.testing import assert_frame_equal

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return it.chain.from_iterable(it.combinations(s,r) for r in range(len(s)+1))

def grouper(df,grpby=None,aggfunc=None):
    ''' produces aggregate DataFrame from DataFrames for non-redundant groupings
       `workingdf` is used to avoid modifying original DataFrame
    '''
    uniqcols = (i for i in grpby if len(df[i].unique()) == 1)
    pwrset = (i for i in powerset(grpby))
    s = set()
    for uniqcol in uniqcols:
        for i in pwrset:
            if uniqcol in i:
                s.add(i) # add a level of aggregation only when non-redundant

    workingdf = df.copy()
    #for idx,i in enumerate(powerset(grpby)):
    for idx,i in enumerate(s):
        print('  grouping by: {}'.format(i))
        if i != ():
            tmp = aggfunc( workingdf.groupby(i) )
        else:
            # hack to get output to be a DataFrameGroupBy object:
            #   insert dummy column on which to group by
            # old, naive code:
            #   tmp = aggfunc( workingdf )
            dummycolname = hash(tuple(workingdf.columns.tolist()))
            workingdf[dummycolname] = ''
            tmp = aggfunc( workingdf.groupby(dummycolname) )

        # drop the index and add it back
        if i == (): tmp.reset_index(drop=True,inplace=True)
        else: tmp.reset_index(inplace=True)

        for j in grpby:
            if j not in tmp: # if column is not in DataFrame add it
                tmp[j] = '(All)'

        # new list with all columns including aggregate ones; do this only once
        if idx == 0:
            finalcols = grpby[:]
            addlcols = [k for k in tmp if k not in grpby] # aggregate columns
            finalcols.extend(addlcols)

        # reorder columns
        tmp = tmp[finalcols]

        # creation of final DataFrame
        if idx == 0:
            final = tmp; del tmp
        else:
            final = pd.concat( [final,tmp] ); del tmp

    del workingdf

    final = final.sort(columns=finalcols)
    final.reset_index(drop=True,inplace=True)

    return final

def agg(grpbyobj):
    ''' the purpose of this function is to:
          specify aggregate operation(s) you wish to perform,
          name the resulting column(s) in the final DataFrame.
    '''
    tmp = pd.DataFrame()
    tmp['Total (n)'] = grpbyobj['Total'].sum()
    return tmp

if __name__ == '__main__':
    df = pd.DataFrame({'Area':['a','a','b',],
                       'Year':[2014,2014,2014,],
                       'Month':[1,2,3,],
                       'Total':[4,5,6,],})
    final = grouper(df,grpby=['Area','Year'],aggfunc=agg)
    print(final)

    # test against expected result
    expected = '''{"Area":{"0":"(All)","1":"a","2":"b"},
                   "Year":{"0":2014,"1":2014,"2":2014},
                   "Total (n)":{"0":15,"1":9,"2":6}}'''
    testfinal = pd.read_json(expected)
    testfinal = testfinal[final.columns.tolist()] # reorder columns
    try:
        # check_names kwarg True: compare indexes and columns
        assert_frame_equal(final,testfinal,check_names=True)
    except AssertionError as e:
        print(e)


texts: Reduce memory consumption of numpy function

texts:
I have a Numpy function that takes the values of an existing array X and a size (int) k equivalent to the columns of the array. This function does some calculations in a new array, to finally output the new array after the calculations are done.

def ff(x, k):
    newarr = np.zeros((x.shape[0], 1), dtype=np.uint32)
    newarr[:, 0] = x[:, 0] * 4
    for i in range(1, k - 1):
        newarr[:, 0] += x[:, i]
        newarr[:, 0] = newarr[:, 0] * 4
    newarr[:, 0] += x[:, -1]
    return newarr

newarr it's the array where the calculated data is stored, it's initialized with np.zeros and a dtype, and it has a shape of (y,1) where y is the length of the x array.

The first step is to store in the (only) column of the newarr the multiplication of the first column of the x by 4.

The iteration occurs over the columns 1 to k-1 of the original array (x).
Inside the iteration, the next step is to sum the values of the first column of x to the column of newarr.
Next, to multiply the column of newarr by 4
To finally, after the iteration is complete, sum the last column of the original array x to the column of newarr.

I'm looking for a way (if there's any) to avoid the creation of the newarr, and do the calculations in the original array. This', to reduce the memory usage of this function, mainly because the x tends to be very big in execution.

The x array looks like this.

array([[3, 3, 0, 1],
       [3, 0, 1, 0],
       [0, 1, 0, 2],
       [1, 0, 2, 2],
       [0, 2, 2, 3],
       [2, 2, 3, 1],
       [2, 3, 1, 3],
       .
       .
       .
       [2, 2, 0, 1]], dtype=uint8)

In this case, the k value would be 4.

Edit

For the sake of completeness, I've attached the memory profile of my solution and the proposed dot product, for a big x array: (248956413, 10).

My solution

Line #    Mem usage    Increment   Line Contents
================================================
18    322.0 MiB    322.0 MiB   @profile
19                             def ff(x, k):
20    322.0 MiB      0.0 MiB       newarr = np.zeros((x.shape[0], 1), dtype=np.uint32)
21   1271.7 MiB    949.8 MiB       newarr[:, 0] = x[:, 0] * 4
22   1274.2 MiB      0.0 MiB       for i in range(1, k - 1):
23   1274.2 MiB      0.0 MiB           newarr[:, 0] += x[:, i]
24   1274.2 MiB      2.5 MiB           newarr[:, 0] = newarr[:, 0] * 4
25   1274.2 MiB      0.0 MiB       newarr[:, 0] += x[:, -1]
26   1274.2 MiB      0.0 MiB       return newarr

Dot product.

Line #    Mem usage    Increment   Line Contents
================================================
18    321.7 MiB    321.7 MiB   @profile
19                             def ff2(x,k):
20   2221.2 MiB   1899.5 MiB       return x.dot(4 ** np.arange(k - 1, -1, -1))

I was expecting a reduction in memory usage. Clearly, I was wrong.


texts:
I have to make a linked list as a quasi-homework task, about which I have already asked two questions about here and here. Since the whole code is really big (400 lines approx.), I will include only the few functions I am asking you to review, although, if you need any more code, I will upload it.

Here is the .add(int, T) function:

public void add(int index, T data){
    if (getNode(index) == null){
        throw new NoSuchElementException();
    } else if (index<0 || index>=size){
        throw new NullPointerException();
    }

    Node<T> crntNode;
    Node<T> newNode = new Node<T>(data);
    crntNode = getNode(index);
    newNode.index = index;

    if (crntNode.previousNode != null) {
        crntNode.previousNode.nextNode = newNode;
    } else {
        firstNode = newNode;
    }
    crntNode.previousNode = newNode;
    newNode.nextNode = crntNode;
    crntNode = newNode;

    while (crntNode.nextNode != null){
        crntNode.index++;
        crntNode = crntNode.nextNode;
    }

    size++;
}

The .get(int) function:

public T get(int index){
    if(isEmpty() || index < 0 || index >= size){
        return null;
    }

    Node<T> crntNode;
    int count = size - index - 1;
    crntNode = lastNode;

    while (count > 0) {
        crntNode = crntNode.previousNode;
        count--;
    }

    return crntNode.data;
}

And the .remove(int) function:

public T remove(int index) {
    if (getNode(index) == null || isEmpty()) {
        return null;
    } else if (size == 1){
        size = 0;
        Node<T> crntNode = firstNode;
        firstNode = null;
        lastNode = null;
        return crntNode.data;
    }

    Node<T> crntNode = getNode(index);

    if (crntNode.nextNode != null){
        if (crntNode.previousNode != null){
            crntNode.previousNode.nextNode = crntNode.nextNode;
        } else {
            firstNode = crntNode.nextNode;
            firstNode.previousNode = null;
            size--;
            return crntNode.data;
        }
    }
    if (crntNode.previousNode != null){
        if (crntNode.nextNode != null) {
            crntNode.nextNode.previousNode = crntNode.previousNode;
        } else {
            lastNode = crntNode.previousNode;
            lastNode.nextNode = null;
            size--;
            return crntNode.data;
        }
    }
    crntNode = crntNode.nextNode;
    size--;

    for(int i = index; i < size-1; i++){
        crntNode = crntNode.nextNode;
        crntNode.index--;
    }

    return crntNode.data;
}

I thought a lot about improving these functions, but I can't seem to find a better concept. The reason might be my lack of knowledge, in which case, I hope you could help me.

Is this code efficient and error-safe enough to be used in real programming situations?


texts:
I am working on this HackerRank problem but running into time constraint issues.

Basically, given two arrays, we need to determine if the ith element of the second array is reachable by the ith element of the first array, where edges are determined by whether or not the gcd of the two node values is greater than some threshold. Below is my attempt but it times out for large inputs.

def computeGCD(x, y):
   while(y):
       x, y = y, x % y
   return x

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if start not in graph.keys():
        return []
    paths = []
    for node in graph[start]:
        if node not in path:
            newpaths = find_all_paths(graph, node, end, path)
            for newpath in newpaths:
                paths.append(newpath)
    return paths

def connectedCities(n, g, originCities, destinationCities):
    res = []
    graph = {i+1:[] for i in range(n)}
    for i in originCities:
        for j in range(n):
            if i != j+1 and computeGCD(i, j+1) > g:
                graph[i].append(j+1)

    for i in range(len(originCities)):
        paths = find_all_paths(graph, originCities[i], destinationCities[i])
        if len(paths) > 0:
            res.append(1)
        else:
            res.append(0)

    return res

Can you help me determine if there is something I can be doing more efficiently here, or if solving this via a graph is even the most appropriate way?


texts:
Can anyone comment on the efficiency of my code? I am new with Python using NumPy/SciPy and I am trying to program a lattice biological model where a certain (one and only one) species (represented by a nonzero element) occupies a lattice square (represented in the code by a 2D array). This species can reproduce to an adjacent and empty lattice square (represented by a zero element). (Quite similar to a lattice gas model.)

The part of the code that takes the longest time is the reproduction part (def repro) because it has to check whether a site is already chosen every time a random site is generated to avoid repetition (the first while loop in def repro). Can anyone suggest a faster way to do this?

I am thinking of creating a collection of indices (2D index) where I can choose a random element and delete it at the same time so that the while loop won't be necessary. How can I do this?

import numpy as np
import matplotlib.pyplot as plt
import random
import time
import csv

open('p14.4.csv','w').close()

t0 = time.time()

def dispose(matrix,dens,s,sp):
    limit = int(n*n*dens)
    for num in range(limit):
        i = np.random.randint(n)
        j = np.random.randint(n)
        while matrix[i,j] != 0:
            i = np.random.randint(n)
            j = np.random.randint(n)
        matrix[i,j] = sp
    return matrix

def mort(matrix,d):
    RN = np.random.random((n,n))
    casualty = (RN < d)
    matrix[...][casualty] = 0
    return matrix

def reprod(matrix,b):
    p = np.random.randint(-1,2)
    q = np.random.randint(-1,2)
    idx = np.random.randint(-1,0,(n,n))
    jdx = np.random.randint(-1,0,(n,n))
    for k in range(n*n):
        i = np.random.randint(n)
        j = np.random.randint(n)
        while (idx[i,j] == i and jdx[i,j] == j):
            i = np.random.randint(n)
            j = np.random.randint(n)
        idx[i,j], jdx[i,j] = i, j
        if matrix[i,j] != 0:
            spp = int(matrix[i,j])
            while ((i+p<0 or i+p>n-1) or (j+q<0 or j+q>n-1)):
                p = np.random.randint(-1,2)
                q = np.random.randint(-1,2)
            if matrix[i+p,j+q] == 0 and b[spp-1] > np.random.random():
                matrix[i+p,j+q] = matrix[i,j]
    return matrix

def csv_writer(data,path,line):
    with open(path, "a") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        writer.writerow(data)
        csv_file.close()
    return path

#birth rate
spp = 10
B = [0.57710226,0.57722738,0.577233935,0.577120507,0.576885731,0.576528293,
     0.576046935,0.575440457,0.574707715,0.573847625]
dr = 0.3

#initial density
initD = 0.005

#mortality rate
m = 0.1

#matrix size
n = 1000

#lattice system is initially empty
latsys = np.zeros((n,n))

#randomly place the species in the matrix
for i in range(1,spp+1):
    dispose(latsys,initD,spp,i)

#reproduction and mortality
for t in range(1):
    print t

    x=latsys

    #reproduction
    reprod(latsys,B)

    t3 = time.time()
    total3 = t3-t0
    print total3

    #mortality
    mort(latsys,dr)

    S1 = float(np.count_nonzero(x==1))/(n*n)
    S2 = float(np.count_nonzero(x==2))/(n*n)
    S3 = float(np.count_nonzero(x==3))/(n*n)
    S4 = float(np.count_nonzero(x==4))/(n*n)
    S5 = float(np.count_nonzero(x==5))/(n*n)
    S6 = float(np.count_nonzero(x==6))/(n*n)
    S7 = float(np.count_nonzero(x==7))/(n*n)
    S8 = float(np.count_nonzero(x==8))/(n*n)
    S9 = float(np.count_nonzero(x==9))/(n*n)
    S10 = float(np.count_nonzero(x==10))/(n*n)

    print S1,S2,S3,S4,S5,S6,S7,S8,S9,S10

    R = [t,S1,S2,S3,S4,S5,S6,S7,S8,S9,S10]

    path = "p14.4.csv"
    csv_writer(R,path,t)

SPCS = [S1,S2,S3,S4,S5,S6,S7,S8,S9,S10]
SURVIVORS = np.count_nonzero(SPCS)

print "The number of surviving species is ", SURVIVORS

t4 = time.time()
total4 = t4-t0
print 'Total simulation run time =', total4, 'second(s).'

#for graphing snapshots
plt.imshow(latsys, cmap=plt.cm.spectral, interpolation='nearest')
plt.colorbar()
plt.show()


texts: Database connection in constructor and destructor

texts:
I am playing with different ways to do database interaction in PHP, and one of the ideas I have been playing with is connecting to the DB in the constructor and disconnecting in the destructor. This is the code from my Database class.

function __construct()
{
  $this->link = mysql_connect($this->server.':'.$this->port, $this->username);
  if(!$this->link)
    die('Could not connect: '.mysql_error());

  if(!mysql_select_db($this->database, $this->link))
    die('Could not select database: '.mysql_error());
}

function __destruct()
{
  if(mysql_close($this->link))
    $this->link = null;
}

This works well, my only reservation is that if I need to connect several to hit the database several times it will do multiple connections and disconnects. If I do that a lot I can see, maybe, potential problems. Is this a concern or is there a better way to do this? And is my code even up to snuff in general?


texts: Reading Large Files in Java getting really slow

texts:
I am trying to read a large file ~200 MB (~300 million lines of text). I am using a relatively standard way of reading like:

for (int i = 1; i <= numProcs; i++) {
    System.out.println("Parsing " + traceFilePrefix + i + ".prg");
    System.out.println("##########################");

    try {
        String line;
        int instrType;
        String hexAddr;
        ArrayList<Trace> traces = new ArrayList<Trace>();

        int lineNum = 1;

        BufferedReader br = new BufferedReader(new FileReader(traceFilePrefix + numProcs + "/" + traceFilePrefix + i + ".PRG"));
        while ((line = br.readLine()) != null) {
            line = line.toUpperCase();
            // validate line format
            if (line.matches(regexLineFormat)) {
                StringTokenizer tokenizer = new StringTokenizer(line);
                instrType = Integer.parseInt(tokenizer.nextToken());
                hexAddr = tokenizer.nextToken();

                traces.add(new Trace(instrType, hexAddr));
            } else {
                // line is in invalid format
                System.err.println("ERR: line " + lineNum + " is invalid \"" + line + "\"");
            }
            lineNum++;

            if (lineNum % 1000 == 0) System.out.println("line " + lineNum);
        }
        br.close();
        processorsTraces.add(i-1, traces);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I find that reading slows down at about line 20 million... in face it doesnt seem to progress at all ... how can I improve this? Whats the problem in this simple piece of code?

A latest run seem to run out of heap space ... I guess I cant store data in an arraylist like that?

This is supposed to be a simulator. It first parses trace files containing hexadecimal addresses of memory accesses. Then is supposed to run simulation of these data. This code snipplet only parses and stores the traces in an arraylist.


texts:
I've created this code which can call functions/ajax requests or pieces of code sequentially, using jQuery. The code not only can call functions/ajax requests or pieces of code sequentially but it also tracks when those calls fail or succeed and when the code fails it stops and doesn't exectue the rest of the queue.
(Bold italic are the names of the queues)
In my example i've 5 timeouts who get queued, the 2 first share a queue named first (1 and 1b) get executed at the same time and when those 2 finish and succeed(fire resolve) the next on the queue gets executed (next in queue is two which contains only 1 timeout). After two gets executed and succeed the third gets executed. I've coded in a way that the third fires a reject which changes the state of promise to reject(fails the request) and thanks to that the last timeout doesn't get called(to simulate a failed ajax request).

I know the code is pretty messy (it's my first version).  I would like some ideas on how I could structure this better or reduce the code considerably.

A problem I have with my code is that when I add a setTimeout, I have to include the deferred.resolve() in it.  I don't see a way around this.  Does anyone have an idea how to resolve this problem?

Code: http://jsfiddle.net/g55PC/

function myqueue(){
    var myself=this;
    var ord=[];// contains names used in promiseArr
    var funcArr=[];// contains setTimeout functions
    var me = $(document);

    this.add = function (func, name) {
        if (typeof funcArr[name] !== "object") funcArr[name] = [];

        funcArr[name].push(func);
        if($.inArray(name, ord)==-1){
            ord.unshift(name);
        }

    }

    this.call= function (name) {

        me.queue("deferQueue", function () {

            var promiseArr=[];

            for(func in funcArr[name]){
                promiseArr[func]=(function(){
                    var dfd = new jQuery.Deferred();
                    funcArr[name][func](dfd);
                    return dfd.promise();
                })();
            }

            $.when.apply($,promiseArr).then(function () {
                console.log("Success "+name);
                me.dequeue("deferQueue");
            }, function () {
                console.log("Fail "+name);
            });
        });
    }
    this.start = function () {
        while(ord.length>0) {
            this.call(ord.pop());
        }
        me.dequeue("deferQueue");
    }
};
myPlugin = new myqueue();
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
1
");
        //console.log("1");
        dfd.resolve();
    }, 2000);
}, "first");//first = queue Name
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
1b
");
        //console.log("1b");
        dfd.resolve();
    }, 1000);
}, "first");//first = queue Name
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
2
");
        //console.log("2");
        dfd.resolve();
    }, 1000);
}, "second");//second = queue Name
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
3
");
        //console.log("3");
        dfd.reject();
    }, 500);
}, "third");//third = queue Name
//forth will not be fired since third failed
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
4
");
        //console.log("4");
        dfd.resolve();
    }, 3000);
}, "forth");//forth = queue Name

myPlugin.start();


texts: Improving Performance of Numba For-Loop and Matrix Multiplication for Time Integration Solver

texts:
I am writing some code that performs a simple time-history integration solver (Newmark method for structural dynamics) and I looking for some suggestions in how I can improve the performance of my code. Currently, I am calculating a parameter called displacements for many time steps (think on the order of 5,000,000 steps). From profiling the code without using numba it is apparent that the matrix multiplication seems to be slowing down the script in the for-loop. Some details about the input:

num_steps = number of time-steps to perform the calculation (5,000,000)

dofs = number of degrees of freedom in the system, this also defines the matrix sizes as (dofs, dofs) before this function is called

yF = vector of size (num_steps, 1)

k_hat_inv, a1, a2, a3 = are all square, symmetric matrices of size (dofs, dofs)

vel_const1, vel_const2, vel_const3, acc_const1, acc_const2, acc_const3 = are constant floats

disp_save, disp_steps = are all ints

For a simple example when dofs = 10 this code runs very quickly (~14s) but as dofs increases to 1280 the run time increases significantly (still running after 1.5 days) and I would like to find some ways to decrease this run time. I have tried running the algorithm using parallel = True and the prange function in Numba but this doesn't provide the correct solution. Are there any other ways that I can improve the performance of this code?

@jit(nopython=True, cache=True)
def newmark_looper(num_steps, dofs, yF, k_hat_inv, a1, a2, a3, vel_const1, vel_const2, vel_const3,
acc_const1, acc_const2, acc_const3, disp_save, disp_steps):

# Time-stepping solution as per Chopra, 2017
print('     Time History Started')

# Initialize some variables
cdisp = np.zeros(dofs-2)
cvel = np.zeros(dofs-2)
caccel = np.zeros(dofs-2)
loading_vec = np.zeros(dofs-2)
disp_counter = 0
displacements = np.zeros((dofs-2, disp_steps))

for count in range(num_steps):

    # Obtain the force for the next time step, i.e i+1
    loading_vec[-2] = yF[count+1]

    # Obtain the force for the next time step, i.e i+1
    # P_i_p1 = loading_vec[:, count+1].copy()

    # Obtain P_i_p1_hat
    P_i_p1_hat = loading_vec + a1@cdisp + a2@cvel + a3@caccel

    # Calculate the displacement due to this force, u_i+1 = k_hat_inv * P_i_p1
    u_i_p1 = k_hat_inv @ P_i_p1_hat

    # Calculate the velocity due to this displacement, u_dot_i+1
    udot_i_p1 = vel_const1*(u_i_p1-cdisp) + vel_const2*cvel + vel_const3*caccel

    # Calculate the acceleration due to this displacement, u_2dot_i+1
    u2dot_i_p1 = acc_const1*(u_i_p1-cdisp) - acc_const2*cvel - acc_const3*caccel

    # Get current values for the next step
    cdisp[:] = u_i_p1
    cvel[:] = udot_i_p1
    caccel[:] = u2dot_i_p1

    # Write the displacement
    if count % disp_save == 0:
        disp_counter += 1
        displacements[:, disp_counter] = u_i_p1

print('     Time History Analyzed')

return displacements


texts: Combining two Arrays of hashes based on a hash key

texts:
I have two arrays of variable lengths: people1 and people2. I want to create an array of arrays where each inner array is a pair of elements from people1 and people2 The pairing should be based on a matching key. I'm using Ruby 2.2.0.

For example, given this input:

people1 = [{ name: :jon, id: 1 }, { name: :jay, id: 3 }, { name: :ray, id: 5 }]
people2 = [{ name: :jon, id: 2 }, { name: :ray, id: 7 }]

I would like this result:

pairs = [
  [{ name: :jon, id: 1 }, { name: :jon, id: 2 }],
  [{ name: :ray, id: 5 }, { name: :ray, id: 7 }]
]

Here's what I came up with:

people1.collect do |p1|
  if p2 = people2.find { |p2| p1[:name] == p2[:name] }
    [p1, p2]
  else
    nil
  end
end.compact

I looked at Array#zip, but it doesn't seem to take a condition. Is there a more idiomatic way to do this?


texts: Project Euler 348: Sum of a square and a cube

texts:
Many numbers can be expressed as the sum of a square and a cube. Some of them in more than one way.

  Consider the palindromic numbers that can be expressed as the sum of a
  square and a cube, both greater than 1, in exactly 4 different ways.
  For example, 5229225 is a palindromic number and it can be expressed
  in exactly 4 different ways:

  22852 + 203

  22232 + 663

  18102 + 1253

  11972 + 1563

  Find the sum of the five smallest such palindromic numbers.

I used brute force; it solves in around 11 seconds. I thought about it for some time but couldn't come up with any obvious optimizations, the problem seems built for brute force. Any suggestions?

Note that I'm using PyPy which makes math code run much faster...

"""Find the sum of the five smallest palindromic numbers
that can be expressed as the sum of a square and a cube."""

from math import log10
from collections import Counter
from timeit import default_timer as timer

def is_palindrome(n):
    length = int(log10(n))
    while length > 0:
        right = n % 10
        left = n / 10**length
        if right != left:
            return False
        n %= 10**length
        n /=10
        length -= 2
    return True

start = timer()
palindromes = Counter()

for square in xrange(1, 30000):
    squared = square**2
    for cube in xrange(1, 3000):
        cubed = cube**3
        total = squared + cubed
        if is_palindrome(total): palindromes[total] += 1

ans = sum(x[0] for x in palindromes.most_common(5))
elapsed_time = timer() - start
print "Found %d in %d s." % (ans, elapsed_time)


texts: Using Barrier to Implement Go's Wait Group

texts:
I have implemented a WaitGroup class to simulate WaitGroup in Go lang. Then I've found that I can use Barrier in a different manner, to achieve the same thing. My WaitGroup has some additional functionality, but in most scenarios Barrier just would do.

Question: Do you spot any design flaws in this style of using Barrier?

Code:

I have an instance of Barrier:

static Barrier WaitGroupBarrier = new Barrier(0);

Then I define my tasks (or threads) this way in multiple places - so I have not the actual number of tasks/threads:

for (int i = 0; i < 1000; i++) // in multiple places
{
    var t = new Task(() =>
    {
        try
        {
            WaitGroupBarrier.AddParticipant();

            // body
        }
        finally
        {
            WaitGroupBarrier.RemoveParticipant();
        }
    });

    t.Start();
}

And I wait for them to complete, this way:

if (WaitGroupBarrier.ParticipantsRemaining > 0)
{
    Console.WriteLine("waiting...");
    WaitGroupBarrier.SignalAndWait();
}


texts:
My first crack at clojure... if you have time to provide input, I'd appreciate it. I'm as much interested in style as proper usage. I'm just getting started.

The task to start with an vector of N zeros, and then "scramble" it by: Select 2 items in the vector. If one is less than 4, and the other is greater than -4, increment one and decrement the other -- so that the sum of the vector remains the same.

am I abusing let?
this generates a sequence of vectors, and I take the last one. Is there a better way to iterate and get the last result?
what tricks that I've missed?
this is just a small sample ;) but what community standards and practices have I missed?

code

(defn level [c] (let [n+ (rand-int (count c))
               n- (rand-int (count c))
               v+ (inc (nth c n+))
               v- (dec (nth c n-))
               go (and (not= n+ n-) (< v+ 4) (> v- -4))
               ]
           (if go (assoc (assoc c n+ v+) n- v-) c)
           ))

(defn rseq [n]
      (let [first (vec (repeat n 0))]
        (last (take (* n 2) (iterate level first)))))

(rseq 16)

(deftest rseq-sum-equals-2
  (let [actual (rseq 16)]
  (is (= 0 (apply + actual)))))
(run-tests 'ursound.core)


texts:
I have a durations as such:

[{'duration': 3600}, {'duration': 3600}]

And I want the output to be {3600: 2}, where 2 is the number of occurrences of 3600.

My first attempt is use a loop, as such:

    var count = {};
    for (var d of durations) {
        var length = d.duration;
        if (length in count) {
            count[length] += 1;
        }
        else {
            count[length] = 1;
        }
    }
    console.log(count);

The second attempt uses reduce() in lodash:

    function foo(result, value) {
        var length = value.duration;

        if (length in result) {
            result[length] += 1;
        }
        else {
            result[length] = 1;
        }

        return result;
    }
    var reduced = _.reduce(durations, foo, {});
    console.log(reduced);

As can be seen, this second attempt is still as verbose as before.

Is there a way to write the iteratee function foo more conform to functional programming?


texts:
I'm working with a third part service of my client that is providing me a list of products and services, which is a little bit of a mess.

The list will return all of the services for the product but the product repeats itself, for example:

The product A has the service A and the product A also has the service B so, when i receive the list i will get two products A with services A and B

What i need to do is to group all of the products to get only one with all of it's services and i have done so but i'm worried about performance because i think my solution isn't the 'best' one:

var productsNormalized = products.Data.AsEnumerable().Select(x => new ProdutoSSO
{
    CodigoServico = int.Parse(string.IsNullOrEmpty(x["CodigoServico"].ToString()) ? "0" : x["CodigoServico"].ToString()),
    CodigoPeca = int.Parse(string.IsNullOrEmpty(x["CodigoPeca"].ToString()) ? "0" : x["CodigoPeca"].ToString()),
    CodigoFamilia = int.Parse(string.IsNullOrEmpty(x["CodigoFamilia"].ToString()) ? "0" : x["CodigoFamilia"].ToString()),
    Familia = x["Familia"].ToString(),
    Servico = x["Servico"].ToString(),
    Peca = x["Peca"].ToString(),
    Hash = x["Hash"].ToString(),
    Valor = decimal.Parse(string.IsNullOrEmpty(x["Valor"].ToString()) ? "0" : x["Valor"].ToString())
})
.GroupBy(x => new { x.CodigoPeca, x.CodigoFamilia, x.Familia, x.Peca })
.Select(x => new ProdutoGroup
{
    Produto = new Produto
    {
        CodigoPeca = x.Key.CodigoPeca,
        CodigoFamilia = x.Key.CodigoFamilia,
        Familia = x.Key.Familia,
        Peca = x.Key.Peca
    },
    Servicos = x.Select(y => new ProdutoServico
    {
        CodigoServico = y.CodigoServico,
        Hash = y.Hash,
        Servico = y.Servico,
        Valor = y.Valor
    }).ToList()
});

Is there a better way to achieve this or this is as good as it gets?


texts:
I have some working Haskell code in a Yesod application that is responsible for creating a new paid Stripe subscription for a user.

Although it works, I'm not pleased with the walking indentation that appears as a result of nested Either case matches.

module Handler.Purchase where

import           Import
import           Web.Stripe
import           Web.Stripe.Customer
import           Web.Stripe.Plan
import           Web.Stripe.Subscription

postPurchaseR :: Handler Html
postPurchaseR = do
  -- I will need to keep a reference to the user later
  _ <- requireAuth

  -- I will need to keep a reference to the Stripe token later
  _ <- runInputPost $ ireq textField "stripeToken"

  -- I hard-code the secret key, which I'm fine with for now
  let config = StripeConfig $ StripeKey "<redacted>"

  -- Here's where things get hairy...
  customer <- liftIO $ stripe config createCustomer
  case customer of
    Left err -> do
      setMessage $ toHtml $ show err
      redirect (AppR :#: ("subscribe" :: Text))
    Right Customer { customerId = cid } -> do
      plan <- liftIO $ stripe config $ getPlan (PlanId "PRO")
      case plan of
        Left err -> do
          setMessage $ toHtml $ show err
          redirect (AppR :#: ("subscribe" :: Text))
        Right Plan { planId = pid } -> do
          subscription <- liftIO $ stripe config $ createSubscription cid pid
          case subscription of
            Left err -> do
              setMessage $ toHtml $ show err
              redirect (AppR :#: ("subscribe" :: Text))
            Right _ -> do
              setMessage "Subscription successful. Thanks!"
              redirect AppR

As I understand it, I should be using ExceptT instead of having all that nesting, but I'm not sure how that works. Correct use of ExceptT will probably obviate the need for me to define how to handle those three failures each time.


texts:
I was asked a question in an interview the other day:

  You have an array list of numbers from 1 to 100, the problem is that
  one number is missing. How would you find that number?

This is a mock of the question. The code seems to work.

Could you give me some feedback?

private int count;

public void find() {
    //prep for question
    List<Integer> ints = new ArrayList();
    for (int i = 0; i < 100; i++) {
        ints.add(i);
    }
    ints.remove(67);

    //find the missing number
    for (Integer i : ints) {
        if (i != count) {
            System.out.println(count);
            count++;
        }
        count++;
    }
}

Output = 67


texts: Getting the outliers of both dates and values

texts:
This is working now, but it looks very inelegant. I'm sure there is a nicer way of doing this.

# Get the outliers of both the dates and values
maxDate   = []
minDate   = []
maxVal    = []
minVal    = []
for k, v of series
  for d, i in v
    series[k][i][1] = nearZero if d[1] is 0
  series[k] = v = _.filter  v,    (d) -> not _.isNull d[1]
  maxDate.push  _.max       v,    (d) -> d[0]
  minDate.push  _.min       v,    (d) -> d[0]
  maxVal .push  _.max       v,    (d) -> d[1]
  minVal .push  _.min       v,    (d) -> d[1]
maxDate   = _.max _.map maxDate,  (d) -> d[0]
minDate   = _.min _.map minDate,  (d) -> d[0]
maxVal    = _.max _.map maxVal,   (d) -> d[1]
minVal    = _.min _.map minVal,   (d) -> d[1]


texts: Getting a connection to the database and executing statements

texts:
I've got two classes for getting a connection to the database and executing things, Class 'A' was made by me and Class 'B' was made by a colleague, we were wondering which one is better for use (Security, efficiency etc), that's why we are asking it here. Which one is better, and why is it? And how can we improve that one?

Class A:

class databaseHandler {

private $db;
private static $instance;

/*

This is the constructor of the PHP class, we create the object for databaseHandler here.

*/
function __construct() {
    $this->createConnection();
}

/*

We return an instance, if the object isn't created yet, we make it a new object and then return it.

*/
public static function getInstance() {
    if(!self::$instance) {
        self::$instance = new databaseHandler();
    }
    return self::$instance;
}

    /* returns the connection to the database, so we can use it to create statments */
public function getConnection() {
    return $this->db;
}

/*
Create a connection to the database, using constants to set the correct data for the connection.
*/
private function createConnection() {
    require 'config.php';
    try {
    $this->db = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE . ";charset=utf8", USERNAME, PASSWORD);

    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    } catch(PDOException $e) {
        echo $e->getMessage();
    }

    }

}
?>

Class B:

class DatabaseConnection
{
 public $dbc, $stmt, $result;

  public function __construct()
  {
    global $dbc;
    $dbc = new PDO("mysql:host=<removed host from post>;dbname=REDACTED", "REDACTED", "REDACTED");
  $dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }

public function closeConn ()
{
  global $dbc;
  $dbc = NULL;
}

public function selectAll ($tableName)
{
  global $dbc, $stmt, $result;

  $stmt = $dbc->prepare("SELECT * FROM $tableName");
  $stmt->execute();
  $result = $stmt->fetchAll();
  $this->closeConn();
  return $result;
}

public function getConnection() {
  global $dbc;
  return $dbc;
}

public function updateStock ($artnr, $amountToDecline)
{
  global $dbc, $stmt, $result;

  $stmt = $dbc->prepare("SELECT `stock` FROM `artikelen` WHERE `artnr` = $artnr");
  $stmt->execute();
  $result = $stmt->fetchAll();
  $updatedStock = $result[0]['stock'] - $amountToDecline;
  if ($updatedStock < 0) {
  return false;
  $this->closeConn();
  } else {
    $stmt2 = $dbc->prepare("UPDATE `artikelen` SET  `stock` = '$updatedStock' WHERE  `artikelen`.`artnr` = $artnr");
    $stmt2->execute();
    return true;
    $this->closeConn();
  }
}
}

We are asking this, as we are planning to use this on our first project with an actual customer.


texts:
Please consider this code for a TaxReturnCalculator (and ignore both the suboptimal use of float instead of BigDecimal and non-existing parameter validation):
public class TaxReturnCalculator {

    private static final float FIFTY_PERCENT = 0.5f;
    private static final float THIRTY_PERCENT = 0.3f;
    private static final float MAXIMUM_AMOUNT_TAX_RETURN = 1000f;

    public static float calculateTaxReturn(float income)
    {
        float basicTaxReturn = calculateBasicTaxReturn(income);

        float taxReturnAddition = calculateTaxReturnAddition(basicTaxReturn);

        float taxReturn = basicTaxReturn + taxReturnAddition;

        float taxReturnLimited = calculateTaxReturnLimited(taxReturn);

        return taxReturnLimited;
    }

    private static float calculateBasicTaxReturn(float income)
    {
        return income * FIFTY_PERCENT; // More complex calculation here
    }

    private static float calculateTaxReturnAddition(float basicTaxReturn)
    {
        return basicTaxReturn * THIRTY_PERCENT;  // More complex calculation here
    }

    private static float calculateTaxReturnLimited(float taxReturn)
    {
        float taxReturnLimited;

        if(taxReturn > MAXIMUM_AMOUNT_TAX_RETURN)
        {
            taxReturnLimited = MAXIMUM_AMOUNT_TAX_RETURN;
        }
        else
        {
            taxReturnLimited = taxReturn;
        }

        return taxReturnLimited;
    }
}

I designed the calculateTaxReturn(float income) method to follow the

One Level of Abstractoin per Function

practice recommended in Clean Code by Robert C. Martin: The three functions inside this method are on the same level of abstraction.
However, what doesn't seem well designed to me is that calculateTaxReturnLimited(taxReturn) is always called and thus always produces a taxReturnLimited -- even if the tax return is not to be limited (because it's smaller than the maximum amount)! Isn't this confusing?
Of course I could avoid this by not having a calculateTaxReturnLimited function at all and put it's code directly inside of the calculateTaxReturn, but that would vialote the One Level of Abstractoin per Function principle.
Renaming the function to something like limitTaxReturnIfNecessary doesn't seem good to me either, having multiple ...IfNecessary functions seems like a clutter and code smell to me.
Is this a trade-off? How can it be resolved best to follow best practices?


texts:
I am working on a small serialization function which serializes form input to json.

Here is the fiddle:
http://jsfiddle.net/jdQfj/2/

I have currently no idea how to split up the array declarations let alone a combination of array and object declaration. However the function works good with infinite object nestings and normal values. But I could believe that there is optimization room.

jQuery.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();

    $.each(a, function() {

        // check if object
        if (this.name.indexOf('.') !== -1) {
            var path = this.name.split('.');

            var current = o;
            for (var i = 0; i < path.length; i++) {
                if (i === (path.length - 1)) {
                    current[path[i]] = this.value;
                } else {
                    if (current[path[i]] === undefined) {
                        current[path[i]] = {};
                    }
                }
                current = current[path[i]];
            }

        // check if array
        } else if (this.name.indexOf('[') !== -1 && this.name.indexOf(']')) {
            console.log(this.name + ' is an array');

            // has to get implmented

        // normal value
        } else {
            o[this.name] = this.value;
        }

    });

    return o;
};


texts:
I am working through a PHP book, and date comparison was mentioned as one of the uses of usort(), so I wrote a date comparison function to use in line with usort(). Writing the function wasn't as easy as I expected (there was a pesky bug which took me a while to identify), so I thought I would submit my comparison code for review.

dates.php

<?
    function dateParse($date)
    {
        return (count(explode("-", $date)) == 3)?(explode("-", $date)):(explode("/", $date));   #Returns the date as an array.
    }

    function dateSort($date1, $date2, $format=1)
    {
        if ($format == 0)   #dd/mm/yyyy format.
        {
            list($day1, $month1, $year1) = dateParse($date1);
            list($day2, $month2, $year2) = dateParse($date2);
        }
        elseif ($format == 1)   #mm/dd/yyyy format.
        {
            list($month1, $day1, $year1) = dateParse($date1);
            list($month2, $day2, $year2) = dateParse($date2);
        }
        elseif ($format == 2)   #yyyy/mm/dd format.
        {
            list($year1, $month1, $day1) = dateParse($date1);
            list($year2, $month2, $day2) = dateParse($date2);
        }
        $day1 = str_pad($day1, 2, "0", STR_PAD_LEFT);   #Adds a leading "0" if the day is a single digit.
        $day2 = str_pad($day2, 2, "0", STR_PAD_LEFT);   #Adds a leading "0" if the day is a single digit.
        $month1 = str_pad($month1, 2, "0", STR_PAD_LEFT);   #Adds a leading "0" if the month is a single digit.
        $month2 = str_pad($month2, 2, "0", STR_PAD_LEFT);   #Adds a leading "0" if the month is a single digit.

        $x1 = $year1.$month1.$day1;
        $x2 = $year2.$month2.$day2;

        return ((int)$x1 <=> (int)$x2);
    }
?>


texts: Dynamically create instance variables from a list of classes

texts:
I have a situation, where I want to add many classes as instance variables of another class, plus perform some action on each class. The purpose is to have an 'app' with many 'views', to represent PageObjects.For instance:

class App
  attr_reader :login_view, :list_view, :create_view

  def initialize
    action([LoginView,ListView,CreateView])
    @login_view = LoginView.new
    @list_view = ListView.new
    @create_view = Create_view.new
  end
end

# App.new.login_view => [LoginView]

I came up with a solution which works:

module ClassToVar
  def create_instances_for(views)
    Array(views).each { |clazz| create_instance_for(clazz) }
  end

  private

  def create_instance_for(clazz)
    class_name = to_camel_case(clazz)
    variable_name = '@' + class_name
    instance_variable_set(variable_name, clazz.new)
    self.class.class_eval { attr_reader class_name.to_sym }
  end

  # *This could be done useing ActiveSupport, but I preferred to add it here*
  def to_camel_case(class_name)
    demodulize(class_name).gsub(/::/, '/')
                          .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
                          .gsub(/([a-z\d])([A-Z])/, '\1_\2').tr("-", "_").downcase
  end

  def demodulize(class_name)
    class_name.to_s.split('::').last
  end
end

# class App include ClassToVar
#   def initialize
#     create_instances_for([ListView, LoginView, CreateView])
# end
#

I think there has to be a different way to solve it: Either a simpler way, or a different design, so I don't need to take this approach.

Any advice?


texts: Validating an entity using a dynamic list of predicates

texts:
I have a generic extension method for validating my entities. The main idea is to be able to specify at runtime (context related) the criteria for validating a specific entity (with the end goal of saving it in the data base).

public static Boolean IsValidEntity<T>(this T entity, List<Predicate<T>> predicates)
{
    Boolean res = true;
    predicates.ForEach(p => res &= (Boolean)p.DynamicInvoke(entity));
    return res;
}

Inside my repository I can then use (simplified as this is not the scope but is somewhat  necessary for the question context):

public void SaveIntProperty(int myProperty, List<Predicate<int>> predicates)
{
    if (myProperty.IsValidEntity<int>(predicates))
    {
        //save to data base or other actions
    }
}

A simple example on a list of ints would be to search for elements which (in a particular context) need to be both even and less than 8.

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

//dynamically create the validation criteria
List<Predicate<int>> predicates = new List<Predicate<int>>();// List<Delegate>();
Predicate<int> lessThan = x => x < 8;
predicates.Add(lessThan);
Predicate<int> even = x => x % 2 == 0;
predicates.Add(even);

numbers.ForEach(n => SaveIntProperty(n, predicates));

The IsValidEntity extension method works and looks simple enough. However, I'm having doubts about the performance and the extensibility. Is the use of the ForEach ok? Should I pass the predicates differently? Should I use something else instead of predicates?


texts: Randomises capitalisation of letters like bird spongebob

texts:
A friend and I have an inside joke; well, not exactly inside if it is based off an existing meme. We would send messages in the 'retarded' form, as the meme 'Retarded Spongebob' does in the example "i WoUlD aPPreCiaTE sOmE fEeDbAcK oN mY CoDE". It takes in an input, loops through the character array formed from the string input, randomises the capitalisation, and the entire array is put back for output. Any improvements that can be suggested?

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class RetardedSpongebobifier {
    private char prevChar = 'z';

    public static void main(String[] args) {

        // Take input of sentence
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter desired sentence to RS.");
        // Save input
        String input = scanner.nextLine();
        // Turn input into a character array
        char[] inputArray = input.toCharArray();

        RetardedSpongebobifier obj = new RetardedSpongebobifier();
        // Create array to hold new array
        char[] charArray = new char[input.length()];

        // Run through the list of characters, maybe changing them to uppercase or lowercase
        for (int i = 0; i < input.length(); i++) {
            // Send character for random capitalizing
            char adding = obj.randCap(inputArray[i]);
            // Add uppercase/lowercase character back into the character array
            charArray[i] = adding;
        }

        // Print array
        System.out.print(new String(charArray));
    }

    private char randCap(char character) {

        // Check if character is not any of the blacklisted
        if (character == 'i' || character == 'l' || character == ' ' || character == ',' || character == '.') {
            prevChar = character;
            return character;
        }
        else {
            // Random TRUE/FALSE
            boolean isCap = (Math.random() * 100) >= 50;
            if (isCap && Character.isLowerCase(prevChar)) {
                prevChar = character;
                // Return uppercase letter
                return Character.toUpperCase(character);
            }
            else {
                prevChar = character;
                // Return lowercase letter
                return Character.toLowerCase(character);
            }
        }
    }
}


texts: Return product ID, if it is specified in a form

texts:
I often encounter this problem - I need to get some value, if it exists, and then do something with that value.

Getting that value becomes a separate method, and since that value might not exist, I need to indicate that somehow. For example, I might have a method that returns a productId if a product is attached to the form the user is filling out. If it doesn't exist, I can return 0, which is an invalid productId, which is a magic number.

My current problem with this instance is this:

public int GetProductIdFromFormIfAny(JObject form)
{
  int productId = 0; //default to 0
  IList<FormComponentMetadata> formFields = ParseFormForDropdowns(form);
  bool isProductAttached = formFields.Any(field => field.DataLookupTable == "Products");
  if(isProductAttached){
    FormComponentMetadata productField = formFields
      .Single(field => field.DataLookupTable == "Products");
    string filterStringContainingProductId = productField.DataLookupFilter;
    productId = filterStringContainingProductId.Split("=")[1];
  }
  return productId;
}

I don't know how to get around the magic number issue. I can create a new class, which holds an id and a bool indication whether or not that id exists, but that seems very heavy-handed and a LOT of extra code that someone has to maintain, even though the tradeoff is clarity.

As a side note, this is what comes back for the filterStringContainingProductId: "data_lookup_filter":"Product_ID=9" - I am not sure how to make the Split("=")[1] clear without comments or constants, which, again, seem heavy.

Edit: Looks something like this when refactored to use nullable types.

 public int? GetProductIdFromFormIfAny(JObject form)
{
  IList<FormComponentMetadata> formFields = ParseFormForDropdowns(form);
  bool isProductAttached = formFields.Any(field => field.DataLookupTable == "Products");
  int? productIdOrNull = isProductAttached ?GetExistingProductId(formFields) : default(int?);
  return productIdOrNull;
}

private int GetExistingProductId(IList<FormComponentMetadata> formFields)
{
  const string keyValueSeparatorChar = "=";
  const int idxOfProductId = 1;
  FormComponentMetadata productField = formFields
  .Single(field => field.DataLookupTable == "Products");
  string filterStringContainingProductId = productField.DataLookupFilter;
  string productIdSegment = filterStringContainingProductId.Split(keyValueSeparatorChar)[idxOfProductId];
  int productIdAsInt = int.Parse(productIdSegment);
  return productIdAsInt;
}

Seems like a ton of code for something so trivial...


texts:
I posted a couple of weeks ago with a double linked list.  It was recommended that I rewrite the code as a singlely linked list and replace the recursive parts with loops.

I've gone ahead and made several edits and was hoping to get another critique of the code.

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

struct file {
    int fd;
    struct file *next;
};

struct file *create_head(void) {
    struct file *first_link = malloc ( sizeof *first_link );
    return first_link;
}

void insert(struct file *node, int val) {
    while (node->next != NULL) {
        node = node->next;
    }
    struct file *tail = malloc ( sizeof *tail );
    node->next = tail;
    tail->fd = val;
    tail->next = NULL;
}

int delete(struct file *node, int val) {
    struct file *prev;
    while (node->fd != val) {
        if(!(node->next)) {
            return 1;
        }
        else {
            prev = node;
            node = node->next;
        }
    }
    prev->next = node->next;
    free(node);
    return 0;
}

int locate(struct file *node, int val) {
    while (node->fd != val) {
        if (!(node->next)) {
            return 1;
        }
        else {
            node = node->next;
        }
    }
    printf ("Value %d in list\n", val);
    return 0;
}

void dump(struct file *node) {
    while (node->next) {
        printf ("Node: %d\n", node->fd);
        node = node->next;
    }
    printf ("Node: %d\n", node->fd);
}

int get_choice(void) {
    int choice;
    int val;
    struct file *head = NULL;
    while ( true ) {
        printf ("\n[Choices - Insert=1, Delete=2, Locate=3, Dump=4, Exit=5]\n");
        printf ("\nEnter selection: ");
        scanf("%d", &choice);
        switch (choice) {
            case (1):
                printf ("Enter value: ");
                scanf ("%d", &val);
                if (!(head)) {
                    head = create_head();
                    head->fd = val;
                    head->next = NULL;
                }
                else {
                    insert(head, val);
                }
                break;
            case (2):
                if (head) {
                    printf ("Enter value: ");
                    scanf ("%d", &val);
                    if (head->fd == val && head->next == NULL) {
                        head = NULL;
                    }
                    else if (head->fd == val && head->next != NULL) {
                        free (head);
                        head = head->next;
                    }
                    else if (delete(head, val) == 1) {
                        printf ("Value %d not in list\n", val);
                    }
                }
                else {
                    printf ("List is empty!\n");
                }
                break;
            case (3):
                if (head) {
                    printf ("Enter value: ");
                    scanf ("%d", &val);
                    if (locate(head, val) == 1) {
                        printf ("Value %d not in list\n", val);
                    }
                }
                else {
                    printf ("List is empty!\n");
                }
                break;
            case (4):
                if (head) {
                    dump(head);
                }
                else {
                    printf ("Nothing to dump!\n");
                }
                break;
            case (5):
            return 0;
        }
    }
}

int main(void) {
    printf ("\nSingle Linked List: \n");
    get_choice();
    return 0;
}


texts: Check if is it possible to get to a point that is presented by a number

texts:
Problem description from an Iranian online course, translated with the help of Google Translate:

Tired of coding, Mehdi has gone on to his childhood games. But because he doesn't know who to play with, he has to change the rules of the game and play solitaire. To begin with, he wants to play solitaire "Walnut, Break Out".
Mehdi is standing n cm from the wall and wants to reach the wall. To do this, he can extend his leg forward, or transverse his leg forward. The goal is for him to stretch his legs and move forward so that he can tangle with the wall at the end. But Mehdi doesn't code anymore, so you need to help him figure out how to win this game. That is, tell him to stretch his leg a few times and cross a few times to get the exact distance.
The problem is about checking whether we can get to a wall that is represented with a number, by horizontal and vertical moves or not. If we can, print one of the correct answers and we cant, print -1.

We have three input values: The distance to the wall \$ n \$ , the foot length \$ x\$ , and the foot width \$ y\$ . The values are restricted by
$$
1 \le n,x,y \le 100\,000 \, .
$$
We have to check if \$ n \$ is a multiple of \$ x \$ plus a multiple of \$ y \$. For example if \$n = 10 \$and \$x = 2 , y=3\$ , we can reach to \$10\$ with multiplying \$2 \cdot 2 + 3 \cdot 2 \$, or \$2 \cdot 5 + 3 \cdot 0 \$.
I wrote this code for it. I get correct answers for most of the test cases except one, and 2 errors for a time limit exceeded. I am looking for an optimized and faster solution.
#include<iostream>
using namespace std;
int main()
{
    int n,x,y;
    int x1,y1;
    cin>>n>>x>>y;
    bool flag = false;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n+1;j++)
        {
            if (x * i + j * y == n)
                {
                    flag = true;
                    x1=i;
                    y1=j;
                }
        }
         if(flag)
            break;
    }
    if(flag == false)
        cout<<"-1";
    else
    cout<<x1<<" "<<y1;

    return 0;
}


texts:
Inspired by this question: To calculate the total CPU usage as a percentage

I wrote the following bash script (as an answer) to calculate the CPU usage for a (configurable) period over all CPU cores on a host.

#!/bin/bash

#CORECOUNT=$(grep cpu /proc/stat | grep -v 'cpu ' | wc -l)
#echo $CORECOUNT cores not needed for calculation though

DELAY=${1:-1}

function getstat() {
    grep 'cpu ' /proc/stat | sed -e 's/  */x/g' -e 's/^cpux//'
}

function extract() {
    echo $1 | cut -d 'x' -f $2
}

function change() {
    local e=$(extract $ENDSTAT $1)
    local b=$(extract $STARTSTAT $1)
    local diff=$(( $e - $b ))
    echo $diff
}

#Record the start statistics

STARTSTAT=$(getstat)

sleep $DELAY

#Record the end statistics

ENDSTAT=$(getstat)

#http://www.mjmwired.net/kernel/Documentation/filesystems/proc.txt#1236
#echo "From $STARTSTAT"
#echo "TO   $ENDSTAT"
#     usr    nice   sys     idle       iowait irq    guest
#From 177834 168085 1276260 3584351494 144468 154895 0 0 0 0
#TO   177834 168085 1276261 3584351895 144468 154895 0 0 0 0

USR=$(change 1)
SYS=$(change 3)
IDLE=$(change 4)
IOW=$(change 5)

#echo USR $USR SYS $SYS IDLE $IDLE IOW $IOW

ACTIVE=$(( $USR + $SYS + $IOW ))
TOTAL=$(($ACTIVE + $IDLE))
PCT=$(( $ACTIVE * 100 / $TOTAL ))

echo "BUSY $ACTIVE TOTAL $TOTAL $PCT %"

The key features I wanted to ensure are just a single read of the stat file at the beginning, and another single read at the end.

There is some debate about what constitutes 'active' time (Is IOWait busy, or idle time?) If you have insights on that, I would appreciate that too.

All suggestions and criticisms welcome.


texts:
I have a a python function for taking in a 2D numpy array and checking if each element is the same as its neighbor elements. I feel like there's a more efficient way to do this but I'm not sure. Here is the code:

import numpy as np

def compare_neighbors(arr):
    '''
    Checks if element (i,j) is different than (i-1,j),(i+1,j),(i,j-1), or
    (i,j+1).

    --Input--
    arr: (2D np.array) array to compare all elements of

    --Returns--
    comp_arr: (2D bool np.array) bool array with the resulting comparisons.
           True means the original element is the same as its neighbors,
           False means it was different than at least neighbor
    '''
    comp_arr = np.full(arr.shape, False, dtype=bool) #initialize
    arr_height = arr.shape[0]
    arr_width = arr.shape[1]

    for i in range(arr_height): #Row
        for j in range(arr_width): #column

            center = arr[i,j]

            #Check edges
            if i == 0: #left side
                left = arr[i,j]
            else:
                left = arr[i-1, j]

            if i == arr_height - 1: #right side
                right = arr[i,j]
            else:
                right = arr[i+1,j]

            if j == 0: #up
                up = arr[i,j]
            else:
                up = arr[i, j-1]

            if j == arr_width - 1: #down
                down = arr[i,j]
            else:
                down = arr[i, j+1]

            comp_arr[i,j] = len(set([left, right, up, down, center])) == 1
    return comp_arr

If it is helpful, here are the tests I used for testing it:

A = np.array([[1,1],
              [1,1]])

comp_arr_A = compare_neighbors(A)

B = np.array([[2,2],
              [2,2]])

comp_arr_B = compare_neighbors(B)

C = np.array([[1,1,1,1,1,1,1,1,1],
              [1,1,1,1,1,1,1,1,1],
              [1,2,2,2,2,2,2,2,1],
              [1,2,2,1,1,1,2,2,1],
              [1,2,2,2,2,2,2,2,1],
              [1,1,1,1,1,1,1,1,1]])

comp_arr_C = compare_neighbors(C)

D = np.array([[1,1,1],
              [1,2,1],
              [1,1,1]])

comp_arr_D = compare_neighbors(D)

print(A)
print()
print(comp_arr_A)
print()
print(B)
print()
print(comp_arr_B)
print()
print(C)
print()
print(comp_arr_C)
print()
print(D)
print()
print(comp_arr_D)

which returns

[[1 1]
 [1 1]]

[[ True  True]
 [ True  True]]

[[2 2]
 [2 2]]

[[ True  True]
 [ True  True]]

[[1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 2 2 2 2 2 2 2 1]
 [1 2 2 1 1 1 2 2 1]
 [1 2 2 2 2 2 2 2 1]
 [1 1 1 1 1 1 1 1 1]]

[[ True  True  True  True  True  True  True  True  True]
 [ True False False False False False False False  True]
 [False False False False False False False False False]
 [False False False False False False False False False]
 [False False False False False False False False False]
 [ True False False False False False False False  True]]

[[1 1 1]
 [1 2 1]
 [1 1 1]]

[[ True False  True]
 [False False False]
 [ True False  True]]

as expected. All I need the function to do is check each element and compare it to its left, right, above, and bellow neighbors. If it is the same as them then the compare_array in that index is True and if it is different than any of its neighbors then False.


texts:
My implementation:

Array.prototype.binarySearchFast = function(search) {

  var size = this.length,
      high = size -1,
      low = 0;

  while (high > low) {

    if (this[low] === search) return low;
    else if (this[high] === search) return high;

    target = (((search - this[low]) / (this[high] - this[low])) * (high - low)) >>> 0;

    if (this[target] === search) return target;
    else if (search > this[target]) low = target + 1, high--;
    else high = target - 1, low++;
  }

  return -1;
};

Normal Implementation:

Array.prototype.binarySearch = function(find) {
  var low = 0, high = this.length - 1,
      i, comparison;
  while (low <= high) {
    i = Math.floor((low + high) / 2);
    if (this[i] < find) { low = i + 1; continue; };
    if (this[i] > find) { high = i - 1; continue; };
    return i;
  }
  return null;
};

The difference being my implementation makes a guess at the index of the value based on the values at the start and end positions instead of just going straight to the middle value each time.

I wondered if anyone could think of any case scenarios where this would be slower than the original implementation.

UPDATE:
Sorry for the bad examples. I have now made them a little easier to understand and have setup some tests on jsPerf. See here:

http://jsperf.com/binary-search-2

I'm seeing about 75% improvement by using my method.


texts: Average of three biggest parameters out of five without using sorting algorithm or vector/array

texts:
I'm trying to create a function with has 5 input parameters and returns the average of the 3 biggest. However I'm not supposed to use a sorting algorithm, vector/arrays or function libraries and still try to develop the most efficient logic possible.

So far I've come up with the code below. Is it the most efficient possible considering the restrictions?

float avg3of5(float a, float b, float c, float d, float e) {
    float min;
    float min2;

    min = a;
    if (b < min) {
        min2 = min;
        min = b;
    }
    else {
    min2 = b;
    }

    if (c < min) {
        min2 = min;
        min = c;
    }
    else {
        if (c < min2) {
            min2 = c;
        }
    }

    if (d < min) {
        min2 = min;
        min = d;
    }
    else {
        if (d < min2) {
            min2 = d;
        }
    }

    if (e < min) {
        min2 = min;
        min = e;
    }
    else {
        if (e < min2) {
            min2 = e;
        }
    }

    Return = (a + b + c + d + e - min - min2) / 3
}


texts: Counting the frequency of letters in a string slices

texts:
While preparing a solution for the CodeChef - magic tricks, an easy question about counting the frequency of given character from the string slice, I came up with the following solution:

input_str = input("")
t = int(input(""))
for i in range(t):
    c, l1, l2 = input("").split()
    l, r = int(l1),int(l2)
    print(input_str[l-1:r].count(c))

But It turns out to be inefficient because it's not meeting the time constraint. How can I better implement it?

(here, the indexing starts from 1)


texts: Systemctl services start and UFW ports allow script

texts:
I made a script to start something akin to a "session" in which I start services and open tcp and udp ports in the firewall in order to work with, for example, a full stack project, and stop and close the
corresponding services and ports once I'm done using them.

When I call the script, I place the services with the -s options and the ports with -p. After the -s option I input all the services in I want to start and then likewise with the ports. You can skip the services and/or the ports.

When I start the script, it starts the services via systemctl start and opens the ports via ufw allow. Then it pauses and awaits a key press after which it stops the services and closes the ports.

The services on my system are managed by Systemctl. The firewall software I use is Uncomplicated Firewall (UFW).

Usage: ./start -s service1 service2 -p port1 port2

Example: ./start -s postgresql httpd -p WWW

#!/bin/bash
if [ $EUID != 0 ]; then
    sudo "$0" "$@"
    exit $?
fi

flag=
services=()
ports=()

while [ -n "$1" ]; do
    case "$1" in
        -s) flag="SERVICE" ;;
        -p) flag="PORT" ;;
        *)
            case $flag in
                SERVICE) services+=($1) ;;
                PORT) ports+=($1) ;;
            esac
            ;;
    esac
    shift
done

# Starts the services and opens the ports
start() {
    for serv in ${services[*]}; do
        echo "Starting service $serv"
        systemctl start $serv
    done

    for port in ${ports[*]}; do
        echo "Opening port $port"
        ufw allow $port &> /dev/null
    done
}

# Stops the services and closes the ports
finish() {
    for serv in ${services[*]}; do
        echo "Stopping service $serv"
        systemctl stop $serv
    done

    for port in ${ports[*]}; do
        echo "Closing port $port"
        ufw deny $port &> /dev/null
    done
}

# Catch ^c and terminal close signals:
trap finish 0

start

echo
echo "Awaiting interruption..."
echo

while :; do
    read -t 1 -n 1 -s PASSWORD
    if [ $? = 0 ] ; then
        break
    fi
done

I'm looking for feedback, mainly to see if I could improve this productive waste of time.

The new things I learned by doing this script were:

The parsing of options (-s and -p) with case ... in and shift;
The use of trap;
The "press key to continue" loop.

The only caveat I found was that even though I use trap to detect when the script dies it does not work if the terminal it runs on closes, leaving the services started. It doesn't work either if the signal I trap are SIGINT and SIGCHLD.

Thanks for reading.


texts:
I'm working on my ability to write loosely coupled applications that follow SOLID principles. This is a simple application trying to demonstrate the concept. Is it OK? Am I going along the right lines? What needs to be improved or changed?

I'd just like your overall opinion on the design structure and the code please. If you'd like a straightforward question to answer directly, then it'd be "Is this code that is appropriate to be used in production?"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LooselyCoupled
{
public class Program
{
    static void Main(string[] args)
    {
        //Usage
        Human human = new Human();
        human.Name = "John";
        human.Age = 36;

        Cat cat = new Cat();
        cat.Name = "Molly";
        cat.Age = 8;

        MovementManager movement = new MovementManager(human);
        movement.Move();

        MovementManager movement2 = new MovementManager(cat);
        movement2.Move();
    }

    //Interface to act as a middle man (inversion) to redirect the otherwise narrow flow
    public interface iMovement
    {
        void Move();
    }

    //A manager that has no idea of any implementation, but only an interface
    public class MovementManager
    {
        private iMovement movement;

        public MovementManager(iMovement movement)
        {
            this.movement = movement;
        }

        public void Move()
        {
            movement.Move();
        }
    }

    //I've decided that every class that implements iMovement will have certain attributes
    //therefore I've decided to add an abstract class into the mix (is this OK?)
    public abstract class BaseMovementEntity : iMovement
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public abstract void Move();
    }

    public class Human : BaseMovementEntity
    {
        public override void Move()
        {
            Console.WriteLine($"Name: {Name}, Age {Age} has begun moving...");
        }
    }
    public class Cat : BaseMovementEntity
    {
        public override void Move()
        {
            Console.WriteLine($"The little cat whose name is: {Name}, Age {Age} has begun moving to catch the dog...");
        }
    }
}
}


texts: Pass a table to a function depending on parameter selected by user

texts:
I wrote this function (extremely simplified here, the actual function does a lot more, or it wouldn't make sense to have another function inside it) as part of a Package that, when attached, loads four tables that are a combination of genome and platform arguments (i.e. hg19_27k, hg19_450k, hg38_27k, hg38_450k).
Then one of these tables is passed to the other function depending on what arguments the user has selected.
I was wondering if there's a better way to pass the table instead of assigning it to a generic "platform_data" variable and than pass it to the function.

select_informative_sites <- function(tumor, genome = c("hg19", "hg38"), platform = c("450k", "27k")) {

  platform_data <- get(paste0(platform, "_", genome))

  idx <- cluster_reduction(tumor, platform_data)

  return(idx)
}


texts: Controllers for interacting with a vacation service

texts:
I have a controller called VacationController; in this controller, I retrieve a list of vacations which will be displayed in a grid.

In the grid, I have the option to create a new vacation through a popup window. Should I create a new controller for this popup, considering that the model is represented by one row of the vacation list?

Those are my controllers:

app.controller('app.VacationController', ['$scope', 'vacationService', function ($scope, vacationService) {

    var vm = this;

    vm.model = {
        hasError: false,
        errorMessage: '',
        hasData:false,
        data: []
    }

    vacationService.get().success(function (vacations) {
        vm.model.hasData = vacations.length !== 0;
        vm.model.data = vacations;
    }).error(function() {
        vm.model.hasError = true;
        vm.model.errorMessage = 'Error';
    });

}]);

app.controller('app.NewVacationController', ['$scope', 'vacationService', function ($scope, vacationService) {

    var vm = this;
    vm.hasError = false;
    vm.error = '';
    vm.data = null;

    vacationService.getById(0).success(function (vacation) {
        vm.data = vacation;
    });

    vm.createNewVacation = function (viewModel) {
        vacationService.post(viewModel.data).success(function () {
            alert('success');
        });
    }
}]);


texts: Computing the weighted centroid dependent on previous row/column

texts:
I am working on a project for a Raspberry Pi that requires some image processing.

The aim is to find a white line on a black background by finding the weighted mean in each row/column. However to avoid this being skewed by other parts of the path that may also be in the picture I want to restrict the mean to within a tolerance of the last centroid computed with a known value for the first row/column As a mainly C++ programmer I initially wrote this code using for loops but this is very slow in python.

I have started reading about numpy arrays and vectorisation, however I am struggling to see how I might use them because of the dependency on the previous value calculated. This is my current attempt:

img = Image.open('Test2.png')

img = img.convert('L')
print("Size of image is:")
size = img.size
print(img.format, img.size, img.mode)

pixels = np.asarray(img)
width, height = img.size

average_index_rows = []
average_index_rows.append(int(width/2))
average_index_cols = []
average_index_cols.append(int(height/2))
tol = 20

for cc in range(0, width):
    min_index = max(0, average_index_cols[cc] - 20)
    max_index = min(height, average_index_cols[cc] + 20)
    sub_array = np.asarray(pixels[cc, min_index:max_index])
    y = sub_array.sum()
    next_centroid = compute_weighted_centroid((sub_array))
    if next_centroid!= next_centroid:
        break
    else:
        average_index_cols.append(next_centroid)

for rr in range(0, height):
    min_index = max(0, average_index_rows[rr]-20)
    max_index = min(height, average_index_rows[rr]+20)
    sub_array = pixels[min_index:max_index, rr]
    next_centroid = compute_weighted_centroid((sub_array))
    if next_centroid!= next_centroid:
        break
    else:
        average_index_rows.append(next_centroid)

img = img.convert('RGB')
img_pixel = img.load()

for rr in range(1, len(average_index_rows)):
    if average_index_rows[rr] != -1:
        current_average_pixel = average_index_rows[rr]

        for pixel in range(-3,3):
            if (current_average_pixel+pixel > 0) and (current_average_pixel+pixel < height):
                img_pixel[rr-1, current_average_pixel+pixel ] = (255,10,10)

for cc in range(1, len(average_index_cols)):
    if average_index_cols[cc] != -1:
        current_average_pixel = average_index_cols[cc]

        for pixel in range(-3,3):
            if (current_average_pixel+pixel > 0) and (current_average_pixel+pixel < width):
                img_pixel[current_average_pixel+pixel, cc-1 ] = (10,255,10)

img.show()

Is there a better way to formulate this to improve the speed?


texts: Comparator classes supporting operations on sets

texts:
I have a class Comparator that does several operations (union, intersection, etc) on 'sets'.  In this specific case each 'set' is a 3 dimensional array.

in order to do these operations, I have to use a nested foreach to loop through each dimension before getting to the data I need to compare against.

I figure there are two ways to implement this.  One is to simply do the loop in each operation, like so:

class Comparator  {

    //union is the set of unique elements from both setA and setB
    public function union()  {
        //initially add $setB to $union resultset.
        $union = self::$setB;

        foreach (self::$setA as $k => $v)  {
            foreach ($v as $k2 => $v2)  {
                foreach ($v2 as $k3 => $element)  {
                    if (!isset($union[$k][$k2][$k3]))  {
                        //add $element to $union resultset if it does not already exist in $union.
                    }
                }
            }
        }

        return $union
    }

    //Set of elements in setB that are not in setA.
    public function rightComplement()  {
        $complement = self::$setB

        foreach (self::$setA as $k => $v)  {
            foreach ($v as $k2 => $v2)  {
                foreach ($v2 as $k3 => $element)  {
                    //if $element is in setA, remove it from $complement.
                    unset($complement[$k][$k2][$k3]);
                }
            }
        }

        return $complement;
    }
}

Problem is I have about 9 other operations that all operate off of an identical loop... just a different thing is done inside the final foreach.

The other way is bit drier, but I feel somewhat confusing:

class Comparator  {

    //union is the set of unique elements from both setA and setB
    public function union($args = null)  {
        //initially add $setB to $union resultset.
        $union = self::$setB;

        if ($args === null)  {
            $this->iterate(self::$setA, __FUNCTION__);
        }  else  {
            if (!isset($union[$args['k']][$args['k2']][$args['k3']]))  {
                //add $element to $union resultset if it does not already exist in $union.
            }
        }

        return $union
    }

    //Set of elements in setB that are not in setA.
    public function rightComplement($args = null)  {
        $complement = self::$setB

        if ($args === null)  {
            $this->iterate(self::$setA, __FUNCTION__);
        }  else  {
            unset ($complement[$args['k']][$args['k2']][$args['k3']]);
        }

        return $complement;
    }

    public function iterate($obj, $function)  {
        foreach($obj as $k => $v)  {
            foreach ($v as $k2 => $v2)  {
                foreach ($v2 as $k3 => $element)  {
                    //call the method named in $function, pass back the keys and final value.
                    $this->$function(array(
                        'k1' => $k,
                        'k2' => $k2,
                        'k3' => $k3,
                        'element' => $element
                    ));
                }
            }
        }
    }
}

So my question is which (if either) is the better approach?  Is the second approach too DRY?  Too confusing?  I'm open to other approaches as well.


texts:
I read around for a while and surprisingly didn't find a fitting solution. I need a .NET Stream that internally issues HTTP Range requests when it seeks. There are huge files server-side for which I only need small amounts of data in a very random-access way. The consumer of the custom stream (beyond my control) issues lots of tiny, sequential reads, so the stream has to do caching. I have the following, and it seems to work quite well, but it's long and it's irritating my sense of "this should be easier in .NET".

Are there any suggestions to improve or shrink this?

class PartialHTTPStream : Stream, IDisposable
{
    Stream stream;
    WebResponse resp;
    int cacheRemaining = 0;
    const int cachelen = 1024;

    public string Url { get; private set; }
    public override bool CanRead { get { return true; } }
    public override bool CanWrite { get { return false; } }
    public override bool CanSeek { get { return true; } }

    long position = 0;
    public override long Position
    {
        get { return position; }
        set
        {
            long delta = value - position;
            if (delta == 0)
                return;
            if (delta > 0 && delta < cacheRemaining)
            {
                Console.WriteLine("Seeking in cache");
                byte[] dummy = new byte[delta];
                cacheRemaining -= (int)delta;
                while (delta > 0)
                {
                    int nread = stream.Read(dummy, 0, (int)delta);
                    if (nread == 0) throw new IOException();
                    delta -= nread;
                }
            }
            else cacheRemaining = 0;
            position = value;
            Console.WriteLine("Seek {0}", value);
        }
    }

    long? length;
    public override long Length
    {
        get
        {
            if (length == null)
            {
                HttpWebRequest request = HttpWebRequest.CreateHttp(Url);
                request.Method = "HEAD";
                length = request.GetResponse().ContentLength;
            }
            return length.Value;
        }
    }

    public PartialHTTPStream(string Url) { this.Url = Url; }

    public override void SetLength(long value)
    { throw new NotImplementedException(); }

    public override int Read(byte[] buffer, int offset, int count)
    {
        if (cacheRemaining == 0)
        {
            Console.WriteLine("Cache miss");
            if (stream != null)
            {
                stream.Close();
                resp.Close();
            }
            HttpWebRequest req = HttpWebRequest.CreateHttp(Url);
            cacheRemaining = (int)Math.Min(Length - Position, Math.Max(count, cachelen));
            req.AddRange(Position, Position + cacheRemaining - 1);
            resp = req.GetResponse();
            stream = resp.GetResponseStream();
        }

        count = Math.Min(buffer.Length - offset, Math.Min(cacheRemaining, count));
        Console.WriteLine("Read {0} @ {1}", count, Position);

        int nread = stream.Read(buffer, offset, count);
        position += nread;
        cacheRemaining -= nread;
        return nread;
    }

    public override void Write(byte[] buffer, int offset, int count)
    { throw new NotImplementedException(); }

    public override long Seek(long pos, SeekOrigin origin)
    {
        switch (origin)
        {
            case SeekOrigin.End:
                Position = Length + pos;
                break;
            case SeekOrigin.Begin:
                Position = pos;
                break;
            case SeekOrigin.Current:
                Position += pos;
                break;
        }
        return Position;
    }

    public override void Flush() { }

    new void Dispose()
    {
        base.Dispose();
        if (stream != null)
        {
            stream.Dispose();
            stream = null;
        }
        if (resp != null)
        {
            resp.Dispose();
            resp = null;
        }
    }
}


texts:
I have this code that's pretty much straightforward: it slides a box out at the bottom of the page and keeps another element fixed when you scroll past it.

What I am wondering is if there's any need for me to throttle the scroll event/handler for performance, considering that it's such a small code. I'm also wondering if it was necessary for me to check for the class (sticky) before I added/removed it.

var $window = $(window);
var $slidebox = $('#slidebox');
var $topShare = $('#top-share');
var distance = $('#top-share').offset().top - 8;

$window.scroll(function(){
    if($window.scrollTop() + $window.height() > $(document).height() - 200) {
        $slidebox.animate({'right':'0px'}, 300);
    } else {
        $slidebox.stop(true).animate({'right':'-326px'},100);
    }

    if ($window.scrollTop() >= distance) {
        if (!$topShare.hasClass('sticky')) {
            $topShare.addClass('sticky');
        }
    } else {
        if ($topShare.hasClass('sticky')) {
            $topShare.removeClass('sticky');
        }
    }

});


texts: Minimal, very simple, implementation of an HTTP server for static content, using only core node.js modules

texts:
To practice the very basics of node back-end, I'm implementing the most basic server possible for static content, using only the core node modules:

http
fs
path

With the following server requirements:

Can serve any http file inside the public directory.
Accepts only GET requests, 404 for anything else.
Accepts only .html extensions, 404 for anything else.
Use public/not-found.html for 404s.

These requirements are arbitrary, just to include some very basic logic in the request and response handling.
The working solution I'm presenting for code review is the following:
const fs = require('fs')
const http = require('http')
const path = require('path')

const hostname = 'localhost'
const port = 3000
const runLog = `Server running ar http://${hostname}:${port}`
const rootPath = '../public'
const errorPath = `${rootPath}/not-found.html`

const server = http.createServer((req, res) => {
  const fileUrl = req.url === '/' ? '/index.html' : req.url
  const filePath = path.resolve(`${rootPath}${fileUrl}`)
  res.setHeader('Content-Type', 'text/html')

  if (reqIsOk(req, filePath)) {
    res.statusCode = 200
    fs.createReadStream(filePath).pipe(res)
  } else {
    res.statusCode = 404
    fs.createReadStream(errorPath).pipe(res)
  }
})

function reqIsOk (req, filePath) {
  const fileExt = path.extname(filePath)
  return req.method === 'GET' && fileExt === '.html' && fs.existsSync(filePath)
}

server.listen(port, hostname, () => {
  console.log(runLog)
})

I'm looking for all kind of feedback, from style, code smells, anti-patterns, anything that can be improved is very welcome.

Are the fs and path packages needed? Do they simplify things enough to justify the inclusion?
Can this be written more concisely?
Is the ternary operator justified? Would you keep it here, or is an if construct preferred?


texts: Remove nth node from last position in linked list

texts:
Description:

Given a linked list, remove the nth node from the end of list and return its head.

  Given linked list: 1->2->3->4->5, and n = 2.

  After removing the second node from the end, the linked list becomes
  1->2->3->5.

Note:

Given n will always be valid.
Try to do this in one pass.

Code:

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int total = 0;
        ListNode current = head;
        while (current != null) {
            total++;
            current = current.next;
        }
        // current must be null here

        // 1 based index
        int indexToRemove = total - n + 1;
        if (indexToRemove < 0) {
            return null;
        }
        if (1 == total && n == 1) {
            return null;
        }
        if (indexToRemove == 1) {
            return head.next;
        }

        current = head;
        ListNode prev = null;
        for (int i = 0; i < indexToRemove - 1; i++) {
            prev = current;
            current = current.next;
        }
        // i > indexToRemove

        if (current == null) { // last
            prev.next = null;
        }
        else {
            prev.next = current.next;
        }
        return head;
    }
}

Questions:

I managed to run the code and pass all the tests but I still feel confused while dealing with off-by-one errors and NullPointerException. The question felt quite easy at first but implementation took a lot of time because of above two errors and correcting them, it was like I was shooting in the dark.

I still feel I have written a lot of extra code which could have been avoided.

What mental model or basic rules I can learn to visualise or understand program states and avoid such errors?


texts: Damage or Heal based on the buttons you press

texts:
If you press the damage button, it will damage armor before health. If you press the heal button, it will heal armor before health.

The project is here: https://github.com/austingaee/DamageHealth-Armor

Are there any improvements I can make?

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var armorBarView: UIView!

    @IBOutlet weak var healthBarView: UIView!

    var damageAmount : Float = 0.0
    var healAmount : Float = 0.0

    //Maximum Health
    var barAmount : Float = 0.0

    override func viewDidLoad() {
        super.viewDidLoad()

        damageAmount = Float(self.armorBarView.frame.size.width) * 0.10
        healAmount = Float(self.armorBarView.frame.size.width) * 0.05
        barAmount = Float(self.armorBarView.frame.size.width)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func damageBar(_ sender: UIButton) {
        //7.63 came from how much damage was left after 10 hits
        if self.armorBarView.frame.size.width > 7.63 {
            self.armorBarView.frame.size.width -= CGFloat(damageAmount)
        } else if self.healthBarView.frame.size.width > 7.63 {
            self.healthBarView.frame.size.width -= CGFloat(damageAmount)
        }
    }

    @IBAction func healBar(_ sender: Any) {
        if self.armorBarView.frame.size.width < CGFloat(barAmount) {
            self.armorBarView.frame.size.width += CGFloat(healAmount)
            print(self.armorBarView.frame.size.width)
        } else if self.healthBarView.frame.size.width < CGFloat(barAmount) {
            self.healthBarView.frame.size.width += CGFloat(healAmount)
        }
    }

}