texts:
I made this method that takes any string and transforms it into a multiline text l; each line having the max (character) length specified by the rowLength parameter.

How can I make this better, functionality and code wise?

There is currently one known issue. It sometimes adds an empty line at the end because I have to add the Enviroment.NewLine call. Check it out, please, and give some suggestions.

public static string ConvertToMultiLineText(string value, int rowLength)
{
    var multiLine = new StringBuilder();
    string[] lines = value.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
    var filterLines = lines.Where(line => !line.IsNullEmptyOrWhiteSpace());

    foreach (var line in filterLines)
    {
        if (line.IsNullEmptyOrWhiteSpace())
            continue;

        if (line.Length > rowLength)
        {
            int startIndex = 0;
            var number = (decimal)line.Length / rowLength;
            var rowNumber = Math.Ceiling(number);

            for (int i = 0; i < rowNumber; i++)
            {
                if (line.Contains(@" "))
                {
                    int lastIndex = rowLength;

                    // if it's not the first row set the last character on the current row of the iteration
                    if (i != 0)
                        lastIndex = (rowLength * (i + 1));

                    // if it's the last row set last character as the lenght of the last row
                    if (i == rowNumber - 1)
                        lastIndex = line.Length - 1;

                    int lastSpace = line.LastIndexOf(@" ", lastIndex, StringComparison.Ordinal);

                    //if " " is found inside the string
                    if (lastSpace > -1)
                    {
                        var lastOccurence = (lastSpace <= startIndex) ? startIndex - lastSpace : lastSpace - startIndex;

                        if (i == rowNumber - 1)
                            multiLine.Append(line.Substring(startIndex, lastOccurence) + Environment.NewLine + line.Substring(lastSpace, line.Length - lastSpace));
                        else
                            multiLine.Append(line.Substring(startIndex, lastOccurence) + Environment.NewLine);

                        startIndex = lastSpace;
                    }
                    else
                    {
                        if (i == rowNumber - 1)
                            multiLine.Append(line.Substring(startIndex, (line.Length - rowLength * ((int)rowNumber - 1))));
                        else
                            multiLine.Append(line.Substring(startIndex, rowLength) + Environment.NewLine);
                        startIndex += rowLength;
                    }
                }
                else
                {
                    if (i == rowNumber - 1)
                        multiLine.Append(line.Substring(startIndex, (line.Length - rowLength * ((int)rowNumber - 1))));
                    else
                        multiLine.Append(line.Substring(startIndex, rowLength) + Environment.NewLine);
                    startIndex += rowLength;
                }
            }
        }
        else
            multiLine.Append(line.Substring(0, line.Length) + Environment.NewLine);
    }

    return string.Format(@"{0}", multiLine);
}


texts: Best practice for properties initialization using constructor

texts:
I am declaring a "class" using a "constructor method". In both samples, properties uuid and dateCreated are initialized but in different places.

I would like to know the "best practice" in this scenario and why (also in terms of readability).

Solution A

define([
    'dojo/_base/declare',
    'dojo/_base/lang',
], function (declare, lang) {
    return declare('xxx.xxx.Command', null, {
        uuid: utilis.UUID(), // IS GOOD PRACTICE?
        dateCreated: Date.now(), // IS GOOD PRACTICE?
        action: null,
        properties: null
        },
        constructor: function (action, receiver, properties) {
            this.action = action;
            this.receiver = String(receiver);
            this.properties = properties;
        }
    });
});

Solution B

define([
    'dojo/_base/declare',
    'dojo/_base/lang',
], function (declare, lang) {
    return declare('xxx.xxx.Command', null, {
        uuid: null,
        dateCreated: null,
        action: null,
        properties: null
        },
        constructor: function (action, receiver, properties) {
            this.uuid = utilis.UUID();
            this.dateCreated = Date.now();
            this.action = action;
            this.receiver = String(receiver);
            this.properties = properties;
        }
    });
});


texts:
How can I optimize the if condition in this snippet? The only one difference is && [self isCurrentPosition:i]. How can I make it a single if, including the condition val?

Note: self is a category of NSArray.

- (void) cleanTextfieldExcluding:(int)current checkPosition:(BOOL)val {
  for ( int i=0; i<[self count]; i++ ) {

    // -----------
    if ( val ) {  // this IF block is very bad
      if ( i != current && [self isCurrentPosition:i] )
        [self replaceObjectAtIndex:i withObject:@""];
    } else {
      if ( i != current )
        [self replaceObjectAtIndex:i withObject:@""];
    }
    // -----------

  }
}


texts: Simple web based file browser with Flask

texts:
I made a simple web-based file browser with Flask. It also shows some metadata of a file. I have a few questions regarding security though. Is it possible for an attacker to escape out of the preset root directory? Are there any ways to make my code more readable and/or more efficient? Would love to hear some feedback to improve my program! :)

app.py:

from flask import Flask, render_template
import os
import stat

app = Flask(__name__)

# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app

FILE_SYSTEM_ROOT = "D:\Test123"

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/browser')
def browse():
    itemList = os.listdir(FILE_SYSTEM_ROOT)
    return render_template('browse.html', itemList=itemList)

@app.route('/browser/<path:urlFilePath>')
def browser(urlFilePath):
    nestedFilePath = os.path.join(FILE_SYSTEM_ROOT, urlFilePath)
    if os.path.isdir(nestedFilePath):
        itemList = os.listdir(nestedFilePath)
        fileProperties = {"filepath": nestedFilePath}
        if not urlFilePath.startswith("/"):
            urlFilePath = "/" + urlFilePath
        return render_template('browse.html', urlFilePath=urlFilePath, itemList=itemList)
    if os.path.isfile(nestedFilePath):
        fileProperties = {"filepath": nestedFilePath}
        sbuf = os.fstat(os.open(nestedFilePath, os.O_RDONLY)) #Opening the file and getting metadata
        fileProperties['type'] = stat.S_IFMT(sbuf.st_mode)
        fileProperties['mode'] = stat.S_IMODE(sbuf.st_mode)
        fileProperties['mtime'] = sbuf.st_mtime
        fileProperties['size'] = sbuf.st_size
        if not urlFilePath.startswith("/"):
            urlFilePath = "/" + urlFilePath
        return render_template('file.html', currentFile=nestedFilePath, fileProperties=fileProperties)
    return 'something bad happened'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

browse.html:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

        {% for item in itemList %}

{{ item }}

        {% endfor %}

file.html:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

Current file: {{ currentFile }}

            {% for key, value in fileProperties.items() %}

                {{ key }}
                {{ value }}

            {% endfor %}

The output when browsing looks something like this:

The output with the metadata of a file looks like this:


texts: Splitting a String into words and add to an array, Only using StringBuffer and String Array

texts:
I've been doing a Java for beginners course for a few weeks (2 hours a week), we had an exam question.

  Take a sentence as an input from a user for twitter. Using only String
  Arrays and String Buffers (do not use split() or any other methods not
  covered in class yet). Separate the sentence into words and add to an
  array. Then change any instance of the word "cannot" with "can't".
  Must use an instantiable class and all relevant set, compute, get
  methods covered. Comment all code to show you understand what
  everything you've used is doing.

This is the code I submitted (it works), looking for feedback before the results come out to see what I can expect.

Thanks

App Class
    enter code here

public class tweetApp{
    public static void main(String arg[]){
        //decalre variables
        String sentence;
        //create an array for the new sentence
        String [] newSentence;

        //instaniate classes
        tweet myTweet;
        Scanner input;
        //creat classes
        myTweet = new tweet();
        input = new Scanner(System.in);

        System.out.print("Enter a sentence: ");
        sentence = input.nextLine();

        //set method for the sentence inputted from the user
        myTweet.setSentence(sentence);
        //compute method for chaging the sentence given by the user
        myTweet.computeSentence();
        //set the array to the new changed sentence
        newSentence = myTweet.getNewSentence();
        //output each section of the array and a space, to print out the entire message
        for(int y = 0; y < newSentence.length; y++){
            System.out.print(newSentence[y]+" ");

        }
        //end the program by adding a blank print line to make sure the command line looks ok.
        System.out.println();
    }
}

enter code here

Instantiable class

enter code here
public class tweet{
    //declare variables
    private String sentence;
    private int strlen;
    private StringBuffer word;
    private String newSentence[];
    private String newWord;
    private int wordCount;
    //create constuctor
    public tweet(){
        sentence = " ";
        strlen = 0;
        word = new StringBuffer();
        wordCount = 1; //starting at 1 if user enters 1 word
        newSentence = new String[wordCount];
        newWord = " ";
    }
    //set method
    public void setSentence(String sentence){
        this.sentence = sentence;
    }
    //compute method
    public void computeSentence(){
        strlen = sentence.length();//get length of sentence
        for(int x = 0; x < strlen; x++){//transverse the string,
            if(sentence.charAt(x)==' '){//calculate word count
                wordCount = wordCount +1;
            }
        }
        newSentence = new String[wordCount]; //use word count to set size of the array
        for(int j = 0; j < newSentence.length; j++){//transverse the array,
            for(int i = 0; i< strlen; i++){//transverse string,
                if(sentence.charAt(i) == ' '){//check if char is a space,
                    j = j+1;//if so,increment j by 1
                    word = new StringBuffer();//start a new buffer
                }
                else{
                    word.append(sentence.charAt(i));//char at i, append to buffer,
                    newWord = word.toString();//convert buffer to string,
                    newSentence[j] = newWord;//add to j'th place of array
                    }
            }
        }
        for(int x = 0; x < newSentence.length; x++){//change any instance of cannot to can't
            if(newSentence[x].equalsIgnoreCase("cannot")){
                newSentence[x] = "can't";
            }
        }
    }
        //get method, returning new sentence to app class
        public String[] getNewSentence(){
            return newSentence;
        }
    }


texts: Array decomposing recursive function in JavaScript

texts:
What I need is to remove first word from the string again and again until only one word is left, and put it all into array.

For example, I have this string as an input:

Chicago IL 12345 United States

What I need to achieve is this array:

[ 'Chicago IL 12345 United States',
'IL 12345 United States',
'12345 United States',
'United States',
'States' ]

My code works but I wanted to get rid of the second param, and maybe make the code shorter and look more beautiful.

Here is what I currently have:

const stringToArray = (str, arr) => {
  const result = arr || [];
  const wordArray = str.split(' ');
  const len = wordArray.length;
  result.push(str);

  if (len === 1) {
    return arr;
  }

  return stringToArray(wordArray.slice((-1 * len) + 1).join(' '), result);
};

const partsArray = stringToArray('Chicago IL 12345 United States');

console.log(partsArray);


texts: Pointers and string reverse function implementation

texts:
char * reverse_string(const char *s1)
{
int count = 0;
char *output;
char *o;
while(*s1 != '\0')
    s1++;

s1--;
output = new char[strlen(s1)];
o = output;

while(*s1)
    *output++ = *s1--;

if(*s1 == '\0')
    cout<<"yes";
return o;
}

int main()
{
const char *s1 = "hello world";
char *result;
result = reverse_string(s1);
cout<<result;
}

This is a way of implementing string reverse.  I know the code uses extra space and strlen(), which is not optimal.

But, my question is, when I decrement the s1 pointer one location from the beginning of the input string, it has '\0' as its value. I do not understand how that could be feasible? For testing, I am printing an "yes" (at the end of function strrevImp()).

Could someone point out if I am lost anywhere here?


texts:
I have prepared a small makefile for a small project, but I am trying to find what would be the best practices; up to now I have gathered these:

relatively idiomatic (typical structures, flows, var names for Least Astonishment)
define the products in terms of the inputs (if I have .c files and want an exec, why should I think about intermediate files?)
up-to-date with GNU make's and gcc's capabilities (auto-dependency tracking)
silent by default
but can be verbose (for Eclipse integration for example)
keeps object files in directories separate from sources
avoids implicit rules (explicit is clearer and anyway I wanted to mute the output)

Also a couple of make-quirk-addressing details like immediate assignment :=, order-only prerequisites…

So here's the makefile:

WARNINGS := -Wall -Wextra
CFLAGS ?= -std=gnu99 -g $(WARNINGS)

OBJDIR := obj
SRCDIR := src

# silent by default
ifeq ($(VERBOSE),1)
    SILENCER :=
else
    SILENCER := @
endif

# pass this environment variable to the C source
ifeq ($(DEBUG_BUILD),1)
    CFLAGS +=-DDEBUG_BUILD
endif

# typical way to list files and build full paths
# list the sources, not the object files (nor includes)
_SRCS := uthreads.c main.c
SRCS := $(patsubst %,$(SRCDIR)/%,$(_SRCS))
OBJS := $(patsubst %,$(OBJDIR)/%,$(_SRCS:c=o))

# generate phony deps during compilation
CFLAGS += -MMD -MP
DEPS := $(patsubst %,$(OBJDIR)/%,$(_SRCS:c=d))
# can't include the deps before the first, default target has appeared!

# "all" is the classical default target
all: main

createdir:
        $(SILENCER)mkdir -p $(OBJDIR)

main: $(OBJS)
        #@echo " LINK $^"
        $(SILENCER)$(CC) $(CFLAGS) -o $@ $^

# put object and dependency files away from the sources
# create the dir before building into it
$(OBJDIR)/%.o: $(SRCDIR)/%.c | createdir
        #@echo " CC $<"
        $(SILENCER)$(CC) $(CFLAGS) -c -o $@ $<

clean:
        $(SILENCER)$(RM) -f *~ core main
        $(SILENCER)$(RM) -r $(OBJDIR)

.PHONY: clean all

# dependencies won't turn into a default target here
-include $(DEPS)

I'll be grateful for any criticism or addition to either the list of "best practices" or to the makefile itself.

Thanks!


texts:
I currently have a code that is connecting to SQL database in VBA. The data is populating correctly. However, I was wondering if there is a way to condense the code below.

I have 4 different columns and 26 rows and I feel like if I go this route, I will be wasting a lot of time. I want the range to go from C20:C45 and the results to show from cells H20:H45.

Sub ConnectSqlServer()

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sConnString As String
    Dim wks As Worksheet, xRow As Long

    ' Create the connection string.
    sConnString = "Provider=SQLOLEDB;Data Source=chocnt-285;" & _
                  "Initial Catalog=trackerfy2015;" & _
                  "Integrated Security=SSPI;"

    ' Create the Connection and Recordset objects.
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset
' Open the connection and execute data for WFTEs.
   Set rs = conn.Execute("SELECT sum(Hours)/80 FROM payroll2015_rif WHERE DepartmentCode = '" & Range("$E$6") & "' AND payperiod = '" & Range("C20") & "' and paycode IN ('REG1', 'REG2');")
        ' Transfer result.
        Sheets(2).Range("$H20").CopyFromRecordset rs
    ' Close the recordset
        rs.Close

' Open the connection and execute data for WFTEs.
   Set rs = conn.Execute("SELECT sum(Hours)/80 FROM payroll2015_rif WHERE DepartmentCode = '" & Range("$E$6") & "' AND payperiod = '" & Range("C21") & "' and paycode IN ('REG1', 'REG2');")
        ' Transfer result.
         Sheets(2).Range("$H21").CopyFromRecordset rs
 ' Clean up
    If CBool(conn.State And adStateOpen) Then conn.Close
    Set conn = Nothing
    Set rs = Nothing

End Sub


texts: Functional Pascal triangle in Python (working version)

texts:
This is actually a follow-up question of Yet another Pascal triangle in Python written in functional programming pattern, which is put on hold for posting broken code.

Again, this is my implementation of a Pascal program, which is used to print an n-order Pascal triangle. I write it to familiarize myself with Python's Functional Programming Modules. Some changes have been made to get the code work and make it more "functional"

#!/usr/bin/env python3

import operator
from itertools import starmap, tee

def pairwise(iterable):
    """
    s -> (s0,s1), (s1,s2), (s2,s3), ...
    https://docs.python.org/3/library/itertools.html#itertools-recipes
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def pascal_row(n):
    """
    Return a generator that yields the nth row of a Pascal triangle
    """
    if n < 2:
        return (x for x in [1])
    else:
        def dispatch():
            yield 1
            yield from starmap(operator.add, pairwise(pascal_row(n-1)))
            yield 1
        return dispatch()

def print_pascal(n):
    """
    Print an n-order Pascal triangle
    """
    if n > 0:
        print_pascal(n-1)
        print(list(pascal_row(n)))

print_pascal(10)

  Output:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

Please let me know if this piece of code isn't reflecting the essence of functional programming correctly.


texts:
I'm trying to figure out what to call this sorting algorithm:

function sort(array) {
  array = array.slice();

  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array.length - 1; j++) {
      if (array[j] > array[i]) {
        //swap
        [array[i], array[j]] = [array[j], array[i]]
      }
    }
  }

  return array;
}

console.log(sort([8, 4, 5, 2, 3, 7]));

I wrote it while trying to figure out bubble sort which is a lot different. Tho will have slightly the same running time as the actual bubble sort. I might be wrong :(


texts: AngularJS apply filters on data previously filtered

texts:
I have a $scope.users that I use to show a table and I need to apply a filter with multiple options,

Here is the $scope.users object:

[
  {
    "login": "andres.un1@mail.com",
    "merchant": {
      "merchantId": 500095,
      "status": "ENABLED",
      "defaultAccountId": null,
      "accounts": {
        "500092": "ADMIN",
        "500178": "CONSULT",
        "500180": "ADMIN",
        "500182": "ADMIN",
        "500201": "ADMIN"
      }
    },
    "name": "Carlos"
  },
  {
    "login": "andres.un2@mail.com",
    "merchant": {
      "merchantId": 500095,
      "status": "DISABLED",
      "defaultAccountId": null,
      "accounts": {
        "500092": "CONSULT",
        "500178": "MANAGER",
        "500180": "ADMIN",
        "500182": "ADMIN",
        "500201": "ADMIN"
      }
    },
    "name": "Carlos Andres"
  },
  {
    "login": "cosme.fulanito@mail.com",
    "merchant": {
      "merchantId": 500095,
      "status": "DISABLED",
      "defaultAccountId": null,
      "accounts": {
        "500092": "CONSULT",
        "500178": "MANAGER",
        "500180": "ADMIN",
        "500182": "ADMIN",
        "500201": "ADMIN"
      }
    },
    "name": "Cosme"
  }
]

In the filter I pass other object from the $scope to filter the data, in this case is $scope.searchParams that I previously calculate in a directive.

$scope.searchParams:

{
  "name": [
    "arl"
  ],
  "login": [
    "@"
  ],
  "merchant.status": [
    "ENABLED"
  ],
  "merchant.accounts": [
    "501678",
    "501675",
    "MANAGER",
    "ADMIN"
  ]
}

As you can see, name and login are unique in the filter, but status and account can have multiple values to apply in the filter. Here is my approach to do that but I think is very ineffective, it is important that each filter is applied on the data previously filtered by another filter:

var usrUser = function () {

  var SEPARATOR = '.';

  return function (users, filters) {

    // when the filter is not defined shows all results
    if(filters === undefined || angular.equals({}, filters)){
      return users;
    }

    var matchName = function (element){
      if(element['name'].indexOf(filters['name']) >= 0){
        return element;
      }
    };

    var matchLogin = function (element){
      if(element['login'].indexOf(filters['login']) >= 0){
        return element;
      }
    };

    var matchState = function (element){
      if(filters['merchant.status'].indexOf(element['merchant']['status']) >= 0){
        return element;
      }
    };

    var matchAccount = function (element){
      var match = false;
      angular.forEach(element['merchant']['accounts'], function(profile, accountId){
        if(filters['merchant.accounts'].indexOf(accountId) >= 0 ||
          filters['merchant.accounts'].indexOf(profile) >= 0){
          match = true;
          return;
        }
      });
      if(match){
        return element;
      }
    };

    if(filters['name'] !== undefined){
      users = users.filter(matchName);
    }

    if(filters['login'] !== undefined){
      users = users.filter(matchLogin);
    }

    if(filters['merchant.status'] !== undefined){
      users = users.filter(matchState);
    }

    if(filters['merchant.accounts'] !== undefined){
      users = users.filter(matchAccount);
    }

    return users;
  };
};
//-- register filter
angular.module('users').filter('usrUser', usrUser);

Finally here is how I am using the fiter: <tbody ng-repeat="user in users | secUser:searchParams " class="table-striped">

Is there a better way to implement this filter considering that in the future there can be more filter fields? Also I think is very coupled with the view.


texts:
Given a multi-dimensional array representing a board in Sudoku, the function should be able to return whether the sudoku is valid or not.

Examples:

var goodSudoku = [
  [7,8,4, 1,5,9, 3,2,6],
  [5,3,9, 6,7,2, 8,4,1],
  [6,1,2, 4,3,8, 7,5,9],

  [9,2,8, 7,1,5, 4,6,3],
  [3,5,7, 8,4,6, 1,9,2],
  [4,6,1, 9,2,3, 5,8,7],

  [8,7,6, 3,9,4, 2,1,5],
  [2,4,3, 5,6,1, 9,7,8],
  [1,9,5, 2,8,7, 6,3,4]
];

var badSudoku = [
  [1,1,1, 1,1,1,  2,2,2],
  [5,3,9, 6,7,2, 8,4,1],
  [6,1,2, 4,3,8, 7,5,9],

  [9,2,8, 7,1,5, 4,6,3],
  [3,5,7, 8,4,6, 1,9,2],
  [4,6,1, 9,2,3, 5,8,7],

  [8,7,6, 3,9,4, 2,1,5],
  [2,4,3, 5,6,1, 9,7,8],
  [1,9,5, 2,8,7, 6,3,4]
];

validSudoku(badSudoku); // false;
validSudoku(goodSudoku); // true;

Specific questions

How can I improve my function? What am I doing bad/good?
Is my algorithm efficient? Advice on it?

Here is my code

function validSudoku(data) {
    var valid = true,
        temp = [],
        data,
        side,
        slot;

    // Check wrong size
    if (data[0].length !== data.length) valid = false;

    // slot*slot
    slot = Math.sqrt(data.length);

    // Verifiy horizontal
    data.forEach(function(arr) {
        valid = valid && arr.every(function(val, i) { return arr.indexOf(i + 1) > -1; });
    });

    // Verifiy vertical lines
    data.forEach(function(arr, i) {
        temp  = data.map(function(val) { return val[i]; });
        valid = valid && arr.every(function(val, i) { return temp.indexOf(i + 1) > -1; });
    });

    // Verifiy boxes
    for (var i = 0; i < slot; i++) {

        data.forEach(function(val, e) {
            side  = val.slice(slot * i, slot * i + slot);
            temp  = temp.concat(side);

            if ((e+1) % slot == 0 && e > 0) {
                for (var j = 1; j <= data.length; j++)
                    if (temp.indexOf(j) < 0) valid = false;
                temp = [];
            }

        });

    }
    return valid;
}


texts: Finding the first triangle number with over five hundred divisors

texts:
Project Euler Problem #12:

  The sequence of triangle numbers is generated by adding the natural
  numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7
  = 28. The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

  1: 1
    3: 1,3
    6: 1,2,3,6
   10: 1,2,5,10
   15: 1,3,5,15
   21: 1,3,7,21
   28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have over five
  divisors.

The code runs correctly, but I want to know if I can make any improvements to the code.

#include <iostream>
#include <limits>
#include <cmath>
int highlyDivisibleTriangularNum();

int main() {
std::cout <<highlyDivisibleTriangularNum() << std::endl;
return 0;
}

int highlyDivisibleTriangularNum()
{
//The number to be added to all the previous numbers
int i = 1;
//The number that adds all the previous numbers
int overallAdd = 0;
//Max number
int max = std::numeric_limits<int>::max();
for(int counter = 0; counter < max; counter++)
{
    int total = 0;
    int sum = overallAdd + i;
    i++;
    overallAdd = sum;

    int sqrtSum = (int)sqrt(sum);
    for(int c = 1; c <=sqrtSum;c++)
    {
        if(sum%c == 0)
        {
            total += 2;
        }
        if(total > 500)
        {
            return sum;
        }
    }

}
return 0;
}


texts: Excel Data Manipulation - parse, match and create

texts:
I've got a simple Excel Data Manipulation Script to match one of my daily tasks, written in python 3.
Intro
Let's assume that I have 3 excel files: main.xlsx, 1.xlsx and 2.xlsx. In all of them I have a column named serial numbers. I have to:

lookup for all serial numbers in 1.xlsx and 2.xlsx and verify if they are in main.xlsx.

If a serial number is find:

on the last column of main.xlsx, on the same row with the serial number that was find, write OK + name_of_the_file_in which_it_was_found. Else, write NOK. At the same time, write in 1.xlsx and 2.xlsx ok or nok on the last column if the serial number was found or not.

Now, my script is simply creating new files with the last column appended (instead of appending directly to the same file), which is ok (but if you guys have a better method, shout it). What I'm looking for, is a way of making this as optimized as possible. I'm not looking for PEP8 comments as I'm aware of them, but I'll handle this part when I'll have this as optimized / improved as possible.
Code:
import petl

main = petl.fromxlsx('main.xlsx')
one = petl.fromxlsx('1.xlsx', row_offset=1)
two = petl.fromxlsx('2.xlsx')

non_serial_rows = petl.select(main, lambda rec: rec['serial number'] is None)
serial_rows = petl.select(main, lambda rec: rec['serial number'] is not None)
main_join_one = petl.join(serial_rows, petl.cut(one, ['serial number']), key='serial number')
main_join_one_file = petl.addfield(main_join_one, 'file', 'ok, 1.xlsx')
main_join_two = petl.join(serial_rows, petl.cut(two, ['serial number']), key='serial number')
main_join_two_file = petl.addfield(main_join_two, 'file', 'ok, 2.xlsx')
stacked_joins = petl.stack(main_join_two_file, main_join_one_file)
nok_rows = petl.antijoin(serial_rows, petl.cut(stacked_joins, ['serial number']), key='serial number')
nok_rows = petl.addfield(nok_rows, 'file', 'NOK')
output_main = petl.stack(stacked_joins, non_serial_rows, nok_rows)
main_final = output_main

def main_compare(table):
    non_serial_rows = petl.select(table, lambda rec: rec['serial number'] is None)
    serial_rows = petl.select(table, lambda rec: rec['serial number'] is not None)
    ok_rows = petl.join(serial_rows, petl.cut(main, ['serial number']), key='serial number')
    ok_rows = petl.addfield(ok_rows, 'file', 'OK')
    nok_rows = petl.antijoin(serial_rows, petl.cut(main, ['serial number']), key='serial number')
    nok_rows = petl.addfield(nok_rows, 'file', 'NOK')

    return petl.stack(ok_rows, nok_rows, non_serial_rows)

one_final = main_compare(one)
two_final = main_compare(two)

petl.toxlsx(main_final, 'mainNew.xlsx')
petl.toxlsx(one_final, '1New.xlsx')
petl.toxlsx(two_final, '2New.xlsx')

Sample files, can be downloaded from here. (for those who have time to play a lil' bit with the code).


texts:
I have made this class that runs a query. I want to optimize my code and want to have some expert advice.

Here is the class:

class testClass extends Model
{
    protected $_var1;
    protected $_var2;
    protected $_var3;

    public function __construct($var1,$var2, $var3)
    {
        $this->_var1= $this->$var1;
        $this->_var2= $this->var2;
       $this->_var3= 8;  // i need this 8 if no value is passed

    }

    public function testMethod(){
       $query = "SELECT * from table where id = ".this->_var1." AND name= ".$this->var2." AND x= ".$this->var3;
            return $runQuery($query);
    // $runquery is another method…not in concern here..it returns the results…just take my words :)
    }
}

Usage of class:

  $r= new testClass($var1, $var2, $var3);
            $result = $r->testMethod();

How can I improve this?  Or is this even a good way to do it?


texts: Feedback on Erlang Lists processing function

texts:
I have just started learning erlang...I am just practicing the recursion and all in erlang...I tried to write a few of the list processing functions on my own in erlang...Can someone review the code and give some advice on it...

-module(listma).
-export([duplicates/1,reverse/1])
%% Remove the duplicates in a list

duplicates(List) ->
    duplicates(List,[]).

duplicates([Head|Tail],Newlist) ->
    Insert =
        fun(H,N) ->
            case [H] -- N of
                [] -> N;
                [H] -> [H|N]
            end
        end,
    duplicates(Tail,Insert(Head,Newlist));

duplicates([],Outputlist) ->
    reverse(Outputlist).

%% Reverse a list

reverse(List) ->
    reverse(List,[]).
reverse([Head|Tail],Newlist) ->
    reverse(Tail,[Head|Newlist]);
reverse([],Outputlist) ->
    Outputlist.


texts: Creating charts for my UPS metrics - Part 2

texts:
Following up from my previous question

  Streaming my UPS metrics for graphical viewing in bash

#!/usr/bin/env bash

[ -v METRICS_CHECK ] && set -x

API_URL="https://api.thingspeak.com/update"
UPS_PROPS=("LINEV" "LOADPCT" "TIMELEFT")
API_PARAMS=("api_key==XXXXXXXXXXXXXX")

for index in "${!UPS_PROPS[@]}"
do
    value=$(/sbin/apcaccess -up "${UPS_PROPS[$index]}")
    field=$((index + 1))
    if [ "$field" -eq 2 ]
        then
        # bc required for floating point arithmetic
        value=$(echo "$value * 6" | bc)  # 600 Watt * load percent
    fi
    PARAM=$(printf "field%d==%s" "$field" "$value")
    API_PARAMS+=("${PARAM}")
done

/usr/local/bin/http "$API_URL" ${API_PARAMS[@]}

Updates:

Collects data for different metrics supported by apcaccess
Use a variable check for enabling debug mode
Split parameters sent to API URL into a different array
Move away from curl to use httpie
Custom computation for certain attributes

The shellcheck passes everything except the unquoted ${API_PARAMS[@]} in the last line. I am not sure that httpie would work if I quote that and pass it as a single argument.

Charts for viewing pleasure (last 600 minutes data from the time post was created):

Input line voltage

Load (in wattage) on the UPS

Battery time left for the UPS

Click the images to get live charts.


texts:
I have the following code with switch case statement:

public string IrregularCouponLabel
{
    get
    {
        switch ((ctrl.IrregularCouponFirst ? 10 : 0) + (ctrl.IrregularCouponLast ? 1 : 0))
        {
            case 11: return LocalString.Evaluate("label.Both");
            case 10: return LocalString.Evaluate("label.First");
            case 1: return LocalString.Evaluate("label.Last");
            default: return LocalString.Evaluate("label.None");
        }
    }
}

How should I refactor this code to be more clear and readable or how could I otherwise improve this code snippet?

UPDATE
According to valuable answers
I have updated the code in the following way,

    public string IrregularCouponLabel
    {
        get
        {
            return LocalString.Evaluate("label." + GetIrregularCouponValue());
        }
    }

    private string GetIrregularCouponValue()
    {
        bool first = ctrl.IrregularCouponFirst;
        bool last = ctrl.IrregularCouponLast;
        bool both = first && last;
        return both  ? "Both" :
               first ? "First" :
               last  ? "Last" :
                        "None";

    }

What do you think about this? Is it readable or not?


texts: Textbased User Interface for user and program taking turns

texts:
I wrote this program to model interactions between a user and an artificial player, both playing by the same rules (not enforced here for simplicity).
The game played is here is "your next word has to start with the last letter of mine"

module Main where

import Lib
import System.Random
import System.Exit
import Control.Monad

vocab     = ["alpha","beta","gamma"]
blacklist = []

pick:: [a] -> IO a --picks random element. copy pasted, not understood
pick x = Control.Monad.liftM (x !!) (randomRIO (0, length x - 1))

main :: IO ()
main = do
  userInput <- getLine
  processUser userInput vocab blacklist

processUser :: String -> [String] -> [String] -> IO a
processUser input vocab blacklist = if input == "quit" then exitSuccess
                                    else do
                                          successor <- getNext input vocab (input:blacklist)
                                          processPC successor vocab blacklist

processPC :: Maybe (IO String) -> [String] -> [String] -> IO a
processPC  Nothing      v b = do putStrLn "I give up"
                                 exitSuccess

processPC (Just ioWord) v b = do word <- ioWord
                                 putStrLn word
                                 userInput <- getLine
                                 processUser userInput v (word:b)

getNext:: String -> [String] -> [String] -> IO (Maybe (IO String))
getNext lastWord vocab blacklist  = do let chooseFrom = filter (`notElem` blacklist) vocab
                                       let matches    = filter (\x -> head x == last lastWord) chooseFrom
                                       if null matches then return Nothing
                                       else return (Just (pick matches) )

I am especially interested how to formulate this better structurally-


texts:
I created an OAuth 1.0 signature generator using Ramda based on this.

I'm just getting to grips with it, so was wondering if someone more familiar with Ramda and functional programming would give me review.

const R = require('ramda')
const hmacsha1 = require('hmacsha1');

// For RFC 3986 Compliant URI Encoding.
let encode = R.pipe(
  encodeURIComponent,
  R.replace(/\!/g, '%21'),
  R.replace(/\'/g, '%27'),
  R.replace(/\(/g, '%28'),
  R.replace(/\)/g, '%29'),
  R.replace(/\*/g, '%2A')
);

// Create a random alphanumeric string of a given length.
let nonce = R.pipe(
  R.times(
    R.partial(
      chars => chars[Math.floor(Math.random() * chars.length)],
      [ '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ]
    )
  ),
  R.join('')
);

// Return the current timestamp in seconds
let now = R.pipe(
  Date.now,
  R.flip(R.divide)(1000),
  Math.floor
);

// Sort a list of pairs by the first item then the second.
let sortPairs = R.compose(
  R.sortBy(R.prop(0)),
  R.sortBy(R.prop(1))
);

// Encode a list of pairs.
let encodePairs = R.map(R.map(encode));

// Convert a list of pairs into a query string.
let toParams = R.compose(
  R.join('&'),
  R.map(R.join('='))
);

// Join key items with an ampersand and hash with given data.
let hash = R.pipe(
  R.join('&'),
  R.curry(R.binary(hmacsha1))
);

// Rename an objects keys
let renameKeys = R.curry((keysMap, obj) => {
  return R.reduce((acc, key) => {
    acc[keysMap[key] || key] = obj[key];
    return acc;
  }, {}, R.keys(obj));
});

// Convert arguments object to OAuth object.
let renameOAuthKeys = R.curry(renameKeys)({
  consumerKey: 'oauth_consumer_key',
  signatureMethod: 'oauth_signature_method',
  oauthToken: 'oauth_token',
  version: 'oauth_version',
});

// reverse concat
let fconcat = R.flip(R.concat);

// Prepend the method and url to the base string.
let prependRequest = R.pipe(
  R.adjust(R.toUpper, 0),
  R.adjust(R.compose(fconcat('&'), encode), 1),
  R.join('&'),
  R.concat
)

// Sort and encode the OAuth params.
let encodeParams = R.pipe(
  R.toPairs,
  encodePairs,
  sortPairs,
  toParams,
  encode
);

// Create dynamic OAuth values.
let addDynamicKeys = R.curry(nonceSize => R.merge({
  oauth_nonce: nonce(nonceSize),
  oauth_timestamp: now(),
}));

// Create an OAuth 1.0 signature.
module.exports = ({
  consumerKey,
  consumerSecret,
  oauthToken,
  oauthSecret,
  url,
  params={},
  data={},
  method='POST',
  version='1.0',
  signatureMethod='HMAC-SHA1',
  nonceSize=32
}) => R.pipe(
    R.merge(R.merge(params, data)),
    renameOAuthKeys,
    addDynamicKeys(nonceSize),
    encodeParams,
    prependRequest([method, url]),
    hash([consumerSecret, oauthSecret])
  )({ consumerKey, signatureMethod, oauthToken, version, })

Full Gist is here


texts: Finding matches in Excel files, adding to a Pandas Dataframe

texts:
I have a business requirement where I have to read excel files and match each cell with a given keyword list and find the matches and write it into a dataframe.

I have written the code, but when the excel size is increasing (7 MB - 5 sheets, 30k * 9), the code is taking unusually long time (40 minutes), and I know that it should since I have so many for loops, but is there anyway to optimize it?

I have tried many different ways to optimize the same, but nothing worked out well.

import pandas as pd
import re
import datetime
import numpy as np

raw_details_list = []
# there are around 10 keys and 600 values
keyword_dic = {"it spend": ['IT OpEx', 'OpEx'], "Infra": ["Dell", "Oracle"]}

def pattern(keys):
    return re.compile('|'.join([r'(?<!\w)%s(?!\w)' % re.escape(keys)]), flags=re.I)

# this is reading each cell of the excel and doing a match whether with the keyword_dic
def sheet_handler(path, page_count, row):
    try:
        global keyword_dic
        if isinstance(row, str):
            for category, keywords in keyword_dic.items():
                for keys in keywords:
                    r = pattern(keys)
                    words = r.findall(row)
                    # storing the matches in a list of dictionary
                    for i in words:
                        temp_dic = {"File Path": path, "Total Number of Page(s)/Slide(s)": page_count, "Keyword": keys,
                                    "IT Category":category}
                        raw_details_list.append(temp_dic)
    except Exception as e:
        pass

# reading the excel - all sheets and creating a dataframe
def xlsx_handler(path):
    # reading the excel file
    sheets_dict = pd.read_excel(path, sheet_name=None, header=None)
    sheet_count = len(sheets_dict)
    for name, sheet in sheets_dict.items():
        # removing float type columns
        sheet = sheet.loc[:, sheet.dtypes != np.float64]
        # reading each row, we have keep track of each cell's row and column details
        for index, row in sheet.iterrows():
            for i in range(len(row)):
                try:
                    # if the content is float, we can skip it
                    float(row[i])
                except Exception as e:
                    sheet_handler(path, sheet_count, row[i])

print(datetime.datetime.now())
xlsx_handler(r"D:\Backend Python\test\test.xlsx")
df = pd.DataFrame(raw_details_list)
print(datetime.datetime.now())

Sample data:

1   Oracle  ERP would be good   United states
2   Dell    Laptops UK
3   Vaio    Off-limit   India
4   Oracle 1.2  E-series    Chine

The output for this should somewhat look like this:

File Path   Pages   Keyword IT Category
D://Data    1   Oracle  Infra
D://Data    1   Oracle  Infra
D://Data    1   Dell    Infra


texts: Simplifying conditional statements for transaction code

texts:
I have below code in one function:

public void func()
{
    if (!string.IsNullOrEmpty(customerpay) && !string.IsNullOrEmpty(warrantypay) && !string.IsNullOrEmpty(maintanceplan))
    {
        if (customerpay == "Include" && warrantypay == "Include" && maintanceplan == "Include")
        {
            transactiontype = "," + "[Population].[Transaction Type Code].&[C^W^I]";
        }
        else if (customerpay == "Include" && warrantypay == "Include" && maintanceplan != "Include")
        {
            transactiontype = "," + "[Population].[Transaction Type Code].&[C^W]";
        }
        else if (customerpay == "Include" && warrantypay != "Include" && maintanceplan != "Include")
        {
            transactiontype = "," + "[Population].[Transaction Type Code].&[C]";
        }
        else if (customerpay != "Include" && warrantypay == "Include" && maintanceplan == "Include")
        {
            transactiontype = "," + "[Population].[Transaction Type Code].&[W^I]";
        }
        else if (customerpay != "Include" && warrantypay != "Include" && maintanceplan == "Include")
        {
            transactiontype = "," + "[Population].[Transaction Type Code].&[I]";
        }
        else if (customerpay != "Include" && warrantypay == "Include" && maintanceplan != "Include")
        {
            transactiontype = "," + "[Population].[Transaction Type Code].&[W]";
        }
        else if (customerpay == "Include" && warrantypay != "Include" && maintanceplan == "Include")
        {
            transactiontype = "," + "[Population].[Transaction Type Code].&[C^I]";
        }
    }
}

I need to simplify the above if-else C# code. Is there a way to do this?


texts:
I have been programming for a while, but I've only made games and less serious stuff. I want to get more serious. I would like some feedback on this class that defines a person. Structure, readability, use of static variables, etc. Please point out everything that can be improved.

public class Person {

    private String firstName, lastName, address;
    private int age;
    private boolean hasAddress = false;
    private boolean hasAge = false;
    private static final String NO_ADDRESS = "No address defined";

    //Constructors

    //Minimum information required
    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    //All possible info
    public Person(String firstName, String lastName, int age, String address) {
        this(firstName, lastName);
        this.age = age;
        this.address = address;
        hasAge = true;
        hasAddress = true;
    }

    //No address defined
    public Person(String firstName, String lastName, int age) {
        this(firstName, lastName);
        this.age = age;
        hasAge = true;
    }

    //No age defined
    public Person(String firstName, String lastName, String address) {
        this(firstName, lastName);
        this.address = address;
        hasAddress = true;
    }

    //Methods

    //Get-methods
    public String getName() {
        return firstName + lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public int getAge() {
        if (hasAge)
            return age;
        else
            return 0; //Return 0 if no age is defined
    }

    public String getAddress() {
        if (hasAddress)
            return address;
        else
            return NO_ADDRESS;
    }

    //Set-methods
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}


texts:
I have homework, in which I get number of cases and then four numbers.  Each number tells how many rows there are in each column

For example: 2 2 3 3 should be viewed like this:

    _ _
_ _ _ _
_ _ _ _

Wherever there are lines that can be joined in one, I have to do this, and write out minimum number of lines required to make that kind of sketch.

So the above would be:

  __
____
____

And the correct answer is 3.

A more complicated example:

3 1 2 1

Should be viewed as:

_
_   _
_ _ _ _

Joining the lines:

_
_ _
_____

And the answer is: 4.

Here is the code:

#include <iostream>
using namespace std;

int main()
{
    unsigned long long int stPrimerov = 0;
    cin >> stPrimerov;
    unsigned long long int *totalRows = new unsigned long long int[stPrimerov];

    for (unsigned long long int i = 0; i < stPrimerov; i++)
    {
        //totalRows[i] = 0;
        unsigned long long int a, b, c, d;
        cin >> a >> b >> c >> d;
        /*a = rand() % 100000000;
        b= rand() % 100000000;
        c= rand() % 100000000;
        d = rand() % 100000000;*/

        unsigned long long int temp = 0;
        unsigned long long int array[4] = { a, b, c, d };
        for (int k = 0; k<4; k++)
        {
            if (array[k]>temp)
                temp = array[k];
        }

        //totalRows[i] = 0;
         /*int* aArray = new int[temp];
         int* bArray = new int[temp];
         int* cArray = new int[temp];
         int* dArray = new int[temp];*/
        unsigned long long int ttr = 0;
        for (unsigned long long int l = 0; l< temp; l++)
        {
            int aa, bb, cc, dd;
            if (l < a) aa = 1;
            else aa = 0;
            if (l < b) bb = 1;
            else bb = 0;
            if (l < c) cc = 1;
            else cc = 0;
            if (l < d)dd = 1;
            else dd = 0;

            if (aa == 0 && bb == 0 && cc == 0 && dd == 0) {continue; }
            else if (aa == 0 && bb == 1 && cc == 0 && dd == 1) { ttr += 2; continue; }

            else if (aa == 1 && bb == 0 && cc == 0 && dd == 1) { ttr += 2; continue; }
            else if (aa == 1 && bb == 0 && cc == 1 && dd == 0) { ttr += 2; continue; }
            else if (aa == 1 && bb == 0 && cc == 1 && dd == 1) { ttr += 2; continue; }

            else if (aa == 1 && bb == 1 && cc == 0 && dd == 1) { ttr += 2; continue; }
            else{ ttr+= 1; continue; }

        }
        totalRows[i] = ttr;

    }

    for (unsigned long long int a = 0; a < stPrimerov; a++)printf("%d\n",totalRows[a]);
    //system("pause");
    return 0;
}

I have to make it faster.

Example input:

3
2 1 6 4
0 1 1 1
3 9 8 11

Result:

7
1
12

Number of cases can be up to 104 and number of rows up to 108.


texts: Slow data-processing and inefficient memory usage in .NET containers

texts:
I am writing a text classifier, and in order to do so, I need TF/IDF values per every word of my single text.

Then I need to use the cosine similarity:

$$similarity = cos(\theta) = \dfrac{A \cdot B}{\lVert A \lVert \lVert B \lVert} = \dfrac{\overset{n}{\underset{i=1}{\LARGE\Sigma}}A_i \times B_i}{\sqrt{ \overset{n}{\underset{i=1}{\LARGE\Sigma}}(A_i)^2} \times \sqrt{\overset{n}{\underset{i=1}{\LARGE\Sigma}}(B_i)^2}}$$

This requires processing of a big data storage (all of the texts that already exists in my database). The problem is that my code is doing his job for about 2 hours (quite too long) and breaks giving me message that I have run out of memory. I think that the main method might be very, very unoptimised.

public static void CreateCategoryClasses()
{
    deserializeClasses = Deserialize();
    howManyClasses = deserializeClasses.Count;
    ewhClass = new EventWaitHandle[howManyClasses];

    for (var i = 0; i < 5; ++i)
    {
        categoryClasses.Enqueue(new ConcurrentDictionary<string, double>());
        result.Enqueue(new ConcurrentDictionary<string, double>());
    }
    WaitCallback threadMethod = ParseCategories;
    ThreadPool.SetMaxThreads(howManyStudents, howManyClasses);

    for (var i = 0; i < howManyClasses; ++i)
    {
        ewhClass[i] = new EventWaitHandle(false, EventResetMode.AutoReset);
        ThreadPool.QueueUserWorkItem(threadMethod, i);
    }
    for (var i = 0; i < howManyClasses; ++i)
    {
        ewhClass[i].WaitOne();
    }
    threadMethod = AddIDF;
    ThreadPool.SetMaxThreads(howManyStudents, 5);

    for (var i = 0; i < 5; ++i)
    {
        ewhClass[i] = new EventWaitHandle(false, EventResetMode.AutoReset);
        ThreadPool.QueueUserWorkItem(threadMethod, i);
    }
    for (var i = 0; i < 5; ++i)
    {
        ewhClass[i].WaitOne();
    }

    List<List<SingleWords>> efekt = new List<List<SingleWords>>(5);

    for (int i = 0; i < 5; ++i)
    {
        foreach (var secondWord in categoryClasses.ToList()[i])
        {
            result[i].Add(new SingleWords(secondWord.Key, secondWord.Value));
        }
    }
    var xmls = new XmlSerializer(typeof(List<List<SingleWords>>));
    using (var sw = new StreamWriter(@"categoryClasses.xml"))
    {
        xmls.Serialize(sw, efekt);
    }
}

private static void AddIDF(object index)
{
    Console.WriteLine("Thread started with id:" + index + " and number: " + Thread.CurrentThread.ManagedThreadId);
    var i = index as int?;
    double sum;
    foreach (var word in categoryClasses.ElementAt(i.Value))
    {
        sum =
            deserializeClasses.Count(
                clas =>
                    clas.Bag.Where(x => clas.Category == ((Categories)i.Value).ToString())
                        .Contains(new Words(word.Key, 0, 0)));
        var temp = Convert.ToDouble(sum) /
                   Convert.ToDouble(
                       deserializeClasses.Count(x => x.Category == ((Categories)i.Value).ToString()));
        result.ElementAt(i.Value).AddOrUpdate(word.Key, temp, (s, d) => temp);
    }
    ewhClass[(i).Value].Set();
    Console.WriteLine("Thread ended with id:" + index + " and number: " + Thread.CurrentThread.ManagedThreadId);
}


texts: Implement PageObjects using TestNg in selenium

texts:
I am trying to implement page objects with Page factory using TestNg and selenium. Please advice improvements in it.

Classes:

LoginPageObjects extends LoginPageLocators {
   private WebDriver driver;

   public LoginPageObjects(WebDriver driver)
   this.driver=driver;

   public HomePageObjects loginFunction(){
      // some code here
      return PageFactory.initElements(HomePageObjects.class);
   }
}

HomePageObjects extends HomePageLocators{
   private WebDriver driver;

   public HomePageObjects(WebDriver driver)
   this.driver=driver;

   public void verifyTitle(){
       // some code here
   }
}

public class LoginPageTest{

   LoginPageObjects loginPage=new LoginPageObjects();

   public void LoginPageTest(){
      HomePageObjects homepage=loginPage.loginFunction();
      Assert.assertTrue("HomePageTitle",homepage.verifyTitle());
   }
}

TestNGTests.class

public void firstTest() {
   LoginPageTest test=new LoginPageTest();
   test.loginPageTest;
   //other test code
}

`Testng.xml` calls the `TestngTests.class`
`Locators` class contains the `PageFactory` objects


texts: Circular dependencies between immutable objects; the Freeze Pattern

texts:
Generally, I structure small threadsafe immutable objects like this:

public class SmallObject {
    private final String state;
    public SmallObject(final String state) {
        this.state = state;
    }

    // ...
}

And then wire these up in Spring like this:

<bean name="SmallObjectForThisThing" class="my.package.SmallObject">
    <constructor-arg name="state" value="in practice this is usually a ref"/>
</bean>

However, this leads to complications with circular dependencies.  To keep the immutability when this happens, I use a "freeze" pattern, where the variables are set once.  This is what I want reviewed:

public class SmallObject {
    private String state = null;

    public void setState(String state) {
        if (this.state != null) {
            throw new IllegalStateException("state already set: '" + state + "'.");
        }
        this.state = state;
    }

    private void ensureInitialized() {
        if (this.state == null) {
            throw new IllegalStateException(
                "state must be set before this instance is used."
            );
        }
    }

    // ... For every additional method on the object, I call
    // ensureInitialized() first.
}

And then wire them up like this:

<bean name="SmallObjectForThisThing" class="my.package.SmallObject">
    <property name="state" value="in practice this is usually a ref"/>
</bean>


texts: Better way for securing direct access to php files

texts:
I don't know if this method uses a lot of time to process, or if it is bad but I wanted to know if there is any better way of actually doing this? I have a few class files that I want to stop users viewing through the browser, and only allowing them to view it if actually load it from the index.php

So I have this nice little piece of code.

In my index.php I have:

define("SECURE", true);

And I check if it has been defined in class files using

defined("SECURE") or exit('Please define variable SECURE to continue.');

So when they visit class files it actually blocks them from viewing it unless they have loaded index.php first.

Any better way?


texts:
This is just a little palindromic game that searches all palindromic numbers in ur random generated list. Feel free to give me some advice.

import random

numbers = []
total = []
dice = random.randint(1000, 50000)

while len(numbers) < dice:
        x = random.randint(100000, 1000000)
        numbers.append(x)

def palindrome(n):
    check_palin = []
    for i in n[::-1]:
        i = str(i)
        check_palin.append(i)
        for k in check_palin:
            k = k[::-1]
            check_palin.clear()
            if k == i:
                total.append(k)
    print(total)
    numbers.clear()

palindrome(numbers)

length = len(total)

if length > 58:
    print("\nHolly Shit!!! You broke my record!!! with %d." % (length))

elif length == 58:
    print("\nWow, Nice!!! %d is my highest Palindromic number (too).\nThat's a draw" % (length))


texts:
I'm very very fresh to programming. This is one of my first experiments with Python and I'm wondering in what ways I could have made this program less clunky. Specifically, is there a way that I could have used classes instead of defining my x, y, and z variables globally?

def getx():
    try:
        global x
        x = float(raw_input("Please give your weight (pounds): "))
        return x
    except ValueError:
        print("Use a number, silly!")
        getx()
def gety():
    try:
        global y
        y = float(raw_input("what is your current body fat percentage? (>1): "))
        return y
    except ValueError:
        print("Use a number, silly!")
        gety()
def getz():
    try:
        global z
        z = float(raw_input("What is your desired body fat percentage? (>1): "))
        return z
    except ValueError:
        print("Use a number, silly!")
        getz()
def output():
    getx()
    gety()
    getz()
    A = (x*(y/100-z/100))/(1-z/100)
    B = x - A
    print("Your necessary weight loss is %.1f pounds, and \
your final weight will be %.1f pounds" % (A,B))
    more()
def more():
    again = raw_input("Calculate again? ")
    if again.lower() == "yes" or \
       again.lower() == "y" or \
       again.lower() == "sure" or \
       again.lower() == "ok" or \
       again.lower() == "" or \
       again.lower() == "okay":
        output()
    elif again.lower() == "no" or \
         again.lower() == "n" or \
         again.lower() == "nah" or \
         again.lower() == "nope":
            end()
    else:
        more()
def end():
    print("Ok, see ya later!")
output()


texts:
I'm a beginner programmer and decided to try some coding challenges. I found CodeEval and attempted the first challenge, FizzBuzz. However upon submitting my code I found that my submission only partially solved the problem.

Link to the challenge

  Challenge Description:

  Players generally sit in a circle. The first player says the number
  “1”, and each player says next number in turn. However, any number
  divisible by X (for example, three) is replaced by the word fizz, and
  any divisible by Y (for example, five) by the word buzz. Numbers
  divisible by both become fizz buzz. A player who hesitates, or makes a
  mistake is eliminated from the game.

  Write a program that prints out the final series of numbers where
  those divisible by X, Y and both are replaced by “F” for fizz, “B” for
  buzz and “FB” for fizz buzz.

  Input Sample:

  Your program should accept a file as its first argument. The file
  contains multiple separated lines; each line contains 3 numbers that
  are space delimited. The first number is the first divider (X), the
  second number is the second divider (Y), and the third number is how
  far you should count (N). You may assume that the input file is
  formatted correctly and the numbers are valid positive integers.

  For Example:

  1) 3 5 10

  2) 2 7 15

  Output Sample:

  Print out the series 1 through N replacing numbers divisible by X with
  “F”, numbers divisible by Y with “B” and numbers divisible by both
  with “FB”. Since the input file contains multiple sets of values, your
  output should print out one line per set. Ensure that there are no
  trailing empty spaces in each line you print.

  1) 1 2 F 4 B F 7 8 F B

  2) 1 F 3 F 5 F B F 9 F 11 F 13 FB 15

How can I improve my code speed-wise and memory-wise so that I can fully complete this challenge?

The code is working for my test cases.

import sys

def main(name_file):
    _test_cases = open(name_file, 'r')
    for test in _test_cases:
        result = ""
        if len(test) == 0:
            break
        else:
            test = test.split()
            first_div = int(test[0])
            second_div = int(test[1])
            lim = int(test[2])
            for i in range(1, lim+1):
                if i % (first_div*second_div) == 0:
                    result += "FB "
                elif i % first_div == 0:
                    result += "F "
                elif i % second_div == 0:
                    result += "B "
                else:
                    result += "%d " % i
            print(result[:-1])

    _test_cases.close()
if __name__ == '__main__':
    main(sys.argv[1])


texts: Sum-based sliding rate limiting with Redis and Lua

texts:
As I'm new to Redis, I would like to get a review / improvement suggestions from Redis / Lua experts on the following problem and the solution I have found so far.

Problem

The context is: an e-commerce system used by multiple users purchasing various items at different prices. Because of regulation, user purchases must be capped to a certain amount during a certain sliding period.

For example, no more than 10€ can be spent by a purchasing user during a sliding window of 1 week.

The problem to solve is: using StackExchange.Redis (Redis client .NET library) and Redis v3, implement a sliding window rate limiting mechanism, based not on max count of requests (many solutions for this particular problem can be found on web), but on a total sum of purchases done during a sliding period.

Solution design

A single purchase is represented by a purchase ID. It is stored as a string data type with the associated purchase amount (2.5 in the example below). Because we don't need to keep it forever, we'll expire it after 1 week (604800 seconds).

SETEX purchaseid:98db31bf9b 604800 2.5

Users and their corresponding purchases are represented by a sorted list where the key is the user ID, scores are numbers of seconds since 1970 (Epoch time), and values are purchase IDs. Likewise, the expiration is one week (renewed with each new purchase):

ZADD userid:hello@example.com 1443719939 purchaseid:98db31bf9b
EXPIRE userid:hello@example.com 604800

Fig1.: Data model (example)

Because several Redis calls might be required to implement this, I used a pre-loaded Lua script (using EVALSHA) in order to execute several Redis commands in one shot, so to avoid race conditions and to reduce network exchanges (please correct me if I'm wrong here).

Every time a user tries to purchase something, this script is called by the client application, and returns 1 if the purchase is accepted and registered, 0 otherwise.

However, I'm not sure how this approach will work in the context of a Redis Cluster. Will the data created through the Lua script be auto-partitioned over multiple masters? If yes, will the Lua script be able to read it back?

Solution code (Lua)

--[[
Initialization: StackExchange.Redis library allows passing
named parameters tagged with @
--]]
local userKey = 'userid:' .. @curUserId
local curPurchaseKey = 'purchaseid:' .. @curPurchaseId
local sum = 0
--[[
Cleaning up old entries up to @minSecond (in our example,
minSecond = Now (Epoch time in secs) - 604800 (nb of secs in a week)):
--]]
redis.call('ZREMRANGEBYSCORE', userKey, '-inf', @minSecond)

--[[
Getting the list of purchases done by user since @minSecond,
summing them up, returning 0 (failed) if @maxAmount is reached (e.g., 10€):
--]]
local pastEntries = redis.call('ZRANGEBYSCORE', userKey, @minSecond, '+inf')
for i = 1, #pastEntries, 1 do
    local purchaseKey = pastEntries[i]
    local amount = tonumber(redis.call('GET', purchaseKey) or 0)
    sum = sum + amount
end

if sum >= tonumber(@maxAmount) then
    return 0
end

--[[
Saving the current purchase ID + amount (e.g., 2.5€),
updating the sorted list of the user's purchases,
returning 1 (success):
--]]
redis.call('SETEX', curPurchaseKey, @expInSec, @curAmount)
redis.call('ZADD', userKey, @curSecond, curPurchaseKey)
redis.call('EXPIRE', userKey, @expInSec)
return 1


texts: My First React JS Portfolio Web App : A Restaurant Website

texts:
I have written my first react js web app. It is a portfolio project which is a restaurant website. I have used firebase to authenticate users and to host my website. I am asking the Code Review community to kindly review my code if there are scopes for improving and refactoring the code.
And I faced three problems while writing the app. The first problem is I am getting unused variables when using a context. Is there a better way to consume a context than below :
const [loggedInUser, setLoggedInUser] = useContext(UserContext)
And I am proving the values as below :

<UserContext.Provider value={[loggedInUser, setLoggedInUser]}>

All content goes here

 </UserContext.Provider>

And the second problem I faced is, I think, a lag between two computations. I have some protected routes, and I have set some Link elements that will redirect to the Login page if a user hasn't logged in. The problem is that when a user clicks on a link, he gets redirected to the login page even if he has logged in. I have set another redirection to redirect logged-in users to the profile page from the login page. So just in a second, the wrongly logged-in user is being redirected to the profile page. I think it can be solved using async/await. But how can I do this?
The third React Router Link element inside a Router element isn't working. The URL is changing on the address bar but the content isn't changing.
Here is my repository link and the live website link.


texts: C++ - printing a binary tree vertically, Depth first

texts:
eg:
   5
  / \
 3   4
/\   /\
7 8  9 1

should print: 5 3 7 8 4 9 1

#include <iostream>
include <stack>
using namespace std;`

class node{
public:
int val;
node* left;
node* right;
bool istraversed=false;
};

void printdfs(node* root){
stack<node*> s;
s.push(root);

while(!s.empty()){

    node *temp = s.top();
    if(temp->istraversed==false){
        cout<<temp->val<<" ";
        temp->istraversed=true;
    }
    if(temp->left!=NULL){
        if(temp->left->istraversed==false){
            s.push(temp->left);
            continue;
        }
    }
    if(temp->right!=NULL){
        if(temp->right->istraversed==false){
            s.push(temp->right);
            continue;
        }
    }
    s.pop();
}
}

int main() {

node* root;
root->val=1;
cout<<root->val<<",";

root->left->val = 2;
cout<<root->left->val<<",";
root->right->val = 3;
cout<<root->right->val<<",";

root->left->left->val=4;
cout<<root->left->left->val<<",";
root->left->right->val=5;
cout<<root->left->right->val<<",";
root->right->left->val=6;
root->right->right->val=7;
root->left->left->left->val=8;

printdfs(root);

return 0;

}


texts:
After some advice, which method do you think is better to use when searching a dictionary for the matching value(s)?

Method One

Console.WriteLine("ENTER A PERSON/NUMBER TO SEARCH FOR");
string input = Console.ReadLine().ToUpper();
bool found = false;

if (myPhoneBook.ContainsKey(input)) // used with a persons name and returns number
{
    Console.WriteLine(myPhoneBook[input]);
    found = true;
}
if (!(myPhoneBook.ContainsKey(input))) //searches the number and returns the name
{
    var searchingfornumbers = from num in myPhoneBook
                              where num.Value == input
                              select num.Key;

    foreach(var person in searchingfornumbers)
    {
        Console.WriteLine(person);
        found = true;
    }
}
if(found == false)
{
    Console.WriteLine("NO RECORD FOUND");
}

Method Two

Console.WriteLine("ENTER A PERSON/NUMBER TO SEARCH FOR");
string input = Console.ReadLine();
bool found = false;
var query0 = from person in myPhonebook //searches for the number, returns name
             where person.Value == input
             select person.Key;

foreach(var person in query0)
{
    Console.WriteLine(person);
    found = true;
}

var query1 = from person in myPhonebook //searches for the name, returns numbers
             where person.Key == input
             select person.Value;

foreach (var person in query1)
{
    Console.WriteLine(person);
    found = true;
}
if(found == false)
{
    Console.WriteLine("NO RECORD FOUND");
}
Console.ReadKey();


texts: Prove that the graph is a valid tree in Python

texts:
I recently solved this leetcode problem:

  Given n nodes labeled from 0 to n - 1 and a list of undirected edges
  (each edge is a pair of nodes), write a function to check whether
  these edges make up a valid tree.

For example:

Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.

  Note: you can assume that no duplicate edges will appear in edges.
  Since all edges are undirected, [0, 1] is the same as [1, 0] and thus
  will not appear together in edges.

My code is correct, and runtime beats 80% of answers submitted, but the overall structure is not at all user friendly. Could anyone give some code review to improve readability?

Don't worry what alternative method or improving the solution since it is already in \$O(n)\$.

from collections import defaultdict

class Solution(object):
    def validTree(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: bool
        """
        if not edges:
            if n == 1:
                return True
            elif n == 2:
                return False

        visited_nodes = defaultdict(list)
        count = True
        unvisited = []
        for key, value in edges:

            if key in visited_nodes and value in visited_nodes:
                return False

            if count:
                visited_nodes[key] = []
                visited_nodes[value] = []
                count = False
                continue
            if key in visited_nodes:
                visited_nodes[key].append(value)
                visited_nodes[value] = []
            elif value in visited_nodes:
                visited_nodes[value].append(key)
                visited_nodes[key] = []
            else:
                unvisited.append([key, value])

        for key, value in unvisited:

            if key in visited_nodes and value in visited_nodes:
                return False

            if key in visited_nodes:
                visited_nodes[key].append(value)
                visited_nodes[value] = []
            elif value in visited_nodes:
                visited_nodes[value].append(key)
                visited_nodes[key] = []
            else:
                return False

        return n == len(visited_nodes.keys())

print Solution().validTree(4, [[0, 1], [2, 3], [1, 2]])


texts:
I'm new to Python and experimenting with some simple scripts. I would appreciate if you could give me some suggestions on how the following code can be improved or made simpler or anything in general.

#Coverts MAC Addresses into cisco format

def mac_conv(mac, sep='-'):
  #split mac address into 3 groups
  splitted_mac = mac.split(sep)
  gr1 = ''.join(splitted_mac[0:2])
  gr2 = ''.join(splitted_mac[2:4])
  gr3 = ''.join(splitted_mac[4:])

  #join groups into a single MAC
  mac = gr1, gr2, gr3
  final_mac = '.'.join(mac)

  #print final MAC address
  print(final_mac)

#Open file with MAC addresses and convert them
with open('mac.txt', 'r') as f:
  for mac in f.readlines():
    mac_conv(mac)


texts:
We have some code to populate a CMFCPropertyGridCtrl grid with controls that is based on copied samples. We are currently using Visual Studio 2012 but intend to upgrade to VS2015 soon. A typical excerpt is:

void CPropGridProps::AddPropertiesJoint(const bool bIsDataEditable, const CJointDefault& ent)
{
    CMFCPropertyGridProperty* pProp;
    {   // entity
        std::auto_ptr<CMFCPropertyGridProperty> apEnt(new CMFCPropertyGridProperty(_T("Joint")));
        {   // master
            pProp = new CMFCPropertyGridProperty(_T("Master node"), (_variant_t) (long) ent.Master, _T("Joint master node"), JOINT_MASTER);
            pProp->AllowEdit(bIsDataEditable);      pProp->Enable(bIsDataEditable);
            apEnt->AddSubItem(pProp);
        }
        {   // direction
            CString csDir[6] = { L"x",L"y",L"z",L"xx",L"yy",L"zz" };
            for (int j=0; j<6; ++j)
            {
                CMFCPropertyGridProperty* pBoolProp = new CMFCPropertyGridProperty(_T("Direction " + csDir[j]), COleVariant(), _T("Joint direction " + csDir[j]), JOINT_DIRECTION_X + j);
                pBoolProp->AllowEdit(bIsDataEditable);  pBoolProp->Enable(bIsDataEditable);
                apEnt->AddSubItem(pBoolProp);
            }
        }
        m_pPropGrid->AddProperty(apEnt.release(), FALSE, FALSE);
    }
}

The routines AddProperty and AddSubItem, which both take ownership of the pointers, take either auto_ptr or simple pointers.
The smart pointers are auto_ptr where unique_ptr may be better.
There is an awkward double cast (_variant_t) (long).
The code makes no checks for AddProperty and AddSubItem failing, not even a call of VERIFY().


texts: Generating probability table of 2-character combinations from text file in Java

texts:
I have written a probability table generator in Java to help me generate randomized girl's names for the game I am making.
It reads from a text file and creates a HashMap<String, Double> full of two-character combinations and their rate of incidence.
I don't have a lot of experience with either probability tables or Java in general.
I would like help making it run faster
Example text from input file:
Each line has ten names. The real text file has 462 lines, and 4620 names.

Marva Kandy Debbi Louisa Edris Orpha Lynn Louise Reyna Jacki Evangeline
Ray Sienna Alecia Elin Debby Noreen Alishia Michael Evangelina Eliz
Usha Ladawn Dominga Cynthia Marty Shayla Sanora Betsey Ira Jodee
Qiana Elia Elke Torie Amirah Marta Lavonna Ozie Lavonne Teofila
Latoria Catharine Epifania Susy Keli Delpha Isa Marth Rosina Marti
Jordan Ella Theda Tyesha Rana Francesca Shayna Letha Shayne Marry
Rea Joellen Fidela Kandi Celeste Salina Kamryn Jenelle Celena Celesta
Kenyatta Ada Shelia Maribel Edith Lorilee Jazmyn Myrtice Kena Laurence

My code
public class MCVE {

    public static void main(String[] args) throws Exception {
        // create the file-path
        String address = "./res/text_files/Human_FirstNames";
        // will hold letter combinations and their frequency
        HashMap<String, Double> frequencies = new HashMap<>();

        FileReader fr = new FileReader(address);
        BufferedReader br = new BufferedReader(fr);

        // Iterate through file
        // get rid of new-line characters and concat to wholeString
        String aLine = "";
        String wholeString = "";
        while((aLine = br.readLine()) != null) {
            wholeString += aLine.replaceAll(System.lineSeparator(), " ");
        }

        // convert names to lowercase and into char[]
        char[] charArr = wholeString.toLowerCase().toCharArray();

        // iterate through char[] charArr and
        // add the number of times each character-combination is shown
        // to the value for each character-combination key.
        int length = charArr.length;
        String tempString = "";
        for(int i = 0; i < length; i++) {

            if(i + 1 == length)
                break;

            if(charArr[i] != ' ' && charArr[i + 1] != ' ') {
                tempString = Character.toString(charArr[i]) + Character.toString(charArr[i + 1]);
                if (frequencies.containsKey(tempString))
                    frequencies.replace(tempString, frequencies.get(tempString) + 1.0);
                else // if it doesn't contain this key yet, create it
                    frequencies.put(tempString, 1.0);
            }
        }

        // iterate through HashMap frequencies and
        // replace the values with the product of
        // (original_value / size_of_HashMap)
        double mapLength = frequencies.size();
        Iterator iter = frequencies.entrySet().iterator();
        while(iter.hasNext()) {
            HashMap.Entry pair = (HashMap.Entry)iter.next();

            frequencies.replace((String) pair.getKey(), (Double) pair.getValue() / mapLength);

            System.out.println(pair.getKey() + " " + pair.getValue());
            iter.remove();
        }
    }
}


texts: LINQ to Entities query with lots of grouping

texts:
I have been presented with a simple but slow performing LINQ to Entities query which I've pasted below.

Could anybody give me some pointers on how to improve performance?  The query below has been significantly improved since I inherited it but I don't know what else I can do without moving to the DB (which isn't an option at this stage)

var created = DateTime.Now.AddMonths(-6);

            return (from t1 in db.Opportunities
                    from s1 in db.OpportunityStatus.Where(x => x.OpportunityStatus_ID == t1.StatusReason_ID)
                    from t2 in db.Leads.Where(x => x.Lead_ID == t1.Lead_ID)
                    from t3 in db.Tasks.Where(x => (x.Type_ID == 4) && (x.Item_ID == t1.Opportunity_ID)).DefaultIfEmpty()
                    from t4 in db.TaskAppointments.Where(x => x.Parent_Task_ID == t3.Task_ID).DefaultIfEmpty()
                    from t5 in db.Addresses.Where(x => x.Address_ID == t4.Address_ID).DefaultIfEmpty()
                    from n1 in db.Notes.Where(x => x.Type_ID == 4 && (x.Item_ID == t1.Opportunity_ID)).DefaultIfEmpty()
                    from n2 in db.Notes.Where(x => x.Type_ID == 5 && (x.Item_ID == t1.Lead_ID)).DefaultIfEmpty()
                    from t6 in db.Quotations.Where(x => x.OpportunityId == t1.Opportunity_ID).DefaultIfEmpty()
                    from u1 in db.UserNames.Where(x => x.User_Username == t1.Owner).DefaultIfEmpty()
                    from u2 in db.UserNames.Where(x => x.User_Username == t2.Owner).DefaultIfEmpty()

                    where (t1.Company_ID == company) && (t1.Created >= created)

                    orderby (t1.Created) descending

                    group new { t1, t3, t4, s1, t6, u1, u2, n1, n2, t5 } by new
                    {
                        t1.Opportunity_Title,
                        t2.Company_Name,
                        s1.OpportunityStatus_Name,
                        ts = u1.Name,
                        fs = u2.Name
                    } into g

                    let latestAppointment = g.Max(uh => uh.t4.AppointmentStart)
                    let latestAppointmentStatus = g.FirstOrDefault(x => x.t4.AppointmentStart == latestAppointment).t4.AppointmentStatu.Status_Name
                    let latestAppointmentCity = g.FirstOrDefault(x => x.t4.AppointmentStart == latestAppointment).t5.City

                    let latestNoteDate = g.Max(uh => uh.n2.Date)
                    let latestNote = g.FirstOrDefault(x => x.n2.Date == latestNoteDate).n2.Note_Text

                    let latestOpportunityNoteDate = g.Max(uh => uh.n1.Date)
                    let latestQuotationDate = g.Max(uh => uh.t6.Created)

                    select new PipelineViewModel
                    {
                        Id = 0,
                        CompanyName = g.Key.Company_Name,
                        OpportunityTitle = g.Key.Opportunity_Title,
                        CompanyCity = latestAppointmentCity,
                        OpportunityStatusName = g.Key.OpportunityStatus_Name,
                        LastAppointmentDate = latestAppointment,
                        LastAppointmentStatus = latestAppointmentStatus,
                        LastOpportunityNoteDate = latestOpportunityNoteDate,
                        LastNoteDate = latestNoteDate,
                        LastNote = latestNote,
                        LastQuoteDate = latestQuotationDate,
                        TelesalesUserName = g.Key.ts,
                        FieldSalesUserName = g.Key.fs
                    }).Take(howMany);


texts: Decorator pattern with a builder in a booking application

texts:
I'm working on a booking application and am in the process of porting some legacy code to a more SOLID and testable architecture. Right now I'm working on the process of canceling bookings. Over the years, we have changed the steps involved here. The core has been the same (update booking entity status, make the timeslot open again, etc), but we've been adding and removing some other steps, and we do some steps depending on where the cancellation is made from (support UI, customer UI etc).

My current solution involves the decorator pattern for dynamically adding extra steps to the cancellation process. In order to hide the concrete classes responsible for those steps, as well as the fact that this pattern is used at all from client code, I've wrapped this up in a builder. I now wonder if there are some pitfalls I should look out for here.

public class OrderCancellationProcessBuilder
{
    private readonly ITimeProvider _timeProvider;
    private IOrderProcessor _cancellationProcessor;

    public OrderCancellationProcessBuilder(ITimeProvider timeProvider, string cancelationMessage)
    {
        _timeProvider = timeProvider;
        _cancellationProcessor = new CancelBookingsAndRevokePayments(cancelationMessage);
    }

    public IOrderProcessor Build()
    {
        return _cancellationProcessor;
    }

    public OrderCancellationProcessBuilder SendConfirmationEmails(IConfirmationEmailSender emailSender)
    {
        _cancellationProcessor = new SendConfirmationEmails(
            _cancellationProcessor,
            emailSender,
            _timeProvider);
        return this;
    }

    public OrderCancellationProcessBuilder RemovePendingMessages(IPendingMessagesService pendingMessagesService)
    {
        _cancellationProcessor = new RemovePendingMessages(_cancellationProcessor, pendingMessagesService);
        return this;
    }
}

The order processor can later on be consumed by the client code by something like someOrder.Accept(cancellationProcessor);. SendConfirmationEmails and others are the decorators for the order processor. The decoration steps are being hidden behind the builder pattern in a 1:1 way (although this could of course change).

If I were to voice any concern I might have at this stage, it is that it might be overly complicated. But then again, I think this way of thinking might come partly from the fact that the current code LOOKS pretty simple until you look into things and realize how much global state and newing of dependencies there are. If this looks complicated, it might just be because it IS complicated, and this pattern just makes it more visible.

I really think something like this solution could work to make it a lot easier to add/remove steps without breaking existing code, but I wonder if there's a simpler way


texts: Modeling a Triangle, with a utility method to classify it

texts:
Inspired by this question, I played a bit with the idea of modeling a Triangle, and a utility method to classify it:

class Triangle {

    private final int a;
    private final int b;
    private final int c;

    enum Type {
        EQUILATERAL, INVALID, ISOSCELES, SCALENE
    }

    public Triangle(int a, int b, int c) {
        if (!isSaneArguments(a, b, c)) {
            throw new IllegalArgumentException("All sides of a Triangle must be > 0");
        }
        if (!isTriangle(a, b, c)) {
            throw new IllegalArgumentException("Not a triangle: no side must be longer than the sum of the other sides");
        }
        this.a = a;
        this.b = b;
        this.c = c;
    }

    private static boolean isSaneArguments(int a, int b, int c) {
        return a > 0 && b > 0 && c > 0;
    }

    private static boolean isTriangle(int a, int b, int c) {
        return a < b + c && b < a + c && c < a + b;
    }

    public static Type classifyValidTriangle(int a, int b, int c) {
        final Type type;
        if (a == b && b == c) {
            type = Type.EQUILATERAL;
        } else if (b == c || a == b || c == a) {
            type = Type.ISOSCELES;
        } else {
            type = Type.SCALENE;
        }
        return type;
    }

    public static Type classify(int a, int b, int c) {
        if (!isSaneArguments(a, b, c) || !isTriangle(a, b, c)) {
            return Type.INVALID;
        }
        return classifyValidTriangle(a, b, c);
    }

    public Type classify() {
        return classifyValidTriangle(a, b, c);
    }
}

Unit tests:

public class TriangleTest {
    @Test(expected = IllegalArgumentException.class)
    public void testInvalidTriangleWithTooLongSide() {
        int a = 1;
        int b = a + 1;
        new Triangle(a, b, a + b + 1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testInvalidTriangleWithNegativeSide() {
        new Triangle(1, 2, 0);
    }

    @Test
    public void testScalene() {
        assertEquals(Triangle.Type.SCALENE, new Triangle(2, 3, 4).classify());
        assertEquals(Triangle.Type.SCALENE, Triangle.classify(2, 3, 4));
    }

    @Test
    public void testEquilateral() {
        assertEquals(Triangle.Type.EQUILATERAL, new Triangle(3, 3, 3).classify());
        assertEquals(Triangle.Type.EQUILATERAL, new Triangle(2, 2, 2).classify());
        assertEquals(Triangle.Type.EQUILATERAL, Triangle.classify(5, 5, 5));
    }

    @Test
    public void testIsosceles() {
        assertEquals(Triangle.Type.ISOSCELES, new Triangle(3, 3, 2).classify());
        assertEquals(Triangle.Type.ISOSCELES, new Triangle(3, 2, 3).classify());
        assertEquals(Triangle.Type.ISOSCELES, new Triangle(2, 3, 3).classify());
        assertEquals(Triangle.Type.ISOSCELES, Triangle.classify(2, 3, 3));
        assertEquals(Triangle.Type.ISOSCELES, Triangle.classify(3, 3, 2));
        assertEquals(Triangle.Type.ISOSCELES, Triangle.classify(3, 2, 3));
    }
}

What do you think? What would you do differently? How can it be better?


texts: Calculate the percentage of sum of hash values

texts:
Please review my code and help on How can I make it better calculation in method and class definition with SOLID ruby principles??

The application has a static JSON file which contains:

{
  "homes": {
    "person_a": "windows+tables",
    "person_b": "lights+tables",
    "person_c": "doors+curtains"
 }
}

The application should, for each user request, calculate quotes for the 3 insurers. The business requirement is as follows:

The quote is a 10% of the rate if 2 covers are matched or 20% if just 1 cover is matched and that is the biggest requested, 25% if it is the second biggest or 30% if is the third.

the request from user is as follow

{:curtains=>20, :tables=>30, :windows=>50}

The system should not return a quote if the value is zero(0)

For eg: the application will return  the result for the above user request

{
    person_a: 8 (10% of 80 (two matches on windows and tables))
    person_b: 7.5 (25% of 30 (one match on tables, the 2nd biggest cover))
    insurer_c: 6 (30% of 20 (one match on curtains, the 3rd biggest cover)

}

This is my solution:

require_relative './rules'

module Coverage
  class CalculateQuotes
    def initialize(quotes)
      @quotes = quotes
    end

    def calculate_rates
      result = []
      @insurer = Coverage::Rules.parse_file ## which will give {
                                        #"insurer_rates": {
                                       #"person_a": "windows+tables",
                                       # "person_b": "lights+tables",
                                       #"person_c": "doors+curtains"
                                      # }}
      @insurer[:insurer_rates].each do |k, v|
        @match_covers = match_cover(v.split("+"))
        result << [k, calculate_rate ]
      end
    end

    def match_cover(covers)
      covers = covers.map { |x| x.to_sym }
      @quotes.select { |k,v| covers.include?(k) }
    end

    def calculate_rate
      premium    = 0.0
      persentage = get_percentage_by_match_covers
      @match_covers.values.each do |v|
        premium += v * persentage
      end
      premium == 0 ? nil : premium
    end

    def get_percentage_by_match_covers
      if @match_covers.size == 2
        0.1
      elsif @match_covers.size == 1
        only_1_match_covers
      else
        0
      end
    end

    def only_1_match_covers
      index = position_of_customer_request
      case index
      when 0
        0.2
      when 1
        0.25
      when 2
        0.3
      else
        raise StandardError
      end
    end

    def position_of_customer_request
      (@quotes.to_a.reverse).index(@match_covers.to_a.flatten)
    end
  end
end

request = {:windows=>50, :contents=>30, :engine=>20}

Coverage::CalculateQuotes.new(request).calculate_rates
````


texts:
I want to reduce/shorten this part quite a lot. If you see that a method can be reduced or even erased please do not hesitate to suggest that. Any answer that rescue the code would be great.

(photos, identification, testers, id) = ([], [], {}, 0)

# Get the folders containing the training data
for (subdirectorys, directorys, files) in os.walk(dir):

    # Loop through each folder named after the subject in the photos
    for subdirectory in directorys:
        testers[id] = subdirectory
        subpath = os.path.join(dir, subdirectory)

        # Loop through each photo in the folder
        for file_name in os.listdir(subpath):

            # Skip non-image formates
            f_name, f_extension = os.path.splitext(file_name)
            if(f_extension.lower() not in
                    ['.png','.jpg','.jpeg','.gif','.pgm']):
                print("Skipping "+file_name+", wrong type given for the file")
                continue
            path = subpath + '/' + file_name
            lable = id

            # Add to training data
            photos.append(cv2.imread(path, 0))
            identification.append(int(lable))
        id += 1
(im_width, im_height) = (112, 92)

# Create a Numpy array from the two lists above
(photos, identification) = [numpy.array(lis) for lis in [photos, identification]]


texts:
Everything in this code is completely working, but I still feel that this code needs to be refactored. any suggestions?

<?php
    class Db_CheckUsername{
        protected $_conn;
        protected $_username;
        protected $_minimumChars = 8;
        protected $_errors = array();

        public function __construct($username, $conn){
            $this->_username = $username;
            $this->_conn= $conn;
        }

        public function check(){

            $sql = "SELECT * FROM accounts WHERE username = '{$this->_username}'";

            $result = $this->_conn->query($sql);
            $numRows = $result->num_rows;

            if(preg_match('/\s/',$this->_username)){
                $this->_errors[] = "Spaces are not allowed";
            }

            if($numRows > 0){
                $this->_errors[] = "Username Taken";
            }

            if(strlen($this->_username) < $this->_minimumChars){
                $this->_errors[] = "Username Should Contain, atleast {$this->_minimumChars} chars";
            }

            return $this->_errors ? false : true;
        }

        public static function isUsernameCorrect($username,$conn){

        }

        public function getErrors(){
            return $this->_errors;
        }
    }


texts: Get the next date based on a collection of valid weekdays

texts:
public static DateTime NextByDayOfWeek(this DateTime target, IEnumerable<DayOfWeek> validDaysOfWeek)
{
    validDaysOfWeek = validDaysOfWeek
        .OrderBy(item => item);

    var nextDayOfWeek = validDaysOfWeek
        .Where(item => item > target.DayOfWeek)
        .FirstOrDefault();

    return nextDayOfWeek != 0
        ? target.AddDays(nextDayOfWeek - target.DayOfWeek)
        : target.AddDays((validDaysOfWeek.First() + 7) - target.DayOfWeek);
}

Usage:

DateTime.Today.NextByDayOfWeek(new[] { DayOfWeek.Monday, DayOfWeek.Friday })

I don't think there are any possible edge cases here, at least some initial tests don't reveal any problem.

I think it's short and readable, but readability is often hard to judge when you're the author.

Any remarks?


texts:
I wrote a very simple quick and easy script to migrate a bunch of data to another table in my database.

Can I accomplish this task without using so many foreach loops?
I realize I'm imputting similar data in each of my loops and it just seems redundant and wrong.

I thought of using array_merge on talkers, pros & anons and I thought that   because each of the second loops use the same field, I would write code to retrieve getYI and then write code to determine if it belonged to a talker, anon, or pro.
However I wasn't sure if either of those solutions would make my script any more efficient/better.

Certainly any insight would be appreciated. Thanks in advance!

And if it helps I'm using Symfony 2.3.

public function migratingDataScript()
{
    $em = $this->getDoctrine()->getManager();

    $talkers = $em->getRepository('AppBundle:Talker')->findAll();
    $anons = $em->getRepository('AppBundle:Anon')->findAll();
    $pros = $em->getRepository('AppBundle:Pro')->findAll();

    foreach ($talkers as $talker) {
        echo "Talker: ".$talker->getId()."
";
        foreach ($talker->getYI() as $year => $status) {
            $rounds = $em->getRepository('AppBundle:Round')->findByYear($year);
            foreach ($rounds as $round) {
                $newTalkerInvitation = new Invitation($round);
                $newTalkerInvitation->setStatus($status);
                $newTalkerInvitation->setTalker($talker);
                // $newTalkerInvitation->setNumAt(); No Data For Talker
                // $newTalkerInvitation->setStart(); No Data For Talker
                $em->persist($newTalkerInvitation);
            }
        }
    }//Ends Talker Migration

    foreach ($anons as $anon) {
        echo "Anon: ".$anon->getId()."
";
        foreach ($anon->getYI() as $year => $status) {
            $rounds = $em->getRepository('AppBundle:Round')->findByYear($year);
            foreach ($rounds as $round) {
                $newAnonInvitation = new Invitation($round);
                $newAnonInvitation->setStatus($status);
                $newAnonInvitation->setAnon($anon);
                // $newAnonInvitation->setNumAt(); No Data For Anon
                // $newAnonInvitation->setStart(); No Data For Anon
                $em->persist($newAnonInvitation);
            }
        }
    }//Ends Anon Migration

    foreach ($pros as $pro) {
        echo "Pro: ".$pro->getId()."
";
        foreach ($pro->getYI() as $year => $status) {
            $rounds = $em->getRepository('AppBundle:Round')->findByYear($year);
            foreach ($rounds as $round) {
                $newProInvitation = new Invitation($round);
                $newProInvitation->setStatus($status);
                $newProInvitation->setPro($pro);
                if(is_null($pro->getNumOfAttempts())){
                    $newProInvitation->setNumAt('0');
                }else {
                    $newProInvitation->setNumAt($pro->getNumOfAttempts());
                }
                // $newProInvitation->setStart(); No Data For Pro
                $em->persist($newProInvitation);
            }
        }
    }//Ends Pro Migration

    $em->flush();
    echo "Completed.";
    die;
}


texts: Pass an array of numbers into a method that's overloaded

texts:
I'm doing my homework and it says to write a test program that prompts the user to enter ten double values, invokes this method, and displays the average value.

I was able to get this program working with an overloaded method... but I'm curious to hear your feedback on where I can improve and what I'm not understanding 100%. Please feel free to review this and let me know your constructive feedback as to my code and where you think I can do better.

import java.util.Scanner;

public class PP68 {

    public static void main(String [] args) {//start main

        Scanner input = new Scanner(System.in); //new object of scanner type

        double avg =0, total =0;

        double[] average = new double[10];      //double array

        for(int i = 0; i < 10; i++){             //enter 10 numbers to average
            System.out.print("Enter a number to average.");
            average[i] = input.nextDouble();
        }

        for(int j = 0; j < average.length; j++) {
            total = total + average[j];
            avg = total / average.length;
        }
        System.out.println("The average of your arrays numbers is: " + avg);

    }//end main

    public static int average(int[] array){ //1st method
        int total =0;
        int avg = total / array.length;
        return avg;

    }//end 1st method
    public static double average(double[] array) {//Second method - overloaded
        double total = 0;
        double avg = total / array.length;
        return avg;

    }//end 2nd method

}

New code follows below:

import java.util.Scanner;

public class PP68v2 {

    public static void main(String [] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Enter 1 to average an INT or hit 2 to average a DOUBLE");
    int entry = input.nextInt();

        if (entry == 2) {                                  //choose double and call double method
            double[] array = new double[10];
                for(int i = 0; i < 10; i++){
                    System.out.println("Enter a number to average.");
                    array[i] = input.nextDouble();
                }
                System.out.println("The average of your arrays numbers is: " + average(array));

        } else if (entry == 1) {                           //choose int and call int method
            int[] array = new int[10];
                for(int b = 0; b < 10; b++) {
                    System.out.println("Enter a number to average.");
                    array[b] = input.nextInt();
                }
                System.out.println("The average of your arrays numbers is: " + average(array));
        }

    }

    public static int average(int[] array){
        int total =0;
        int avg1 = 0;
            for(int b=0; b < 10; b++) {
                total = total + array[b];
                avg1 = total / 10;
            }
        return avg1;

    }

    public static double average(double[] array) {
        double total = 0;
        double avg = 0;
            for(int i =0; i < 10; i++) {
                total =  total + array[i];
                avg = total / array.length;
            }
        return avg;

    }

}


texts:
I have this method rated B on Scrutinizer (direct link: https://scrutinizer-ci.com/g/sineverba/domotic-panel/inspections/76996c9f-543f-43b4-9475-c64fe810a278/code-structure/operation/App%5CHttp%5CControllers%5CApi%5CPublicIpController%3A%3Aupdate)

public function update()
{
    try {
        $data = array();
        $update = false;
        $string_previous_public_ip = null;
        $current_public_ip = $this->getGateway()->fetchPublicIp($this->getIp());
        $previous_public_ip = $this->getGateway()->getLastRecord();
        $data[ 'ip_address' ] = $current_public_ip;
        if (isset($previous_public_ip->ip_address)) {
            $string_previous_public_ip = $previous_public_ip->ip_address;
            $data[ 'id' ] = $previous_public_ip->id;
        }
        if ($current_public_ip != $string_previous_public_ip) {
            $update = $this->updateOrCreate($data);
        }
        return response()->json([
            'updated' => $update
        ], 200);
    } catch (ConnectionError $e) {
        // Will return error 500
    } catch (ServiceError $e) {
        // Will return error 500
    } catch (\Exception $e) {
        // Will return error 500
    }
    return response()->json([
        'updated' => $update
    ], 500);
}

Can I lower the cyclomatic complexity? I did move yet a if/else for the update (updateOrCreate method I think it is clear his work), but it is not sufficient.

Thank you!