texts: Elegant way to do the dataframe operations twice

texts:
I am trying to do certain operations in dataframe as shown in my code below. Though this works fine.However I am repeating the same statements twice or following a dirty approach to perform the operations twice. Can you help me to make it efficient and elegant?

I have a dataframe df in which I have to apply certain rules (see at the bottom PEEP_con and Fio2_con). PEEP_con has to be applied only to records with item_name == PEEP (df_P) and FiO2_con to item_name == Fio2 (df_F)

Before I apply the final conditions, I do certain preprocessing tasks which is 100 pc same for both the conditions but has to be done once for df_P and df_F . Hope this helps

Please find my code below (credit to SO users for help)

df = pd.read_csv('sample_data.csv')
df['charttime'] = pd.to_datetime(df['charttime'])
df = df.loc[df.value.mod(1).eq(0)]  # removes records with values like 5.4,6.1 etc

# I am creating two dataframes here. Is it possible to do this on the fly without creating two dataframes
df_P = df[df['item_name'] == 'PEEP']
df_P['value'] = np.where(df_P['value'] < 5, 5, df_P['value'])
df_F = df[df['item_name'] == 'Fi02/100']

# for the first time, I manually keep it to df_P and later I change it to df_F manually
dfa = df_F

# below operations is same for both the dataframes
m = dfa.assign(date=dfa.charttime.dt.date).groupby(['date',dfa.value.ne(dfa.value.shift()).cumsum()]).first().reset_index(drop=True)
c = pd.to_timedelta(24,unit='h')-(m.charttime-m.charttime.dt.normalize())
m['total_hr'] = m.groupby(['subject_id'])['charttime'].diff().shift(-1).fillna(c).dt.total_seconds()/3600
final_df = m.assign(date = m.charttime.dt.date)
gone_hr = final_df[final_df['total_hr'] > 1]
lone_hr = final_df[final_df['total_hr'] < 1]
min_gone_hr_data = gone_hr.groupby(['subject_id','date'])['value'].min().reset_index()
min_lone_hr_data = lone_hr.groupby(['subject_id','date'])['value'].min().reset_index()
op1 = gone_hr.merge(min_gone_hr_data, on = ['subject_id','date','value'],how = 'inner')
op2 = lone_hr.merge(min_lone_hr_data, on = ['subject_id','date','value'],how = 'inner')
op = (op1.set_index(['subject_id','date']).combine_first(op2.set_index(['subject_id','date'])).reset_index())

# This condition is only for `df_P`
PEEP_con = lambda x: (x.shift(2).ge(x.shift(1))) & (x.ge(x.shift(2).add(3))) & (x.shift(-1).ge(x.shift(2).add(3)))

# This condition is only for `df_F`
Fi02_con = lambda x: (x.shift(2).ge(x.shift(1))) & (x.ge(x.shift(2).add(20))) & (x.shift(-1).ge(x.shift(2).add(20)))

# this field should only be applied for df_P
op['fake_VAC'] = op.groupby('subject_id')['value'].transform(PEEP_con).map({True:'fake VAC',False:''})

# this field should only be applied for df_F
op['Fi02_flag'] = op.groupby('subject_id')['value'].transform(Fi02_con).map({True:'VAC',False:''})

I request your inputs in making this more elegant and efficient. Though suggestions w.r.t to logic are welcome, I am mostly looking for ways to optimize the code structure

Currently I generate two csv file output (one for PEEP and other for Fi02). Instead I would like to have both the columns Fi02_flag and fake_VAC in the same csv file (one final dataframe)


texts: Sleeping and invoking a task in Python 2.X and Python 3.X

texts:
I'm writing a program that needs to be compatible for both Python 2.X and Python 3.X. My problem is that, because of the differences between these two versions, I'm duplicating code.

try:
        ### Python 2.X part
        time.sleep(iterator.next())
        if len(arguments) >= len(inspect.getargspec(task).args):
            task(*arguments)
        else:
            print("ERROR: There is a mismatch between the number of"
                  " arguments provided in `arguments` and the ones"
                  " needed by the task function.")
except AttributeError:
        ### Python 3.X part
        time.sleep(next(iterator))
        if len(arguments) >= len(inspect.getfullargspec(task).args):
            task(*arguments)
        else:
            print("ERROR: There is a mismatch between the number of"
                  " arguments provided in `arguments` and the ones"
                  " needed by the task function.")

It can be seen that both versions only differ in the usage of next(), inspect.getargspec() and inspect.getfullargspec(), while the other logic remains the same. Is there any way to optimize the execution of the tasks, in tasks(*arguments), and the printing of the error messages, so that I don't have to repeat the same code? This is just sample working code, but I mean my question in a more broader and general case.


texts: Ternary search tree implementation in python 3

texts:
I have implemented a Ternary search tree. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.

class Node(object):

    def __init__(self, character):
        self.character = character
        self.leftNode = None
        self.middleNode = None
        self.rightNode = None
        self.value = 0

class TST(object):

    def __init__(self):
        self.rootNode = None

    def put(self,key,value):
        self.rootNode = self.putItem(self.rootNode, key, value, 0)

    def putItem(self, node, key, value, index):

        c = key[index]

        if node == None:
            node = Node(c)

        if c < node.character:
            node.leftNode = self.putItem(node.leftNode, key, value, index)
        elif c > node.character:
            node.rightNode = self.putItem(node.rightNode, key, value, index)
        elif index < len(key) - 1:
            node.middleNode = self.putItem(node.middleNode, key, value, index+1)
        else:
            node.value = value

        return node

    def get(self, key):

        node = self.getItem(self.rootNode, key, 0)

        if node == None:
            return -1

        return node.value

    def getItem(self, node, key, index):

        if node == None:
            return None

        c = key[index]

        if c < node.character:
            return self.getItem(node.leftNode, key, index)
        elif c > node.character:
            return self.getItem(node.rightNode, key, index)
        elif index < len(key) - 1:
            return self.getItem(node.middleNode, key, index+1)
        else:
            return node

if __name__ == "__main__":

    tst = TST()

    tst.put("apple",100)
    tst.put("orange",200)

    print( tst.get("orange") )


texts: Optimizing a python script with large arrays

texts:
I have a python script that I'd like to speed up. I'm hoping some of the gurus here can offer some advice.

The script reads in some data from file: 2 arrays with lat/lon vals, 3 arrays with image data and one quality mask. Each array is typically around 22M datapoints.
An output array exists and I convert the lat/lon values into array subscripts, mask the image data and then put into the correct locations in the output array.

I've got a feeling that my current method, whilst successful, is far from optimized!

mainarr =   np.zeros((4,1800,3600))
#Loop over all input files
for infile in files:

    #Code for reading data goes here. Limited by disk I/O so no optimisation here.
    #Location arrays are: lats,lons
    #Image data arrays are: c550,c670,c870
    #Quality mask is: cldy
    #Each of the above is a 1d numpy array, all are the same size
    #Function for reading the input data is not available, have called it 'readdata()' here.
    #lats, lons, c550, c670, c870 are all 32 bit floats. cldy is 8bit int.

    lats    =   np.array(readdata()).ravel()
    lons    =   np.array(readdata()).ravel()
    c550    =   np.array(readdata()).ravel()
    c670    =   np.array(readdata()).ravel()
    c870    =   np.array(readdata()).ravel()
    cldy    =   np.array(readdata(),dtype=np.int8).ravel()

    lats        =   np.array(np.round((lats+90)*10),dtype=np.int16)
    lons        =   np.array(np.round((lons+180)*10),dtype=np.int16)

    lats[(lats>=1800).nonzero()]=1799
    lons[(lons>=3600).nonzero()]=3599

    #The function below is already optimized
    masker  =   getmask(cldy, 1, 1, 0)
    pts     =   (masker != 1).nonzero()
    lats[pts]   =   0
    lons[pts]   =   0

    mainarr[0,lats,lons]    =   mainarr[0,lats,lons]+c550
    mainarr[1,lats,lons]    =   mainarr[1,lats,lons]+c670
    mainarr[2,lats,lons]    =   mainarr[2,lats,lons]+c870
    mainarr[3,lats,lons]    =   mainarr[3,lats,lons]+1

    i       =   i+1


texts:
I'm writing some Java code for some pretty large datasets, in a puzzle I'm trying to solve.  The output is correct, but the program doesn't run within the time limit for all the test cases.  I've tried a number of optimizations, but can't think about how to improve it.  I'd appreciate your suggestions.

The puzzle is here.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(br.readLine());
int N = Integer.parseInt(tok.nextToken());
int M = Integer.parseInt(tok.nextToken());
long[] A = new long[N];
int[] B = new int[M];
long[] C = new long[M];
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) A[i] = Long.parseLong(tok.nextToken());
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) B[i] = Integer.parseInt(tok.nextToken());
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) C[i] = Long.parseLong(tok.nextToken());
br.close();

for (int i = 0; i < M; i++) {
    for (int j = B[i] - 1; j < N; j += B[i]) {
        A[j] = (A[j] * C[i]) % 1000000007;
    }
}
for (long l : A) System.out.print(l + " ");


texts: Faster Google Spreadsheet access and direct use of Named Ranges for code readability

texts:
This object structure, that I think might be useful for a number of projects, attempts to:

learn the use objects (classes are not available in Google Apps Script) and inheritance
minimize calls to the Spreadsheet Service by summoning a data table once per sheet
use the Named Ranges on the spreadsheet to access the data in the table

The code below seems successful, but surely can be improved. A couple of major questions are:

Is there  a better way to accomplish the inheritance of methods and properties than this?
The Spreadsheet() function gets run for each of the Sheet objects, resulting in the environment structure having separate "ss" and "namedRangeList" properties in each of the Sheet objects. Is this normal and expected? Or is there a better approach to avoid this duplication? Or, is Javascript just recording pointers to a single instance of these objects, so it really doesn't matter that they appear to be duplicated?

Because they are common to and the same for all of the Sheets, I had expected "ss" and "namedRangeList" to show up only at the Environment level and therefore available to the Sheets thru inheritance rather than duplication.

What other changes or approaches would improve my fledgling use and understanding of classes and objects?

Here is a stripped down version of my code that preserves the essence of the structure but leaves out comments, error handling, and other functionality. Please note that due to Google Apps Script limitations, it does not use newer Javascript features like "class", "let", etc. Thank you for your comments and assistance!

function Environment() {
  this.title = 'Car & Driver';
  this.ui = SpreadsheetApp.getUi();
  this.dd = new Drivers();
  this.cc = new Cars();
}

function Spreadsheet() {
  this.ss = SpreadsheetApp.getActiveSpreadsheet();

  this.namedRangeList = {};
  var namedRanges = this.ss.getNamedRanges();
  for (var i = 0; i < namedRanges.length; i++) {
    var range = namedRanges[i].getRange();
    this.namedRangeList[namedRanges[i].getName()] = {
      sheet: range.getSheet().getSheetName(),
      row: range.getRow(),
      column: range.getColumn(),
      rowCount: range.getNumRows(),
      columnCount: range.getNumColumns(),
    }
  }
}
Spreadsheet.prototype = Object.create(Environment.prototype);

function Sheet() {
  Spreadsheet.call(this);
  this.sheet = this.ss.getSheetByName(this.sheetName);
  this.data = this.sheet.getDataRange().getValues();
}
Sheet.prototype = Object.create(Spreadsheet.prototype);

function Cars() {
  this.sheetName = 'Cars';
  this.abbreviation = 'cc';
  Sheet.call(this);
}
Cars.prototype = Object.create(Sheet.prototype);

function Drivers() {
  this.sheetName = 'Drivers';
  this.abbreviation = 'dd';
  Sheet.call(this);
}
Drivers.prototype = Object.create(Sheet.prototype);

Sheet.prototype.idxOf = function(namedRange) {
  return (this.namedRangeList[namedRange].rowCount == 1) ?
    this.namedRangeList[namedRange].row - 1 :
    this.namedRangeList[namedRange].column - 1;
}

function test_Environment() {
  var env = new Environment();

  env.ui.alert('The third driver is ' +
      env.dd.data[3][env.dd.idxOf('ddFirst')] + ' ' + env.dd.data[3][env.dd.idxOf('ddLast')] + '.');

  var tests = [
    ['dd', 2, 'ddLast'    , 'Bailey'  ],
    ['dd', 3, 'ddLicense' , 'pro'     ],
    ['cc', 1, 'ccRadio'   , 122.5     ],
    ['cc', 4, 'ccModel'   , 'Corvette'],
  ];
  tests.forEach(function(t) {
    var v = env[t[0]].data[t[1]][env[t[0]].idxOf(t[2])];
    Logger.log( (v == t[3]) + ': ' + (t[0] == 'dd' ? 'Driver ' : 'Car ') +
        t[1] + ' ' + t[2].slice(2) + ' is ' + v );
  });

  env.ui.alert(env.title + ' is all done');
}


texts: Simulate a person who is working in a quarry with classes

texts:
I build my first "bigger" program with classes. Does this look good? Or do you see something, which I could do better?
Do you think I could use a delegate for changing the stones to money here? And how to do this?

using System;

// collect stones
// if 20 stones collected --> event --> change stones for money

namespace FunInTheQuarry
{
    class MainClass
    {
        static void Main(string[] args)
        {
            Quarry quarry = new Quarry();
            Person person1 = new Person();

            for (int i = 0; i < 1000; i++)
            {
                System.Threading.Thread.Sleep(300);
                person1.Work();
                Console.WriteLine("{0} stones in the quarry.", Quarry.stone);
            }
            Console.Read();
        }
    }

    public class Quarry
    {
        public static int stone { get; set; }

        public Quarry()
        {
            stone = 10000;
        }
    }

    public class Person
    {
        public int stone;
        public int money;

        public Person()
        {
            stone = 0;
            money = 0;
        }

        public void Work()
        {
            stone += 1;
            Quarry.stone -= 1;
            if (this.stone >= 20)
            {
                ChangeStonesToMoney(ref this.stone, ref this.money);
            }
        }

        public void ChangeStonesToMoney(ref int stone, ref int money)
        {
            stone -= 20;
            money += 1;
            Console.WriteLine("One Person has now {0} dollar.", this.money);
        }

    }
}

EDIT: this is my revised work.

http://pastebin.com/99gRrUqv


texts:
I wrote a D implementation of the nul2pfb utility from here, as the link to the source code was broken and I wanted to try to learn D. I noticed that it was rather slow (could barely keep up with the find -print0 that was passing it data, when it should be far faster as it need not do anywhere near as many system calls).

This implementation works correctly (tested with zsh and bash printf built-ins, as well as /usr/bin/printf).

I am a newbie to D and do not understand.

How can I improve this code?

import std.stdio;
import std.conv;

void main()
{
  foreach (ubyte[] mybuff; chunks(stdin, 4096)) {
    encodebuff (mybuff);
  }
}

@safe void encodebuff (ubyte[] mybuff) {
  foreach (ubyte i; mybuff) {
    char b = to!char(i);
    switch (i) {
      case 'a': .. case 'z':
      case 'A': .. case 'Z':
      case '0': .. case '9':
      case '/':
      case '.':
      case '_':
      case ':': writeChar(b); break;
      default: writeOctal(b); break;
      case 0: writeChar ('\n'); break;
      case '\\': writeString(`\\`); break;
      case '\t': writeString(`\t`); break;
      case '\n': writeString(`\n`); break;
      case '\r': writeString(`\r`); break;
      case '\f': writeString(`\f`); break;
      case '\v': writeString(`\v`); break;
      case '\a': writeString(`\a`); break;
      case '\b': writeString(`\b`); break;
    }
  }
}

@trusted void writeString (string a)
{
  write (a);
}

@trusted void writeOctal (int a)
{
  writef ("\\%.4o", a); // leading 0 needed for for zsh printf '%b'
}

@trusted void writeChar (char a)
{
  write (a);
}

Tests: (note that filelist is a NUL-delimited list of files generated by
    find -print0 on my home directory, and filelist2.txt is generated from filelist by
    filelist.txt sed -e 's/\x0/\n/g' > filelist2.txt
 and is thus the corresponding list of newline-delimited filenames).

# the sed script escapes the backslashes so xargs does not clobber them
diff filelist2.txt <(<filelist.txt char2code2 | sed -e 's/\\/\\\\/g' | xargs /usr/bin/printf "%b\n")
# from within zsh
bash -c 'diff filelist2.txt <(for i in "$(<filelist.txt char2code)"; do printf "%b\n" "$i"; done)'
# from within zsh and bash
diff filelist.txt <(for i in $(char2code <filelist.txt); do printf '%b\0' "$i"; done)
# from within zsh, bash, and dash
for i in $(char2code <filelist.txt); do printf '%b\0' "$i"; done | diff - filelist.txt


texts: Max flow Ford-Fulkerson using DFS augmented path retrieval

texts:
I have written a naive max flow with DFS, could anyone review my below code. What can be done to improve the code and what are the worst cases where this won’t work acceptably?

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

#define SZ 20

int flow[SZ][SZ];
int residue[SZ][SZ];
int N, E, u, v, c;
int Source, Sink;

int visited[SZ];

inline int min(int a, int b){ return a < b ? a : b; }
inline int abs(int n){ return n < 0 ? -n : n; }

void print(int graph[SZ][SZ]){

    for (register int i = 0; i < N; i++){
        for (register int j = 0; j < N; j++){
            printf("%d ", graph[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

int dfs(int u, int rescap){

    if (u == Sink || rescap == 0){ return rescap;}

    visited[u] = 1;

    for (register int v = 0; v < N; v++){

        if (visited[v] == 0 && residue[u][v]){

            int r = dfs(v, min(residue[u][v], rescap));

            if (r) {

                flow[u][v] += r;
                residue[u][v] -= r;
                residue[v][u] += r;

                if (flow[u][v] > flow[v][u]){
                    flow[u][v] -= flow[v][u];
                    flow[v][u] = 0;
                }
                else {
                    flow[v][u] -= flow[u][v];
                    flow[u][v] = 0;
                }

                visited[u] = 0;
                return r;
            }
        }
    }

    visited[u] = 0;

    return 0;
}

/*void input(){

    freopen("input.txt", "wt", stdout);

    printf("%d %d\n", SZ, 5*SZ);

    for (register int i = 0; i < 5 * SZ; i++){

        int a = rand() % SZ;
        int b = rand() % SZ;
        int c = rand() % SZ;

        printf("%d %d %d\n", a, b, c);
    }

    fclose(stdout);
}*/

void maxflow(){

    freopen("input.txt", "rt", stdin);
    scanf("%d %d", &N, &E);

    Source = 0;
    Sink = N - 1;

    for (register int i = 0; i < E; i++){
        scanf("%d %d %d", &u, &v, &c);
        residue[u][v] = c;
    }

    int total = 0;
    int rescap = 0;
    while (rescap = dfs(Source, 1 << 30))
        total += rescap;

    printf("total flow: %d\n", total);

    print(flow);
    print(residue);
}


texts: Sequence generators not only for potatoes but also for apples and oranges

texts:
The last question about sequence generators Growing potatoes in delayed sequences was only about potatoes. I thougt why not make it work with apples and oranges too so I made it generic.

The base class got a new name and a generic argument and now looks like this:

public abstract class GeneratedSequence<T> : IEnumerable<T>
{
    protected GeneratedSequence(int count) { Count = count; }

    public int Count { get; }

    public IEnumerator<T> GetEnumerator() => Generate().Take(Count).GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

    protected abstract IEnumerable<T> Generate();
}

The RegularSequence has been upgraded and is now generic too:

public class RegularSequence<T> : GeneratedSequence<T>
{
    private readonly T _value;
    public RegularSequence(T value, int count) : base(count) { _value = value; }
    protected override IEnumerable<T> Generate()
    {
        while (true) yield return _value;
    }
}

The biggest change undergone however the FibonnaciSequence. Generics don't support arithmetic operations so I needed to add a lambda for the sum. Now it looks like this:

public class FibonacciSequence<T> : GeneratedSequence<T>
{
    private T _preview;
    private T _current;
    private readonly Func<T, T, T> _sum;

    public FibonacciSequence(T firstTwo, T firstStep, int count, Func<T, T, T> sum) : base(count)
    {
        _sum = sum;
        _preview = firstTwo;
        _current = _sum(_preview, firstStep);
    }

    protected override IEnumerable<T> Generate()
    {
        yield return _preview;
        yield return _preview;
        yield return _current;

        while (true)
        {
            var newCurrent = _sum(_preview, _current);
            yield return newCurrent;
            _preview = _current;
            _current = newCurrent;
        }
    }
}

To simplify the creation process I also added a new FibonacciSequenceFactory:

public class FibonacciSequenceFactory
{
    public static FibonacciSequence<TimeSpan> Create(TimeSpan firstTwo,TimeSpan firstStep, int count)
    {
        return new FibonacciSequence<TimeSpan>(firstTwo, firstStep, count, (x, y) => x + y);
    }

    public static FibonacciSequence<int> Create(int firstTwo, int firstStep, int count)
    {
        return new FibonacciSequence<int>(firstTwo, firstStep, count, (x, y) => x + y);
    }
}

I've applied the same pattern to the GeometricSequence but as it already had a lambda for the incrementation I just changed the argument to T:

public class GeometricSequence<T> : GeneratedSequence<T>
{
    private T _current;
    private readonly Func<T, T> _increment;
    public GeometricSequence(T first, Func<T, T> increment, int count) : base(count)
    {
        _current = first;
        _increment = increment;
    }
    protected override IEnumerable<T> Generate()
    {
        yield return _current;

        while (true)
        {
            yield return (_current = _increment(_current));
        };
    }
}

public class GeometricSequenceFactory
{
    public static GeometricSequence<TimeSpan> Double(TimeSpan first, int count)
    {
        return new GeometricSequence<TimeSpan>(first, x => TimeSpan.FromTicks(x.Ticks * 2), count);
    }

    public static GeometricSequence<TimeSpan> Triple(TimeSpan first, int count)
    {
        return new GeometricSequence<TimeSpan>(first, x => TimeSpan.FromTicks(x.Ticks * 3), count);
    }

    public static GeometricSequence<TimeSpan> Halve(TimeSpan first, int count)
    {
        return new GeometricSequence<TimeSpan>(first, x => TimeSpan.FromTicks(x.Ticks / 2), count);
    }
}

Usage example:

var fs = FibonacciSequenceFactory.Create(2, 4, 10);


texts: Client categorisation based on hourly payment

texts:
I am currently working on a small internal rating system for clients to be able to prioritise my work based on what client pays best. The input data is the hourly rate they are paying and based on that they should be divided into categories in are the range from A-D. The first setup looks like this:

def category_for(client)
  hourly_rate = client.hourly_rate
  case client.country
  when :germany
    return 'A' if hourly_rate >= 35
    return 'B' if hourly_rate >= 30
    return 'C' if hourly_rate >= 25
    return 'D' if hourly_rate < 25
  when :sweden
    return 'A' if hourly_rate >= 400
    return 'B' if hourly_rate >= 350
    return 'C' if hourly_rate >= 300
    return 'D' if hourly_rate < 300
  end
end

This is ofc only part of it to show the general setup.

This code, although working fine, really really hurts my eyes, so I was wondering if someone here had a good idea on how to refactor it in a nice way?


texts:
Each letter represent a category. Example the group with "M" Code is greater Than "I" and "C" group. "F" is the higher group

Here is what I did but I wonder if there is a better way to do it.

 Private Function CompareCode(ByVal code As String, ByVal otherCode As String) As Boolean
    Dim orderedCode As New List(Of String)
    orderedCode.Add("I")
    orderedCode.Add("C")
    orderedCode.Add("M")
    orderedCode.Add("F")

    Return orderedCode.IndexOf(code) < orderedCode.IndexOf(otherCode)

End Function


texts: A 3-D vector class built on top of numpy.array

texts:
I wanted a convenient class to easy access the parameters inside. I am using a lot of math in my game; that's why a wanted to access them through x, y and z (for readability). And this is my outcome.

It is a class which lies on top of numpy array. It basically means that I can control a numpy array trough my class. And using x, y and z for accessing the parameters instead of using indices ([0], [1] or [2]).

For that I overwrite the built in functions.

Example:

a = numpy.array([1,1,1], dtype = "float32")
b = a[0]

to

a = Vector3(1,1,1)
b = a.x

So what I want to know is if this is a good way (I wanted a fast written implementation). Are there any performance issues and is it well written?

import numpy as np
from numbers import Number

class Vector3(object):
    def __init__(self, x = 0, y = 0, z = 0, dtype = "float32"):
        self._data = np.array([x,y,z], dtype = dtype)
        self.x = self._data[0]
        self.y = self._data[1]
        self.z = self._data[2]

    def __str__(self):
        return str("Vector3({0.x},{0.y},{0.z})".format(self))

    def __mul__(self, value):
        if isinstance(value, type(self)):
            result = self._data * value._data
        elif isinstance(value, Number):
            result = self._data * value
        return type(self)(x = result[0], y = result[1], z = result[2])

    def __rmul__(self, value):
        return self.__mul__(value) # Kommutativgesetz/commutative

    def __add__(self, value):
        if isinstance(value, type(self)):
            result = self._data + value._data
        elif isinstance(value, Number):
            result = self._data + value
        return type(self)(x = result[0], y = result[1], z = result[2])

    def __radd__(self, value):
        return self.__add__(value) # Kommutativgesetz/commutative

    def __sub__(self, value):
        if isinstance(value, type(self)):
            result = self._data - value._data
        elif isinstance(value, Number):
            result = self._data - value
        return type(self)(x = result[0], y = result[1], z = result[2])

    def __rsub__(self, value):
        if isinstance(value, type(self)):
            result = value._data - self._data
        elif isinstance(value, Number):
            result = value - self._data
        return type(self)(x = result[0], y = result[1], z = result[2])

#Test
if __name__ == "__main__":
    a = Vector3(5,5,5)
    b = Vector3(2,4,3)
    c = a * b
    d = 2 * a
    e = a * 2
    f = a + b
    g = a + 2
    h = 2 + a
    i = a - b
    j = 2 - a
    k = a - 2
    print(c,d,e,f,g,h,i,j,k, sep = "\n")


texts:
I'm working through the Assembler assignment in the Nand2Tetris course (chapter 6). The suggested implementation contains 4 modules: Main, Parser, Code, SyntaxTree. Today I wanted to get some feedback on my implementation of the Code module.

The book specifies a general API in order to allow students to use whichever programming language they want; I choose Python 2.7. The Code module takes a line of a simplified dialect of Assembly code called Hack and produces binary.

The Code module only deals with a single class of instruction in Hack language: The C-Instruction. This instruction takes the form dest=comp;jump, where either dest= OR ;jump may be optionally omitted. comp is one of 28 valid expressions. dest is the destination to store the result of the computation: it can be any permutation of the three registers available (A, D, M). jump is a condition which, if true, moves control flow the address in instruction memory currently stored in register A.

The resulting opcode takes the form: 111a cccc ccdd djjj, where a and cccc cc correspond to the comp, ddd corresponds to the dest, and jjj corresponds to the jump. For more details, see Chapters 4 and 6 of the textbook.

Please review on style, implementation (especially those terribly ugly lookup tables), etc.

#!/usr/bin/python
# hack code translator

# Sample conversion:
# HACK Instruction: M = 1
# 111
# a = 0
# cccccc = 1111 11
# ddd = 001
# jjj = 000
# BINARY Opcode:    1110 1111 1100 1000

jumpTable = { 'null': '000',
              'JGT' : '001',
              'JEQ' : '010',
              'JEQ' : '010',
              'JGE' : '011',
              'JLT' : '100',
              'JNE' : '101',
              'JLE' : '110',
              'JMP' : '111'  }

compTable = { '0'   : '101010',
              '1'   : '111111',
              '-1'  : '111010',
              'D'   : '001100',
              'A'   : '110000',
              '!D'  : '001101',
              '!A'  : '110001',
              '-D'  : '001111',
              '-A'  : '110011',
              'D+1' : '011111',
              'A+1' : '110111',
              'D-1' : '001110',
              'A-1' : '110010',
              'D+A' : '000010',
              'D-A' : '010011',
              'A-D' : '000111',
              'D&A' : '000000',
              'D|A' : '010101' }

def dest(srcStr):
    # Of the three portions of the opcodes,
    # this is the only one that makes obvious logical sense
    # No point in a lookup table

    # Any combination of A, D, M
    # in that order
    # TODO: bitops this
    bits = ['0', '0', '0']  # 0 by default
    if 'A' in srcStr:
        bits[0] = '1'
    if 'D' in srcStr:
        bits[1] = '1'
    if 'M' in srcStr:
        bits[2] = '1'

    return ''.join(bits)

def comp(srcStr):
    aBit = '0'

    if 'M' in srcStr:
        if 'A' in srcStr:
            raise SyntaxError
        else:
            aBit = '1'
            nStr = srcStr.replace('M', 'A')  # this way we use only one lookup table

    else:
        nStr = srcStr[:]  # non-destructive copy

    return aBit + compTable[nStr]

def jump(srcStr):
    return jumpTable[srcStr]


texts:
I designed a simple timeout thrower for a bluetooth protocol I am writing. If the packet is not received in a certain amount of time, then timeout is thrown. I made it to be as plug and play as possible.

timeout.hpp:

#ifndef __timeout_h__
#define __timeout_h__

#include <thread>

struct Timeoutthread{
    private:
        int sleep;
    public:
        Timeoutthread(int seconds);
        void time(bool* alert);
};

class Timeout{
    private:
        int sleep;
        bool alert;
    public:
        Timeout(int seconds);
        bool timeout();
};

#endif

timeout.cpp:

#include "timeout.hpp"

Timeout::Timeout(int seconds){
    sleep = seconds;
    Timeoutthread timeoutthread(sleep);
    std::thread timeout(&Timeoutthread::time,timeoutthread,&alert);
    timeout.detach();
}

bool Timeout::timeout(){
    return alert;
}

Timeoutthread::Timeoutthread(int seconds){
    sleep = seconds;
}

void Timeoutthread::time(bool* alert){
    std::this_thread::sleep_for (std::chrono::seconds(sleep));
    *alert = true;
}

simple implementation:

#include <iostream>
#include "timeout.hpp"

int main(){
     std::string message = "";
     Timeout timeout(10);
     while(message == ""){
          message = readBLE();
          if(timeout.timeout() == true)
               message = "timed out";
     }

     std::cout<<message<<std::endl;

     return 0;
}

The loop waits for a bluetooth message, but if no message is received in 10 seconds, then a timeout is thrown.

Is this an efficient way to do it. I want to make sure that I am not wasting any resources.

EDIT:

There seems to be some confusion on the readBLE() part. There is a lot more code associated with this part but it does not act like std::cin where it is waiting for a user input. Whenever readBLE() is called, if there was no message received, then it would just return an empty string. Sorry for the confusion.


texts:
In want to implement length prefixed strings in C (not null terminated), with some idiosyncrasies: malloc is prohibited, memory efficiency is important, each string (except for literal-backed ones) is modifiable and can change its length, but it has a fixed (at declaration) allocated length (maximum 255), C code is generated by a code generator.  I want this to work on as many architectures and C compilers as possible.

Suppose I do the following:

typedef struct PLS {
   uint8_t maxlen;
   uint8_t curlen;
   char buf[1];  // actual allocated size is in maxlen
} PLS ;

Then I could declare, say

  struct {
    ...
    PLS s1;   // real allocated size: 100
    char s1buf[99];
    PLS s2;  // real allocated size: 64
    char s2buf[63];
    ...
    };

   // initialization:
   mystruct.s1.maxlen=100;
   mystruct.s1.curlen=0;
   mystruct.s2.maxlen=64;
   mystruct.s2.curlen=0;

   // PLS library:

   void PLS_copy(PLS *to,PLS *from) {
       int tc = from-> curlen; // chars to copy
       if(tc > to->maxlen) tc = to->maxlen;
       memcpy(to->buf,from->buf,tc);
   }

Does this look ok? Any pitfalls? Would some compiler give warnings?
I believe that data structure alignment should not padding between s1 and s1buf, but even then it should work, right?

For literals, if I want to avoid a duplication of allocated chars, things seem trickier (remember, though, that code is machine-generated). Would this be objectionable?

 // static declaration of literal "hello" (5 chars) trailing null byte wasted
 char lit1[] = "\x05\x05hello";
// can the above be casted to PLS? (I won't modif it, I swear)
 PLS * lit1Pls = &(PLS)(lit1);  // smells funny, though...


texts:
I was refactoring a quite large WPF project and I found some pieces of code where it can leads to error.

Ive got some services in the form

 public sealed class CurrenciesService : ContainerServiceBase<Currency>, ICurrenciesService
 {
    public override Currency GetItem(int id)
    {
        return GetItemInternal(x => x.Id == id);
    }

    public override Task Init()
    {
        return PerformInitInternal(InitCacheMessages.STR_GET_COUNTERPARTS,
      InitCacheMessages.STR_GET_COUNTERPARTS_FAILED,()=> CommonRepository.GetCurrenciesAsync());
    }
 }

where the ContainerServiceBase is something as

 public class ContainerServiceBase<T> : IContainerBase<T>
    where T : class
{
    #region Variables
    protected readonly IExceptionService ExceptionService = ServiceLocator.Default.ResolveType<IExceptionService>();
    protected readonly ICommonRepository CommonRepository = ServiceLocator.Default.ResolveType<ICommonRepository>();
    public delegate void ItemsChangedHandler(object sender, EventArgs e);

    public event ItemsChangedHandler OnItemsChanged;

    #endregion

    public virtual T GetItem(int id)
    {
        throw  new NotImplementedException();
    }

    public virtual Task Init()
    {
        return TaskEx.WhenAll();
    }

    public IList<T> Items { get; protected set; }

    protected async Task PerformInitInternal(string okMessage, string koMessage, Func<Task<IList<T>>> function)
    {
        try
        {
            var result = await function();
            if (result != null)
            {
                Items = result;
                LogTo.Information(okMessage, result.Count);

                OnItemsChanged?.Invoke(this, new EventArgs());
            }
            else
            {
                LogTo.Warning(koMessage);
            }
        }
        catch (Exception ex)
        {
            ExceptionService.HandleException(ex);
        }
    }

    protected T GetItemInternal(Func<T, bool> condition)
    {
        if (Items == null) throw new NullReferenceException("Items has not been initialized");

        var result = Items.FirstOrDefault(condition);

        return result;
    }

Currently during the Application's start I perform for each service this

     var taskPortolio = portfoliosService.Init();
        var taskInstitutes = institutesService.Init();
        var taskStatus = statusService.Init();
        var taskCounterparts = counterpartsService.Init();
        var taskCrosses = crossesService.Init();
        var taskCurrencies = currenciesService.Init();
        var taskSigns = signsService.Init();
        var taskCrossSplit = crossSplitService.Init();
        var taskDateMM = dateMmService.Init();
        var taskSignsFx = signsFxService.Init();
        var taskPortfolioTree = portfolioItemService.Init();
        var taskTags = tagService.Init();
        var taskInstitutesCustomerDesk = institutesCustomerDeskService.Init();
        var taskProvenances = provenanceService.Init();
        var taskRepoClasses = repoClassService.Init();
        var taskDatesMaturity = dateMaturityService.Init();

Those methods are initialized even if they're never used.

I was writing a unit test in the form

  [Test]
    public async Task CurrenciesLoaded()
    {
        var viewmodel = viewModelFactory.CreateViewModel<HistoricalDetailPRTViewModel>(null, null);

        var res = viewmodel.InitializeViewModelAsync();

        await res;

        Assert.NotNull(viewmodel.Currencies);
        Assert.IsTrue(viewmodel.Currencies.Count>0);

    }

and correctly I get null at viewmodel.Currencies since no CurrenciesService.Init has been called.

Can I put a check in the Item.getter to check if it's called the Init and if not call it? is this evil? consider that those init are now called async and I wish not to block the UI while it's loading

P.S. I'm using Catel as MVVM Framework


texts: Functional Programming Style in Javascript Picking a Random Item from an Array

texts:
I'm trying to understand the Functional Programming Paradigm (or style) implemented with Javascript. There are a few things I have difficulties with. The naming conventions, and dependency injections. I would be super happy if you could help me out with these two problems.
const items = ['', '', '', ''];

const pickRandomArrayNumber = (floorFunction, randomFunction) => array => floorFunction(randomFunction() * array.length);
const pickRandomItemFrom = pickRandomArrayNumber(Math.floor, Math.random);
console.log(items[pickRandomItemFrom(items)]);

This piece of code grabs a random number between 0 and the length of the provided array. However, I wanted the getRandomArrayNumber function to be independent.
I'm not happy with the names of the functions as they are right now. Mainly because getRandomArrayNumber doesn't really get an array number, but instead provides a function that does.
Is this Functional Programming style future proof and does it follow the Functional Programming Principles correctly? And how would you name these functions? Or perhaps, handle dependency injection in a functional style?
Thanks in advance!


texts:
I am practicing using the Prototype pattern and to do so, I am building a simple CRUD app that allows me to view, add, and delete customers.

Here is a JsFiddle for you to see what I've got so far.

// Create customer 'class' and store state here
var Customer = function(el) {
    this.el = document.getElementById(el);
    this.first_name = $("#input_first_name").val();
    this.last_name = $("#input_last_name").val();
    this.name = ""

}

var customers = [];

// In the Customer prototype store methods
Customer.prototype = {

    // utility to log customer array
    logCustomers: function() {
        console.log(customers);
    },

    fullName: function() {
        this.name = this.first_name + " " + this.last_name;
        return this.name;

    },

    addCustomer: function() {
        // clear out the current html to make room for the append later
        this.el.innerHTML = "";

        // create new customer instance
        var cust = new Customer();

        // add customer to the array
        customers.push(cust);

        // iterate through the array and add each customer to a row in the table
        $.each(customers, function() {
            $("#el").append("
" + this.fullName() + "	delete
");
        })

        // Clear out the text boxes
        $("#input_first_name").val("");
        $("#input_last_name").val("");

    },

    // Remove customer from array and hide the row that contained them
    removeCustomer: function(e) {
        $(e.target).closest('tr').hide();
        customers.splice(e.target, 1);

    }
}

// Default customer object has to be created in order for unobtrusive calls to work
var cust = new Customer("el");

// unobtrusive jQuery event handling below
$("#btn_add_customer").click(function() {
    cust.addCustomer();
});

$("#btn_remove_cust").live("click", cust.removeCustomer);

$("#btn_log_customers_array").click(cust.logCustomers)

There are a few things that I'm concerned about:

I'm using jQuery to handle events and I'm trying to make everything as unobtrusive as possible.  In doing so, I wasn't exactly sure where I needed to place the event-handling code so I created a separate block below the prototype code to contain the button click events.  I'm not sure if this is the best way to go.
The events are being passed a function from the prototype - so in order for anything to work I have to new-up an instance of the 'Customer' before the user actually creates a new customer.  Seems like there might be a better way - but since I'm using a constructor function, I'm not sure if there is any other way around that.  If I change the constructor to an object literal, than I've just got a singleton.
Am I handling the removal of 'customers' from the array properly?  I created a simple utility function that is wired up to a button so that I could check and make sure that objects were being removed - as well as hidden in the DOM.


texts:
This program is designed to interleave two strings, which are input as command line arguments. I'd appreciate any feedback as I am new to C and self-taught.

Edit: Since this is an exercise in becoming more familiar with the intricacies of strings and memory allocation, the output should be stored before being printed.

#include <stdio.h>  // printf
#include <stdlib.h> // malloc, EXIT_FAILURE/SUCCESS
#include <string.h> // strlen

int main(int argc, char const *argv[])
{
  // Expecting: exe name, str_a, str_b
  if (argc != 3)
  {
    return EXIT_FAILURE;
  }

  size_t str_a_len = strlen(argv[1]);
  size_t str_b_len = strlen(argv[2]);
  if (str_a_len != str_b_len)
  {
    return EXIT_FAILURE;
  }

  // +1 for NULL byte
  size_t str_c_len = str_a_len + str_b_len + 1;
  char * str_c = malloc(str_c_len);

   // No free memory
  if (strlen(str_c) == 0)
  {
    return EXIT_FAILURE;
  }

  // Zip letters, AAA BBB => ABABAB
  for (int i = 0, n = str_c_len; i < n; ++i)
  {
    str_c[i] = (i % 2 == 0) ? argv[1][i / 2] : argv[2][i / 2];
  }

  printf("%s\n", str_c);

  return EXIT_SUCCESS;
}

I am compiling with:

gcc *.c -Wall -g -o zip.exe


texts: Selection sort algorithm with increasing/decreasing sort options

texts:
I am running through some traditional algorithms in Go, and I was hoping to get feedback on efficiency and optimization.

Below is a basic selection sort algorithm that takes a parameter to dictate increasing, or decreasing order.

// SelectionSort
// in: A = {31, 41, 59, 26 , 41, 58}
//
// Increasing order
// out: A = {26, 31, 41, 41, 58, 59}

// Illustration:
// 31 | 41 | 59 | 26 | 41 | 58
// 31 | 41 | 59 | 26 | 41 | 58
// 31 | 41 | 59 | 26 | 41 | 58
// 26 | 31 | 41 | 59 | 41 | 58
// 26 | 31 | 41 | 41 | 59 | 58
//
// Decreasing order
// out: A = {59, 58, 41, 41, 31, 26}
//
// Illustration:
// 31 | 41 | 59 | 26 | 41 | 58
// 41 | 31 | 59 | 26 | 41 | 58
// 59 | 41 | 31 | 26 | 41 | 58
// 59 | 41 | 31 | 26 | 41 | 58
// 59 | 41 | 41 | 31 | 26 | 58
// 59 | 58 | 41 | 41 | 31 | 26
package main

import (
    "fmt"
)

// Function that performs a selection sort.
// Second parameter specifies increasing or decreasing order.
func SelectionSort(A []int, S string) []int {
    for i := range A {
        for j := i + 1; j < len(A); j++ {
            switch {
            case S == "increasing":
                if A[i] > A[j] {
                    A[i], A[j] = A[j], A[i]
                }
            case S == "decreasing":
                if A[i] < A[j] {
                    A[i], A[j] = A[j], A[i]
                }
            }
        }
    }
    return A
}

func main() {
    A := []int{31, 41, 59, 26, 41, 58}
    fmt.Println("Unsorted array: ", A)
    fmt.Println("Increasing sort array: ", SelectionSort(A, "increasing"))
    fmt.Println("Decreasing sort array: ", SelectionSort(A, "decreasing"))
}


texts: Pulling data from multiple excel files in Python

texts:
I understand this code is running properly and is grabbing from each excel file individually, but I want to create a for loop for using this data across multiple excel files

kinematic_viscosity = []

kinematic_viscosity_1= []

kinematic_viscosity_2= []
#*empty arrays for creating after loop in completed*
for dynamic_viscosity in DV:
   kinematic_viscosities = dynamic_viscosity/Density_PE_298k
   kinematic_viscosity.append(kinematic_viscosities)

for dynamic_viscosity_1 in DV_1:

    kinematic_viscosities_1 = dynamic_viscosity_1/Density_PE_298k
    kinematic_viscosity_1.append(kinematic_viscosities_1)
#second loop
for dynamic_viscosity_2 in DV_2:

    kinematic_viscosities_2 = dynamic_viscosity_2/Density_PE_298k
    kinematic_viscosity_2.append(kinematic_viscosities_2)
#third loop


texts: How do I refactor this basic form handler

texts:
I've dabbled with PHP for a couple of years, I can generally get what I need done and I've been teaching myself PDO. The problem is I want to set it up with classes but i'm not really sure how to.

Below is my code, which takes data from a form, does some rough checking to see if the email is right and the fields are full. It works but it's gotten to a point where I can't take it further without breaking it or getting confused and i want to add things such as validation.

So what i'm asking for is can some show me how to create a basic connection class that outputs acouple of records from a database, this would help me a lot if anyone could.

<?php
try{
$host = "localhost";
$dbname = "db";
$user = "user";
$pass = "pass";

  $odb = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $user, $pass);
  $odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch (PDOException $e) {
echo "I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}

        if($_SERVER["REQUEST_METHOD"] == "POST"){
            if (isset($_POST['firstname']) && !empty($_POST['lastname']) && filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) && !empty($_POST['phone'])){
                $firstname = $_POST['firstname'];
                $lastname = $_POST['lastname'];
                $email = $_POST['email'];
                $phone = $_POST['phone'];

                        $q = "INSERT INTO jobform(firstname, lastname, email, phone) VALUES (:firstname, :lastname, :email, :phone);";
                        $query = $odb->prepare($q);
                        $results = $query->execute(array(
                        ":firstname" => $firstname,
                        ":lastname" => $lastname,
                        ":email" => $email,
                        ":phone" => $phone,
                        ));
                } else {
            #echo $errMsg;
        }
     }
?>


texts: Rewriting file names according to the available screen space

texts:
I created a function that rewrites file names according to the available space on screen:

@{
  var index = 0;
  foreach (var item in Model)
  {

        var id = "filename_" + ++index;
        @Html.SpanFor(i => item.FileName, new { id = id, title = item.FileName, style = "white-space: nowrap;" })

  }
}

@section Scripts
{

}

Here are the results before and after running script:

Before:

After:

The function runs quite fast for now, but should I be worried from future impact? Any other suggestion or alternatives? Optimization?

I thought about splitting it to 3 spans, 1 for filename, second for ..., and 3rd for the extension, but I don't really know how to make the overflow of the first be hidden under the other two. Besides, if a truncation isn't required, it's gonna look weird.


texts:
I wrote a function that adds items in a list, but my professor says to try and write it in a simpler way because he says I take too many steps. Is there any other way to write this?

def additems(self, item):
    """Add <item> to this PriorityQueue.

    @type self: PriorityQueue
    @type item: object
    @rtype: None

    >>> pq = PriorityQueue()
    >>> pq.additems("yellow")
    >>> pq.additems("blue")
    >>> pq.additems("red")
    >>> pq.additems("green")
    >>> pq._items
    ['blue', 'green', 'red', 'yellow']
    """
    # TODO
    #only insert if the list isn't already empty
    if not self.is_empty():

        i = 0

        #Look for the lowest priority place to insert the item
        while i < len(self._items):

            if item <= self._items[i]:
                self._items.insert(i, item)

                #exit the loop if it inserts
                i = len(self._items)

            elif item >= self._items[-1]:
                self._items.append(item)

                #exit the loop if it inserts
                i = len(self._items)

            i += 1

    else:
        self._items.append(item)


texts:
I've recently try to brush up my javascript skills, so I have a friend who gives me puzzles from time to time to solve. Yesterday I got this :

function testFun() {
  f = {};
  for( var i=0 ; i<3 : i++ ) {
    f[i] = function() { alert("sum='+i+f.length); }
  }
return f;
}

Expected Results:
testFun()[0]() should alert “sum=0”
testFun()[1]() should alert “sum=2”
testFun()[2]() should alert “sum=4”

I did this which does like requested above:

function testFun() {
    var i,
        f = {};
    for (i = 0; i < 3; i++) {
        f[i] = (function(number) {
            return function() {
                alert("sum=" + (number * 2));
            }
        }(i));
    }
    return f;
}

Could my answer be written better and what can be improved if so?


texts: Created my first wordpress plugin template page, need comments

texts:
I managed to create my first wordpress plugin template page collecting various code snippets to make the page function.

Everything works fine, but I need hear comments from PHP & wordpress experts to see if it's well-coded.

Here's the code.

<?php
/*
Plugin Name: name
Plugin URI: http://www.example.com
Description: desc
Version: 1
Author: someone
Author URI: http://www.example
*/
?>
<?php
function my_first_plugin_init(){
    register_setting( 'my_first_plugin_grp', 'my_first_plugin' );
}
add_action( 'admin_init', 'my_first_plugin_init' );

function my_first_plugin_add_page() {
    add_menu_page('plugin title', 'plugin title', 'manage_options', 'my_first_plugin', 'my_first_plugin_do_page' );
}
add_action( 'admin_menu', 'my_first_plugin_add_page' );

function my_first_plugin_scripts() {
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
    wp_enqueue_script('my-upload', plugin_dir_url( __FILE__ ).'/upload-func.js');
}
add_action('admin_print_scripts', 'my_first_plugin_scripts');

function my_first_plugin_styles() {
    wp_enqueue_style('ads-stls', plugin_dir_url( __FILE__ ).'/ads-options.css');
    wp_enqueue_style('thickbox');
}
add_action('admin_print_styles', 'my_first_plugin_styles');

function my_first_plugin_do_page() {
    global $select_options, $radio_options;
    if ( ! isset( $_REQUEST['settings-updated'] ) )
    $_REQUEST['settings-updated'] = false;
?>

<?php echo $plgnme; ?>

    <?php if ( false !== $_REQUEST['settings-updated'] ) : ?>

Options saved.

    <?php endif; ?>
    <form method="post" action="options.php">
    <?php settings_fields( 'my_first_plugin_grp' ); ?>
    <?php $options = get_option( 'my_first_plugin' ); ?>

Sample text input:
<input id="my_first_plugin[lpgrdneurl]" class="regular-text" type="text" name="my_first_plugin[lpgrdneurl]" value="<?php esc_attr_e( $options[$lpgrdneurl] ); ?>" placeholder="http://" />

    <?php submit_button(); ?>
    </form>

<?php } ?>


texts:
I've got a filter that I'd like to work out how to optimize. The most basic implementation, using loops is like the following:

import numpy as np
nrow = 500
ncol = 500
refArray = np.random.randint( 0,100, (nrow,ncol) )
boundsArray = np.random.randint( 90,95, (2,nrow,ncol) )
window = 31
halfwindow = window/2
result = np.zeros_like(refArray)
## we'll ignore edges for the moment

for i in range(halfwindow, nrow - halfwindow):
    for j in range(halfwindow, ncol - halfwindow):
        window = refArray[ (i-halfwindow):(i+1+halfwindow), (j-halfwindow):(j+1+halfwindow)]
        valid = (window >= boundsArray[0,i,j]) & (window <= boundsArray[1,i,j])
        result[ (i-halfwindow):(i+1+halfwindow), (j-halfwindow):(j+1+halfwindow) ] \
           += valid

So, for each location (i,j) in an array, I find a window around this location, and identify all elements which meet a particular requirement, then move on. At each step I count how often element (i,j) has met the requirement.

I'm looking for suggestions on approaches to write this efficiently. I can't see how I can avoid the loops, so I'd consider options like Cython or f2py.


texts: Evaluating a completely parenthesized arithmetic expression

texts:
I tried to solve the following problem in a programming challenge, but the verdict was time limit exceeded.

  Completely parenthesized expression

  Write a program that reads a completely parenthesized expression, and
  prints the result of evaluating it. The three possible operators are
  sum, substraction and multiplication. The operands are natural numbers
  between 0 and 9 (both included).

  Input

  Input has a completely parenthesized expression. That is, parentheses
  always appear around subexpressions that are not digits. For instance,
  the expression 4 + 3 would be written

  ( 4 + 3 )

  The expression 8 * (4 + 3) would be written

  ( 8 * ( 4 + 3 ) )

  The expression (2 − 8) * (4 + 3) would be written

  ((2-8)*(4+3))

  Output

  Print a line with an integer number: the result of evaluating the
  given expression.

  (Source: https://jutge.org/problems/P45102_en/statement)

Some of the public test cases were (each line is a different test case):

9
( 3 + 4 )
( 8 * ( 4 + 3 ) )
( ( 2 - 8 ) * ( 4 + 3 ) )
( ( 3 * 2 ) + 1 )

This is my code, which passed every public test cases, but not the private ones. I ask your help in order to find the bottleneck of my program.

#include <iostream>
#include <sstream>

using std::string;
using std::cin;
using std::cout;

/**
 * Returns the evaluation of a completely parenthesed expression.
 *
 * Preconditions:
 *     * 0 <= i <= j < expr.size()-1.
 *     * expr is a completely parenthesed expression.
 *
 * Postcondition: returns the evaluation of expr[i..j].
 */

int evaluate(const string& expr, int i, int j)
{
    // Skip leading blanks
    while (expr[i] == ' ') {
        ++i;
    }
    while (expr[j] == ' ') {
        --j;
    }

    // Base case
    if (i == j) {
        return expr[i] - '0';
    }
    // Recursive case
    else {
        // Skip first and last parentheses
        ++i;
        --j;
        int open_parentheses = 0;
        int end_i = i;
        // Loop invariant:
        //     * expr[i..end_i) is part of the first subexpression of expr[i..j]
        //     * open_parentheses is the balance of opened and closed parentheses of expr[i..end_i)
        while (open_parentheses > 0 || (expr[end_i] != '+' && expr[end_i] != '-' && expr[end_i] != '*')) {
            if (expr[end_i] == '(') {
                ++open_parentheses;
            }
            else if (expr[end_i] == ')') {
                --open_parentheses;
            }
            ++end_i;
        }
        // Loop ending: expr[end_i] is the 'main' operation of expr[i..j]

        char operation = expr[end_i];

        // By induction hypothesis,
        //     evaluate(expr, i, end_i - 1)
        // and
        //     evaluate(expr, end_i + 1, j)
        // return the values of the first and the second subexpression of expr[i..j]

        if (operation == '+') {
            return evaluate(expr, i, end_i - 1) + evaluate(expr, end_i + 1, j);
        } else if (operation == '-') {
            return evaluate(expr, i, end_i - 1) - evaluate(expr, end_i + 1, j);
        } else {
            int first_expression = evaluate(expr, i, end_i - 1);
            // Multiplication shortcut
            if (first_expression == 0) {
                return 0;
            } else {
                return first_expression * evaluate(expr, end_i + 1, j);
            }
        }
    }
}

int main()
{
    string expr;
    getline(cin, expr);
    cout << evaluate(expr, 0, expr.size() - 1) << "\n";
}


texts: Nested loops - Random Forest, multiple parameters

texts:
I'm writing a code which task is to grow Random Forest trees based on multiple parameters. In short:

Firstly, I declare a data frame in which model parameters and some stats will be saved.
Secondly, I declare model parameters and the loop iterator (it will be showed after every loop iteration).
Next, I have a nested loops with the model and prediction function.
Furthermore, parameters and some stats from the confusion matrix are saved to the dataframe.
Additionally, the number of iterations is printed and counted.
Last but not least, garbage collector is called.

The code looks like this:

## data frame in which model parameters and some stats will be saved

model_eff <- data.frame("ntrees" = numeric(0),
                        "zeros" = numeric(0),
                        "mvars"= numeric(0),
                        "eff" = numeric(0),
                        "0_0" = numeric(0),
                        "0_1" = numeric(0),
                        "1_0" = numeric(0),
                        "1_1" = numeric(0),
                        "predict_sum" = numeric(0),
                        "triangle" = numeric(0))

## parameteres

ntrees <- c(300, 500)
zeros <- sum(train.target) * c(1, 2, 3, 4, 5)
mvars <- c(30, 50, 70, 90, 110, 130)

## loop counter

i = 1

## loop with model, prediction etc.

for (j in 1:length(ntrees)){
  for (k in 1:length(zeros)){
    for (l in 1:length(mvars)){

      ## i-th model

      model <- randomForest(train,
                            y = as.factor(train.target),
                            ntree = ntrees[j],
                            do.trace = T,
                            sampsize = c('0' = zeros[k], '1' = sum(train.target)),
                            mtry = mvars[l])

      ## prediction - my function, apart from a regular prediction
      ##              outputs additional info

      predict.model(model, val, val.target)

      ## inserting model parameters and stats to a data frame for further comparisons

      model_eff <- rbind(model_eff,
                         c("ntrees" = ntrees[j],
                           "zeros" = zeros[k],
                           "mvars"= mvars[l],
                           "eff" = eff_measures$eff,
                           "0_0" = eff_measures$c.m[1, 1],
                           "0_1" = eff_measures$c.m[1, 2],
                           "1_0" = eff_measures$c.m[2, 1],
                           "1_1" = eff_measures$c.m[2, 2],
                           "predict_sum" = sum(TARGET3),
                           "triangle" = eff_measures$triangle))

      ## printing the number of iteration

      cat("iteration =", i)
      i <- i+1

      ## calling garbage collector to assure free space in RAM

      gc()
    }
  }
}

I have already split the train/validation data sets and their target variables, knowing that Random Forest deals with such data mor efficiently. I also tried to use the "foreach" package for parallelizing computations, however, the growing time for only one tree was 10-15% longer than without using all the cores.

I would like to know if I can shorten the time of execution of this code, especially if there is a way to avoid multiple loops since I heard that they are not the best way of programming in R.


texts: Implementation of Parallel.ForEach for .NET 3.5

texts:
Because the TPL backport not only contains Parallel.* but also PLINQ, concurrent collections, etc, I will try to use this one.

Just for fun, I profiled both the TPL implementation and my own, in the very basic and naive test, mine was actually a little bit faster.

Microsoft TPL backport: 00:00:17.0673098
My Implementation: 00:00:16.9210535
Intel Q6600 (quad-core), 4GB of RAM, Win8.1(x64), VS2013 targetting .NET 3.5

The code is here (github gist), the colorful output of the Concurrency Visualizer is below:

This negligeable performance difference (in the best case) gets outweight by the many optimisations the .NET team put in for special cases.

Question:

To ease working with multithreaded code, I wanted to implement a version of Parallel.ForEach for .NET 3.5.

We are for the moment stuck with 3.5 and cannot upgrade.  We cannot use external libraries like TPL.

I found this via Google, but this threw sporadic exceptions during runtime, and because I couldn't find another Version I decided to roll my own.

I did of course test it, but i am always a bit cautious with multithreaded code.

public class Parallel
{
    public static void ForEach<T>(IEnumerable<T> items, Action<T> action)
    {
        if (items == null)
            throw new ArgumentNullException("enumerable");
        if (action == null)
            throw new ArgumentNullException("action");

        var resetEvents = new List<ManualResetEvent>();

        foreach (var item in items)
        {
            var evt = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem((i) =>
            {
                action((T)i);
                evt.Set();
            }, item);
            resetEvents.Add(evt);
        }

        foreach (var re in resetEvents)
            re.WaitOne();
    }
}


texts: Searching an element in an alternately sorted array

texts:
I had to write some code that receives a number 'x' and an alternately sorted array (an array with all even indexes sorted upwards and all odd indexes sorted downwards) and checks if 'x' exists in the array. If it exists, the method will return the index, if not, the method will return -1.

If there is more than one 'x' in the array, I can choose which one to return.
An array example: {-3, 10, 0, 9, 2, 5, 3, 0, 6, -5}

I've written the following code, and I will like to hear what you think, how I can improve it, and if you think of some cases when it won't work:

public static int find(int[] a, int x) {
    int topEven = a.length - 1, topOdd = a.length - 1, bottomEven = 0, midEven = 0, bottomOdd = 1, midOdd = 0;
    if (a.length == 0) {
        return -1;
    } else if (a[0] == x) {
        return 0;
    } else if (a[topOdd] == x) {
        return topOdd;
    }
    while (topEven > bottomEven) {
        midEven = ((topEven + bottomEven) / 2);
        if (midEven % 2 != 0) {
            midEven++;
        }
        if (x > a[midEven]) {
            bottomEven = midEven + 1;
        } else if (x < a[midEven]) {
            topEven = midEven - 1;
        } else
            return midEven;
    }
    while (topOdd > bottomOdd) {
        midOdd = ((topOdd + bottomOdd) / 2);
        if (midOdd % 2 == 0) {
            midOdd++;
        }
        if (x > a[midOdd]) {
            topOdd = midOdd - 1;
        } else if (x < a[midOdd]) {
            bottomOdd = midOdd + 1;
        } else
            return midOdd;
    }
    return -1;
}

Thank you!


texts:
Inspired by a SO post, just as an exercise, I tried to implement a way of notifying a consumer of a class about whether a property on an object has changed or not. I'm not attempting to use this in anyway, but I would like to learn from it.

interface INotifyPropertyChanged
{
    function PropertyChanged($name);
    function RegisterChangeCallback($callback);
}

abstract class NotifyPropertyChanged implements INotifyPropertyChanged
{
    public $changes;
    public $trackChanges;
    private $callback;

    public function PropertyChanged($name)
    {
        if( $this->callback != null){
            call_user_func($this->callback, $name);
        }

        if( !isset($this->changes))
            $this->changes = Array();

        if( !in_array($name, $this->changes))
            $this->changes[] = $name;
    }

    public function RegisterChangeCallback($callback)
    {
        $this->callback = $callback;
    }

    public function __set($name, $value)
    {
        $previousValue = $this->$name;
        $this->$name = $value;

        if( $this->trackChanges && $previousValue !== $value) {
            $this->PropertyChanged($name);
        }
    }

    public function __get($name)
    {
        return $this->$name;
    }
}

Then, implementing a class;

class SampleClass extends NotifyPropertyChanged
{
    protected $name;
}

And finally, usage;

$class = new SampleClass();
$class->name = "value";
$class->trackChanges = true;
$class->name = "test";
var_dump($class->changes);

And if you want, you can call $class->RegisterChangeCallback(..) to be told when it does change.

Like I said, I'm not planning on using this, it was an exercise to see if I could do something similar to .NETs INotifyPropertyChanged. And, what better way to get feedback on an idea.


texts:
Link here I'm currently learning c++ coming from a python background, so I'll include a solution in python and in c++ for the problem statement below, I'm including both for convenience, if you don't know c++, feel free to review python and vice versa.

Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

Example 1:
Input: words = ['flower', 'flow', 'flight']
Output: 'fl'
Example 2:
Input: strs = ['dog', 'racecar', 'car']
Output: ''
longest_common_prefix.py
def get_longest(words):
    if not words:
        return ''
    common = words[0]
    for word in words:
        while not word.startswith(common):
            common = common[:-1]
    return common

if __name__ == '__main__':
    print(f"Longest prefix: \n{get_longest(['flower', 'flow', 'fly'])}")

Leetcode stats:

Runtime: 32 ms, faster than 76.56% of Python3 online submissions for
Longest Common Prefix.

Memory Usage: 14 MB, less than 100.00% of Python3 online submissions
for Longest Common Prefix.

longest_common_prefix.h
#ifndef LEETCODE_LONGEST_COMMON_PREFIX_H
#define LEETCODE_LONGEST_COMMON_PREFIX_H

#include <string_view>
#include <vector>

std::string_view get_common_prefix(const std::vector<std::string_view>& words);

#endif //LEETCODE_LONGEST_COMMON_PREFIX_H

longest_common_prefix.cpp
#include <iostream>
#include <string_view>
#include <vector>

std::string_view get_common_prefix(const std::vector<std::string_view> &words) {
    if (words.empty())
        return "";
    std::string_view common = words[0];
    for (auto word: words) {
        while (word.find(common, 0) != 0) {
            common = common.substr(0, common.size() - 1);
        }
    }
    return common;
}

int main() {
    std::vector<std::string_view> xxx{"flow", "flower", "fly"};
    std::cout << "Longest prefix:\n" << get_common_prefix(xxx);
}

Leetcode stats:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for
Longest Common Prefix.
Memory Usage: 9.9 MB, less than 7.29% of C++
online submissions for Longest Common Prefix.


texts:
I had a task where I was supposed to write a solution to sort entries(Name, score - in an array/list) in order of score and generate ranking based on higher score to lower scores.

I tried doing that, code is working what it was supposed to do but it seems very ambiguous and tightly coupled, I can't even write a unit test for it.

Could someone have a look and suggest.

I have pasted main method class, If anyone wants me to paste other relevent classes as well so do ask me please.

Any suggestion(s)/workaround(s) would be much appreciated.

public class JournalAnalyzer {
    final static int LENGTH_OF_JOURNAL = 5; //Length Journal array
    static int count = 0;
    static Integer ranking = 1;
    static Journal[] journals = new Journal[LENGTH_OF_JOURNAL];
    static ArrayList<Journal> list = new ArrayList<Journal>();
    static Object[] scoreList = new Object[LENGTH_OF_JOURNAL];
    static String journalName;
    static Double journalScore;
    static Integer journalRank;
    static Boolean journalReview;

private static void initData(Journal[] journals) {
    journals[0] = new Journal(0, "Journal A", 5.6, false);
    journals[1] = new Journal(0, "Journal B", 2.6, false);
    journals[2] = new Journal(0, "Journal C", 3.2, false);
    journals[3] = new Journal(0, "Journal D", 4.1, false);
    journals[4] = new Journal(0, "Journal E", 1.6, false);
}

private static int fillJournalList(int count, Journal[] journals,
        int LENGTH_OF_JOURNAL, ArrayList<Journal> list) {

    for (int i = 0; i < LENGTH_OF_JOURNAL; i++) {
        journalRank = new Integer(journals[i].getRank());
        journalName = new String(journals[i].getJournal());
        journalScore = new Double(journals[i].getScore());
        journalReview = new Boolean(journals[i].getIsReviewed());

        if (!journalReview) {
            Journal value = new Journal(journalRank, journalName,
                    journalScore, journalReview);
            list.add(value);
            count++;
        } else {
            continue;
        }
    }
    return count;
}

private static void GenerateRanking(Integer ranking, int count,
        ArrayList<Journal> list, Object[] scoreList) {
    Double scoreComparatorOne;
    Double scoreComparatorTwo;

    Comparator<Journal> scores = new SortScore();
    Collections.sort(list, scores);

    for (int i = 0; i < count; i++) {
        scoreComparatorOne = (list.get(i)).getScore();
        if (i == 0) {
            scoreComparatorTwo = (list.get(i)).getScore();
        } else {
            scoreComparatorTwo = (list.get(i - 1)).getScore();
        }
        if (scoreComparatorOne.equals(scoreComparatorTwo)) {
            if (ranking == 0) {
                ranking += 1;
            } else {
                ranking = ranking;
            }
        } else {
            ranking = i + 1;
        }

        (list.get(i)).setRank(ranking);
        scoreList[i] = (list.get(i));

    }
}

private static void displayJournal(int counter, Object[] scoreList) {
    JournalOutput printer = new JournalOutput();
    printer.display(count, scoreList);
    System.exit(0);
}

public static void main(String[] args) throws IOException {
    initData(journals);
    count = fillJournalList(count, journals, LENGTH_OF_JOURNAL, list);
    GenerateRanking(ranking, count, list, scoreList);
    displayJournal(count, scoreList);
}
}

My question is how to minimize and simplify this code so that I can easily write a unit test for this class


texts:
This seems like a pretty basic question, so bear with me...Say I have two (or many) methods in the same class that need a LINQ to SQL DataContext. Additionally, I am needing the DataContext in other classes as well. Does it make sense to create the new DataContext every time?

Should I be creating this DataContext in a different data access class and then inheriting it on each page? I feel like this is the way it should be done, but I'm still learning LINQ to SQL and just looking for some best practices. Can anyone point me to good examples of this?

Thanks,

Code for reference:

protected void LoadProducts()
{
    StoreDataClassesDataContext db = new StoreDataClassesDataContext();
    var query = from p in db.Products

            select new
            {
             p.ProductID,
             p.Description,
             p.Price
            };

    dgProducts.DataSource = query;
    dgProducts.DataBind();
}

protected void LoadSales()
{
    StoreDataClassesDataContext db = new StoreDataClassesDataContext();
    var query = from s in db.Sales

                select new
                {
                s.SaleID,
                s.SaleDate,
                s.Total
                };

    dgSales.DataSource = query;
    dgSales.DataBind();
}


texts: Round a number and replace trailing zeros by spaces

texts:
Goal

From a number x, I would like a string of the rounded value at n decimals and replace each trailing zeros by a space.

Examples

Let n = 4

f(0.1, n=4)
[1] "0.1   " # 3 whitespace
f(0.1111999, n=4)
[1] "0.1112" # 0 whitespace
f(0.12, n=4)
[1] "0.12  " # 2 whitespace
f(0.1234, n=4)
[1] "0.1234" # 0 whitespace

Current solution

f <- function(x,n)
{
    s = sprintf(paste0("%.",n,"f"), x)
    for (i in 1:n)
    {
        s = gsub(
            paste0("0", paste0(rep("\\s",i-1),collapse=""),"$"),
            paste0(rep(" ",i), collapse=""),
            s
        )
    }
    return(s)
}

It works fine but it is a little cumbersome. I suspect a better regex solution.


texts:
Would anyone be so kind as to review my code for Memory?

import java.util.*;

public class Cards {

    public boolean gameInProgress = true;

    public void shuffleCards() {

        Scanner userInput = new Scanner(System.in);
        List cardList = new LinkedList();
        List matchedCards = new LinkedList();

        //this is the list of cards available to pick from
        String[] cards = {"a", "b", "c", "d", "e", "a", "b", "c", "d", "e"};

        //this shuffles the cards each game
        Collections.shuffle(Arrays.asList(cards));

        //this moves the cards array into a LinkedList
        Collections.addAll(cardList, cards);

        //main game loop. stops when all cards are matched
        while (gameInProgress) {

            //Stores the users card picks in variables card1 and card2
            System.out.println("pick a card (0-9)\n");

            int card1 = userInput.nextInt();

            System.out.println("First card picked is the letter " + cardList.get(card1));

            System.out.println("pick a second card.\n");

            int card2 = userInput.nextInt();

while(card1 == card2){
            System.out.println("You cannot pick the same card twice. Pick a different card.");
            card2 = userInput.nextInt();
        }

            System.out.println("second card picked is the letter " + cardList.get(card2));

            //checks if a card has been picked already
            while(matchedCards.contains(cardList.get(card1))) {
                System.out.println("First card already picked. Pick again: ");
                card1 = userInput.nextInt();
            }

            while(matchedCards.contains(cardList.get(card2))){
                System.out.println("Second card already picked. Pick again: ");
                card2 = userInput.nextInt();
            }

                //copies the matched cards to a new linked list
                if (cardList.get(card1) == cardList.get(card2)) {
                    System.out.println("You got a match!\n");

                    matchedCards.add(cardList.get(card1));
                    matchedCards.add(cardList.get(card2));

                    System.out.println("You have collected " + matchedCards.size() + "/10 cards");

                    System.out.println(matchedCards + " are in the matched pile\n");

                    //stops the game once all cards have been matched
                    if (matchedCards.size() == 10) {
                        System.out.println("You Win!!!");
                        gameInProgress = false;
                    }
                }
                else {
                    System.out.println("Not a match\n");

                }
        }
    }
}

    public class Game {

    public static void main(String[] args) {

        Cards card = new Cards();

        card.shuffleCards();

    }
}


texts: Simple State Machine and Transition Table

texts:
The goal is to have well defined state transitions, and the ability to provide the next event to execute.

I'd like to know if this is a proper implementation of State Machine, considering how states and transitionTable are defined, and how I handle event as input and output via nextEvent.

In many examples I cannot clearly define verbiage for state, so I defined them as verbs (notice ing suffix), as if it represents the ongoing progress of workflow. This may be wrong..

I also defined multiple events that could occur for a single state. For example, GetDeviceStatus and GetIntegrityStatus events both occur in RetrievingStatus state. This is also the case for Downloading state. You can see in the cases, when determining the next event, I need to check what the previous state was first.

If flawed, what are the pitfalls to my design, and how could it be improved? thanks.

enum ExampleState {
    case Initiate
    case Authorizing
    case RetrievingStatus
    case Downloading
    case Confirming
    case End
}

enum ExampleEvent {
    case InitiateSequence
    case GetAuthToken
    case GetDeviceStatus
    case GetIntegrityStatus
    case DownloadFromServer
    case DownloadToDevice
    case Confirm
}

class StateMachine {

var oldState: ExampleState!
var currentState: ExampleState!
var currentEvent: ExampleEvent!

var table: [ExampleState: [ExampleEvent: ExampleState]] = [.Initiate:         [.InitiateSequence:   .Authorizing],
                                                           .Authorizing:      [.GetAuthToken:       .RetrievingStatus],
                                                           .RetrievingStatus: [.GetDeviceStatus:    .Downloading, .GetIntegrityStatus: .Confirming],
                                                           .Downloading:      [.DownloadFromServer: .Downloading, .DownloadToDevice: .RetrievingStatus],
                                                           .Confirming:       [.Confirm:            .End]]

func nextEvent(event: ExampleEvent) -> EventExecutor? {

    let transitionState = table[currentState]![event]!
    let oldState = currentState

    switch (transitionState) {

        case .Initiate:
            currentState = .Initiate
            return InitiateSequence()

        case .Authorizing:
            currentState = .Authorizing
            return GetAuthToken()

        case .RetrievingStatus:
            currentState = .RetrievingStatus
            switch (oldState) {
            case .Authorizing: return GetDeviceStatus()
            case .Downloading: return GetIntegrityStatus()
            default: return nil
            }

        case .Downloading:
            currentState = .Downloading
            switch (oldState) {
            case .RetrievingStatus: return DownloadFromServer()
            case .Downloading: return DownloadToDevice()
            default: return nil
            }

        case .Confirming:
            currentState = .Confirming
            return Confirm()

        case .End:
            currentState = .End
            return nil
    }

}
}

Use case

@objc func rxExecute() {
    publisher
        .map { self.stateMachine.nextEvent(event: $0) } // $0 == event that just completed
        .flatMap { $0!.rxExecute() } // execute next event from state machine output
        .subscribe(subscriber) // handles errors/success from completed event
}


texts:
You are given information about users of your website. The information
  includes username, a phone number and/or an email. Write a program
  that takes in a list of tuples where each tuple represents information
  for a particular user and returns a list of lists where each sublist
  contains the indices of tuples containing information about the same
  person. For example:

  Input:

[("MLGuy42", "andrew@gmail.com", "123-4567"),
("CS229DungeonMaster", "123-4567", "ml@stanford.edu"),
("Doomguy", "john@oculus.com", "carmack@gmail.com"),
("andrew26", "andrew@gmail.com", "mlguy@gmail.com")]

  Output:

[[0, 1, 3], [2]]

  Since "MLGuy42", "CS229DungeonMaster" and "andrew26" are all the same
  person.

  Each sublist in the output should be sorted and the outer list should
  be sorted by the first element in the sublist.

Below is the code snippet that I did for this problem. It seems to work fine, but I'm wondering if there is a better/optimized solution.

def find_duplicates(user_info):
    results = list()
    seen = dict()
    for i, user in enumerate(user_info):
        first_seen = True
        key_info = None
        for info in user:
            if info in seen:
                first_seen = False
                key_info = info
                break
        if first_seen:
            results.append([i])
            pos = len(results) - 1
        else:
            index = seen[key_info]
            results[index].append(i)
            pos = index
        for info in user:
            seen[info] = pos
    return results


texts:
Can anyone think of a way to DRY up this code or is there a way to make it more efficient or quicker. Its what authenticates a user with my API and i want to make it as fast as possible.

def authenticate!
  authenticate_or_request_with_http_basic do |access_key, secret_key|
    @current_app = App.find_by_access_key(access_key)
    @current_app.secret_key == secret_key ? true : false
  end
end


texts: Parsing numbers and ranges from a string in Javascript

texts:
I would like to convert a string like "1 2 3-5" to an array of numbers [1, 2, 3, 4, 5].

Following the robustness principle, the list doesn't need to be separated by spaces, comma on any other separator is accepted. The only mandatory syntax is A-B to represent range from A to B (inclusive). Also, it's ok to ignore malformed input (like 1-3-5), it can be considered "undefined behavior" as long as it doesn't raise an exception.

My current code is a follow:

function parse(string) {
    let numbers = [];
    for (let match of string.match(/[0-9]+(?:\-[0-9]+)?/g)) {
        if (match.includes("-")) {
            let [begin, end] = match.split("-");
            for (let num = parseInt(begin); num <= parseInt(end); num++) {
                numbers.push(num);
            }
        } else {
            numbers.push(parseInt(match));
        }
    }
    return numbers;
}

This seems quite convoluted for such a simple task. Is there any alternative more straightforward using "modern" Javascript (I'm targeting ES6)?


texts: Replace multiple occurrences of a character

texts:
I try to replace multiple occurrences of a character with a single character.

Input:

  hhiii!!!  hooowww   aaareee   yyyooou???

Output:

  hi! how are you?

public class CharSingleOccurrence {
    public static void main(String... args){
        charSingleOccurrence("hhiii!!!  hooowww   aaareee   yyyooou???");
    }
    public static void charSingleOccurrence(String str){
        int i=0;
        int j=0;
        char arr[]=new char[50];
        while (i<str.length()-1) {
            if(str.charAt(i)!=str.charAt(i+1)){
                arr[j]=str.charAt(i);
                i++;
                j++;
            }else{
                i++;
            }
        }
        arr[j]=str.charAt(str.length()-1);
        for(char c:arr){
            System.out.print(c);
        }
    }
}

Here I need review for

char arr[]=new char[50];
arr[j]=str.charAt(str.length()-1);


texts: Largest Palindrome Product - Project Euler #4

texts:
This is my code for Project Euler Problem #4
The question:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

My code:

function problem4(){
    let product = 1;
    let largest = 1;
    for(let i = 100; i<1000; i++){
        for(let j = i; j<1000; j++){
            product = i*j;
            if(("" + product) == ("" + product).split("").reverse().join("")){
                largest = Math.max(largest, product);}
}
    }
    return largest;
}
console.log(problem4());

At present, it takes 311.5649999999732 ms for execution, but I think it can be better. So how can I make it more efficient and faster?


texts:
This is (yet another) integer to Roman numeral converter.

To give it a slightly interesting twist, I've implemented this as a num_put facet of a C++ locale, so by creating the right locale, and imbuing a stream to use that locale, all the numbers written to that stream will be written out in Roman numerals (yeah, I know that's probably rarely useful or desirable, but it seemed like an interesting thing to do at the time).

Here's the header:

#ifndef ROMAN_H_INC_
#define ROMAN_H_INC_

#include <string>
#include <locale>
#include <ios>
#include <iostream>

template <class charT, class OutputIterator = std::ostreambuf_iterator<charT> >
class roman : public std::num_put < char > {
public:
    typedef charT char_type;
    typedef OutputIterator iter_type;

protected:

    virtual iter_type do_put(iter_type out, std::ios_base &, char_type, long v) const {
        return fmt(v, out);
    }

    virtual iter_type do_put(iter_type out, std::ios_base &, char_type, long long v) const {
        return fmt(v, out);
    }

    virtual iter_type do_put(iter_type out, std::ios_base &, char_type, unsigned long v) const {
        return fmt(v, out);
    }

    virtual iter_type do_put(iter_type out, std::ios_base &, char_type, unsigned long long v) const {
        return fmt(v, out);
    }

    std::string fmt_internal(unsigned long long value) const {

        struct conv {
            int val;
            std::string rep;
        };

        static const conv table[] = {
            { 1000, "M" },
            { 900, "CM" },
            { 500, "D" },
            { 400, "CD" },
            { 100, "C" },
            { 90, "XC" },
            { 50, "L" },
            { 40, "XL" },
            { 10, "X" },
            { 9, "IX" },
            { 5, "V" },
            { 4, "IV" },
            { 1, "I" }
        };

        std::string roman;

        for (auto const &c : table) {
            while (value >= c.val) {
                roman += c.rep;
                value -= c.val;
            }
        }
        return roman;
    }

    template <class T, class Iter>
    Iter fmt(T t, Iter i) const {
        std::string s = fmt_internal(t);
        std::copy(s.begin(), s.end(), i);
        return i;
    }
};

#endif

And here's a short demo program:

#include <iostream>
#include "roman.h"

int main() {
    auto loc = std::locale(std::locale(), new roman<char>);
    std::cout.imbue(loc);

    for (int i = 1; i <= 100; i++) {
        std::cout << i << "\t";
        if (i % 10 == 0)
            std::cout << "\n";
    }
}


texts: Clean implementation of FTP File Cleaners

texts:
I was refactoring some of my utility code modules used in my test projects, and wanted to apply my knowledge of clean OOP design patterns and SOLID principles to make these modules more useful and easier to use.

I have an interface called IFtpFileCleaner:

/// <summary>
/// Responsible for deleting a single file located in a remote server
/// </summary>
public interface IFtpFileCleaner
{
    /// <summary>
    /// Deletes a remote file
    /// </summary>
    /// <param name="remotePath">
    /// The full remote path.
    /// </param>
    void Clean(string remotePath);
}

I have an abstract class called RemoteFileCleaner, which implements IFtpFileCleaner:

/// <summary>
/// The file cleaner base class provides common code for all the implementations to reduce code duplication
/// </summary>
public abstract class RemoteFileCleaner : IFtpFileCleaner
{
    /// <summary>
    /// The FTP _client.
    /// </summary>
    private readonly IFtpSecureClient _client;

    /// <summary>
    /// Initializes a new instance of the <see cref="RemoteFileCleaner"/> class.
    /// </summary>
    /// <param name="client">
    /// The FTP client.
    /// </param>
    protected RemoteFileCleaner(IFtpSecureClient client)
    {
        _client = client;
    }

    /// <summary>
    /// Deletes a single file located on a remote server
    /// </summary>
    /// <param name="remotePath">
    /// The full path of the remote file.
    /// </param>
    public void Clean(string remotePath)
    {
        try
        {
            _client.Init();
            _client.DeleteFile(remotePath);
        }
        catch (Exception e)
        {
            Console.WriteLine($"Failed to clean file {remotePath}.{Environment.NewLine}{e}");
            throw;
        }
        finally
        {
            _client.Disconnect();
        }
        Console.WriteLine($"Remote File {remotePath} was deleted.");
    }
}

Now, I can have concrete implementations of my file cleaners. Like SFTPFileCleaner, FTPFileCleaner, and FTPSFileCleaner. They all look very similar. For instance, SFTPFileCleaner looks like this:

/// <summary>
/// The SFTP implementation of <see cref="RemoteFileCleaner"/>.
/// </summary>
public class SFTPFileCleaner : RemoteFileCleaner
{
    /// <summary>
    /// Initializes a new instance of the <see cref="SFTPFileCleaner"/> class.
    /// </summary>
    public SFTPFileCleaner()
        : base(new FtpSecureClientTestFactory().CreateSFTPClient())
    {
    }
}

As you can see, I am performing "Bastard Injection" here in the concrete implementation because I would like to easily instantiate these cleaners in my test methods. Here is an example:

[TearDown]
public void Cleanup()
{
    _ftpCleaner = new SFTPFileCleaner();
    _ftpCleaner.Clean(_expectedRemotePath);
}

What do you guys think about this design? Is it clean and easy to use?
Can it be improved any further?
Is there a name for this design pattern? To me is seems to be the mixture of Facade Pattern (Bastard Injection) and Strategy Pattern. Am I correct?


texts: Saving and loading parts of configuration

texts:
I have a piece of code where I have string pairs (eg. 'a' and 'AA'), where both have their own unique ids. Id for first object is configured by user and second id is received at some point during runtime.

Example code:
http://repl.it/BE5N

Is there smarter way to load/save second ids from/to a file?
It feels somewhat unnecessary to loop through all configs every time new id is found (even if it doesn't happen that often)

And if I added completely new pair-configs during runtime, how should I add them to user's config file while still keeping it human readable?

Initial setup:

var fs = require('fs');

// config pair for first and second
function config (first, second, first_id) {
    this.first    = first;
    this.second   = second;
    // use name as an id for first if none is given
    this.first_id = first_id ? first_id : first;
}

var lookup = function (type, name, arr) {
    return arr.filter(function (obj) {
        return obj[type] === name;
    })[0];
};

// initial config file (few lines out of many)
// user doesn't know second ids
configs = [
    new config('a', 'AA', 'a_id'),
    new config('b', 'BB'),
    new config('c', 'C'),
    new config('d', 'D', 'd_id'),
    new config('e', 'EEE')
];

// read ids for seconds from file if it exists
// read json from file
input_json = {"AA":123,"C":321,"EEE":456};
for (var i=0; i<configs.length; ++i) {
    var key = configs[i].second;
    if (key in input_json) {
        configs[i].second_id = input_json[key];
    }
}

While program is running and new id's are found:

// add new id for 'BB'
BB_config = lookup('second', 'BB', configs);
BB_config.second_id = 654;

// write edited json to file
var output_json = {};
for (var i=0; i<configs.length; ++i) {
    if (configs[i].second_id) {
        output_json[configs[i].second] = configs[i].second_id;
    }
}

console.log(JSON.stringify(output_json));


texts:
I was writing this code to check if a tree is balanced or not and I ran into a situation where I would have liked the method to return 2 values at each step. First to signify whether the tree is balanced at that level or not, and second to return the height at the level so that I can use it to check the balanced nature of the parent. I ended up writing the method such that it returns -1 if the tree is not balanced and the actual height if the tree is balanced at that level.

Is there a better way to do it? If not, then I think I should at least have a better name for the method getHeight. Can you review my code as a whole and let me know my shortcomings?

public boolean isBalanced(Node root){
        return getHeight(root)!=-1;
    }

private int getHeight(Node node){
    if(node ==null)
        return 1;

    int leftHeight = getHeight(node.getLeft());
    int rightHeight = getHeight(node.getRight());
    if(leftHeight==-1 || rightHeight ==-1)
        return -1;

    int diff = Math.abs(leftHeight-rightHeight);
    if(diff>1)
        return -1;

    return Math.max(leftHeight,rightHeight) + 1;

}


texts:
OK, maybe crazy overkill and a little silly, but why not? Here's a Python FizzBuzz Acceptance Test:

import unittest
from fizzbuzzmodule import fizzbuzz

class FizzBuzzAcceptanceTestCase(unittest.TestCase):
    '''
    Test that fizzbuzz(int) returns int
    unless multiple of 3 (then returns 'fizz')
           multiple of 5 (then returns 'buzz')
           multiple of both (then returns 'fizzbuzz')
    '''
    def test_business_as_usual(self):
        '''
        test that an integer >= 0 not evenly divisible
        by three or five returns the same
        '''
        self.assertEqual(fizzbuzz(1), 1)
        self.assertEqual(fizzbuzz(2), 2)
        self.assertEqual(fizzbuzz(4), 4)
        self.assertEqual(fizzbuzz(7), 7)
        self.assertEqual(fizzbuzz(998), 998)
    def test_fizz(self):
        '''evenly divisible by 3 returns fizz'''
        self.assertEqual(fizzbuzz(3), 'fizz')
        self.assertEqual(fizzbuzz(6), 'fizz')
        self.assertEqual(fizzbuzz(111), 'fizz')
        self.assertEqual(fizzbuzz(999), 'fizz')
    def test_buzz(self):
        '''evenly divisible by 5 returns buzz'''
        self.assertEqual(fizzbuzz(5), 'buzz')
        self.assertEqual(fizzbuzz(10), 'buzz')
        self.assertEqual(fizzbuzz(20), 'buzz')
        self.assertEqual(fizzbuzz(500), 'buzz')
    def test_fizz_buzz(self):
        '''evenly divisible by 3 and 5 returns fizzbuzz'''
        self.assertEqual(fizzbuzz(15), 'fizzbuzz')
        self.assertEqual(fizzbuzz(30), 'fizzbuzz')
        self.assertEqual(fizzbuzz(45), 'fizzbuzz')
        self.assertEqual(fizzbuzz(600), 'fizzbuzz')

    # def test_zero(self):
        # self.assertEqual(fizzbuzz(0), 'fizzbuzz') #??????

def main():
    unittest.main()

if __name__ == '__main__':
    main()

Typed up a little implementation that passes these tests:

def fizzbuzz(number):
    '''
    if number divisible by 3 return 'fizz';
    5, 'buzz'; both, fizzbuzz
    else return number
    '''
    if not number % 3:
        if not number % 5:
            return 'fizzbuzz'
        else:
            return 'fizz'
    if not number % 5:
        return 'buzz'
    return number

def main():
    for i in range(1, 101):
        print fizzbuzz(i)

And when I run the tests:

>>> unittest.main()
....
----------------------------------------------------------------------
Ran 4 tests in 0.002s

OK

And my question is, how would you augment the above? Would you find it useful to run this test on someone's code? Does it clearly define a clean API? Would it be preferable to return a consistent type instead of strings or ints?

Should I have done this differently? Have I not considered any edge or corner cases?


texts:
I was told my code contains a lot of force unwrapping. I thought it's okay to do that if I am sure that the value operated won't be nil:
private var x: Int?
private var y: Int?

@IBAction func startButtonPressed(_ sender: UIButton) {

    guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty else {
        return selectedRooms.placeholder = "type it, dude"
    } //if user typed something
    let rooms = Int(numberOfRooms)

    x = Int(ceil(sqrt(Double(rooms!))))
    y = x //grab some values from user input
    maze = MazeGenerator(x!, y!) //generate a maze
    hp = 2 * (x! * y!) //get hp value depending on user input
    hpLabel.text = "hp: \(hp)"

    currentX = getRandomX(x!) //get random value in 0...x
    currentY = getRandomY(y!)
    currentCell = maze?.maze[currentX!][currentY!] //game starts in a random part of the maze

    for item in items.indices { //create and show some imageViews
        items[item].location = (getRandomX(x!), getRandomX(y!))
        createItems(imageName: items[item].imageName)
        if items[item].location == (currentX!, currentY!) {
            reveal(index: item)
        } else {
            hide(index: item)
        }
    }
    refreshButtons() //refresh UI
    maze!.display() //print maze scheme in debug console
    }

Does it look fine? If not, what should be done?