texts: Printing the max of groups of three random ints

texts:
I'm trying to teach myself streaming and lambda expressions. Here's the scenario: I have a collection of 10 Thing objects each containing an int[] of 3 random number. I've written code to print out the largest number in each Thing.

I've already written two statements and an accompanying method that print the result I want, however the code is pretty ropey... improvements and suggestions would be greatly appreciated.

import java.util.Random;
public class Thing {
    private Random r = new Random();
    private int a = r.nextInt(), b = r.nextInt(), c = r.nextInt();

    public int[] getCollectionOfInts() {
        return collectionOfInts;
    }

    private int[] collectionOfInts = new int[]{a, b, c};

}//end of class

//main in separate driver class
public static void main(String[] args) {
        Thing[] things = new Thing[10];
        int a=0,b=0,c=0;
        for (int x =0;x<10;x++){
            things[x] = new Thing();
            for (int y=0;y<things[x].getCollectionOfInts().length;y++)
            {
                if(y==0)
                    a = things[x].getCollectionOfInts()[y];
                if(y==1)
                    b = things[x].getCollectionOfInts()[y];
                if(y==2)
                    c = things[x].getCollectionOfInts()[y];
            }
            //print 3 numbers in each Thing object
            System.out.println(x+": "+a+", "+b+", "+c);
        }
        System.out.println();

        //compare each number and print out largest... too many ternaries
        Stream.of(things).forEach(Thing->System.out.println(Stream.of(Thing.getCollectionOfInts()).mapToInt(z->z[0]>z[1]&&z[0]>z[2]?z[0]:z[1]>z[2]?z[1]:z[2]).reduce((x,y)->x+y).getAsInt()));
        System.out.println();
        //improper use of .max() or .mapToInt(...)?
        Stream.of(things).forEach(Thing->System.out.println(Stream.of(Thing.getCollectionOfInts()).mapToInt(x->maxInt(x)).max().getAsInt()));

    }
    public static int maxInt(int[] x) {
        int max=x[0];
        for (int y:x) {
            if(y>max)
                max = y;
        }
        return max;
    }

I get the expected results for both streams, but I'm still unhappy with how I get there!


texts: Function to print command-line usage for a program

texts:
The following function works well to print out a help message for the program I have written. It prints a multi-line string message that describes the command line usage with some examples:

def usage():

    print(
        """
Usage examples:

Test deployment:
       $ fab [noinput] test deploy

Staging deployment:
       $ fab [noinput] staging deploy

Production deployment:
       $ fab [noinput] production deploy
""")

Unfortunately, in order to make the message look good in the output, the code block currently looks ugly with the string message making the indentation of the code look wrong. Is there a way to improve the code so that it is more readable, similar to the following code (which does not work - it is just an example) where the indentation is more readable?

def usage():

    print(
        """
        Usage examples:
        Test deployment:
            $ fab [noinput] test deploy
        Staging deployment:
          $ fab [noinput] staging deploy
        Production deployment:
          $ fab [noinput] production deploy
        """
    )

How can the readability be improved while still producing results that look good in the output?


texts: Python script that alerts me when specific file gets created

texts:
I wrote a small script that opens a window using PyQt when a specific file gets created.

This is to let me know when another program (that I have no control over) has finished calculating something. I know at the end of the calculation a specific file is created.

Here is the code:

from PyQt5.QtWidgets import QWidget, QLabel
import os.path

file_to_check = "D:/test.txt"

alert_widget = QWidget()
alert_widget.setWindowTitle("Program X finished")
done_label = QLabel("Done",alert_widget)
done_label.move(50,50)

file_does_not_exist = True

while file_does_not_exist:
    if os.path.isfile(file_to_check):
        file_does_not_exist = False

alert_widget.show()

The widget that gets shown luckily just pops up in front of whatever window im currently active in, whether it's browsing the internet or working on an excel sheet. That is intended behaviour, but I did not write it in by specifying it as a "top level" window or somehting.

The script is started in an IPython console in Spyder and just left to run there. It works exactly as expected.

Now my questions

is this constantly running loop good practice?
are there any downsides to having that loop constantly running in the background?
could it block other programs?
is there another, more elegant way to achieve what I'm looking to do?
is the code following python coding conventions?


texts:
I am trying to find out how many minutes that are remaining until the next train will departure, based on the current system time in Java.

I am so far not familiar with the many aspects of Java, but I have managed to get the program to work in most use cases with a switch statement and while loop, but it feels like I am using too many workarounds to get the code to work as intended.

The next step is that I am trying to complete, the task in a less tedious and more elegant way. I was wondering if anyone could point me in the right direction to how the task could be completed in a similar way but with other features of Java, such as ArrayLists, tables etc. that are suitable for what I am trying to accomplish.

public class TrainDepartures{

public static void main(String[] args) {

    long time = System.currentTimeMillis();
    int initialTime = (int) (time / (1000 * 60) % 60);
    int findNextDeparture = (int) (time / (1000 * 60) % 60);

    boolean foundDeparture = false;

    loop: while (foundDeparture != true) {
        findNextDeparture++;
        switch (findNextDeparture) {
            case 10:
                 System.out.print("Departure in " + (Math.abs(initialTime - 10)) + " min.");
                break loop;
            case 20:
                System.out.print("Departure in " + (Math.abs(initialTime - 20)) + " min.");
                break loop;
            case 30:
                System.out.print("Departure in " + (Math.abs(initialTime - 30)) + " min.");
                break loop;
            case 40:
                System.out.print("Departure in " + (Math.abs(initialTime - 40)) + " min.");
                break loop;
            case 50:
                System.out.print("Departure in " + (Math.abs(initialTime - 50)) + " min.");
                break loop;
            case 52:
                System.out.print("Departure in " + (Math.abs(initialTime - 52)) + " min.");
                break loop;
            case 55:
                System.out.print("Departure in " + (Math.abs(initialTime - 55)) + " min.");
                break loop;
            case 56:
                System.out.print("Departure in " + (Math.abs(initialTime - 56)) + " min.");
                break loop;
            case 57:
                System.out.print("Departure in " + (Math.abs(initialTime - 57)) + " min.");
                break loop;
}
}
}
}


texts: K&R Exercise 5-15: sorting with extra options

texts:
As I'm learning to program in C, I'm making my way through K&R.

The goal of the exercise is to add a option to the program so that the sorting does not depend on upper or lower-case letters.

What are your opinions on my use of function pointers in this exercise?
Do you see any obvious beginner traps in the code?

#include "main.h"
char *pointersToLines[MAX_NO_OF_LINES];
int (*compareFunctionPointers[3])(void *, void *);
int main(int argc, char *argv[]) {

    // Store pointers to the diffrent types of
    // compare functions in a array of
    // function pointers.
    compareFunctionPointers[COMPARE_DEFAULT] = &strcmp;
    compareFunctionPointers[COMPARE_FOLDED] = &strcmpFold;
    compareFunctionPointers[COMPARE_NUMERICLY] = &numcmp;

    int numberOfLines;
    int sortDecreasing  = 0; // 1 if the input is to be sorted in a decreasing order
    int compareFunction = COMPARE_DEFAULT; // Index for the compare-function
    // Parse the command line arguments
    if (argc > 1) {
        for (int i = 1; *(argv + i); i++) {
            char *c = *(argv + i);
            if(strcmp(c, "-n") == 0)
                compareFunction = COMPARE_NUMERICLY;
            if(strcmp(c, "-r") == 0)
                sortDecreseingly = 1;
            if(strcmp(c, "-f"))
                compareFunction = COMPARE_FOLDED;

        }
    }

    if ((numberOfLines = readLines(pointersToLines, MAX_NO_OF_LINES)) >= 0) {
        qsort1((void **)pointersToLines, 0, numberOfLines - 1,
           (int (*)(void *, void *))compareFunctionPointers[compareFunction],
            sortDecreasing);

        writeLines(pointersToLines, numberOfLines);
        return 0;
    }
}

Sorting Function

void qsort1(void *v[], int left, int right, int (*comp)(void *, void *),
           int increesingOrDecresing) {
    int last, compare;
    //Base case
    if (left >= right) {
    return;
    }

    swap(v, left, (right + left) / 2);
    last = left;
    for (int i = left + 1; i <= right; i++) {
        compare = (increesingOrDecresing) ? -(*comp)(v[i], v[left])
                                    : (*comp)(v[i], v[left]);
    if (compare < 0)
        swap(v, ++last, i);
    }
    swap(v, last, left);
    qsort1(v, left, last - 1, comp, increesingOrDecresing);
    qsort1(v, last + 1, right, comp, increesingOrDecresing);
}

Compare functions

int strcmpFold(char *s1, char *s2) {
    while (toupper(*s1) == toupper(*s2)) {
        s1++;
        s2++;
    }
    if (toupper(*s1) < toupper(*s2))
        return -1;
    else if (toupper(*s1) > toupper(*s2))
        return 1;
    else
        return 0;
}

int numcmp(char *s1, char *s2) {
    double v1, v2;
    v1 = atof(s1);
    v2 = atof(s2);

    if (v1 < v2)
        return -1;
    else if (v1 > v2)
        return 1;
    else
        return 0;
}


texts: Counting the number of continuous palindromic substrings

texts:
Given a string of lowercase ASCII characters, find all distinct continuous palindromic sub-strings of it.
Here is my code:

def palindrome(s):
    if s==s[::-1]:
        return True

noTest=int(input())
s=[]
for _ in range(noTest):
    s.append(input())

count=[]
for word in s:
    letters=[]
    psub=[]
    for l in word:
        letters.append(l)
        if l not in psub:
            psub.append(l)

    for i in range(len(letters)):
        for k in range(i+1,len(letters)+1):
             sub=('').join(letters[i:k])
             #print (i,k,sub)
             if palindrome(sub) and sub not in psub:
                 psub.append(sub)

    count.append(len(psub))

for c in count:
    print (c)

Input:
The first line of input contains an integer T denoting the number of test cases.    Then T test cases follow. Each test case contains a string.

Output:
Print the count of distinct continuous palindromic sub-strings of it.


texts:
This code was inspired by this question: Payroll Program.  I saw lots of ways I thought the code could be improved.  So much so that I thought it wouldn't be particularly constructive to post all of it as an answer to that question.  Essentially, I wanted to basically rewrite the whole thing from scratch.

So I did.  But I'm far from a C++ expert, so tell me how to make this even better:

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
#include <sstream>

const double WORK_WEEK_HOURS = 40;
const double OVERTIME_RATE = 1.5;

struct employee {
    int id;
    double payrate;
    double hours;
};

void payroll();
std::string fetchFileName();
employee fetchEmployee();
double wagesForEmployee(employee e);
bool askUser(std::string s);
std::string employeesToString(std::vector<employee> e);
void displayEmployees(std::vector<employee> e);
void saveEmployeesToFile(std::vector<employee> e);

int main(int argc, const char * argv[]) {
    payroll();
    return 0;
}

void payroll() {
    std::vector<employee> employees;

    do {
        employees.push_back(fetchEmployee());
    } while (askUser("Would you like to enter more employees? (y/n): "));

    if (askUser("Would you like to view the information you entered? (y/n): ")) {
        displayEmployees(employees);
    }

    if (askUser("Would you like to save the information you entered to file? (y/n): ")) {
        saveEmployeesToFile(employees);
    }
}

bool askUser(std::string s) {
    char answer;
    std::cout << s;
    std::cin >> answer;
    return (answer == 'y' || answer == 'Y');
}

employee fetchEmployee() {
    employee e;
    e.id = -1;
    e.payrate = -1;
    e.hours = -1;

    do {
        std::cout << "Enter the employee ID: ";
        std::cin >> e.id;
    } while(e.id < 0);

    do {
        std::cout << "Enter the payrate: ";
        std::cin >> e.payrate;
    } while (e.payrate < 0);

    do {
        std::cout << "Enter the hours worked: ";
        std::cin >> e.hours;
    } while (e.hours < 0);

    return e;
}

double wagesForEmployee(employee e) {
    if (e.hours < 0 || e.payrate < 0) {
        return 0;
    }
    double wages = 0;
    if (e.hours > WORK_WEEK_HOURS) {
        wages += (e.hours - WORK_WEEK_HOURS) * OVERTIME_RATE * e.payrate;
    }
    wages += std::min(e.hours, WORK_WEEK_HOURS) * e.payrate;
    return wages > 0 ? wages : 0;
}

std::string employeesToString(std::vector<employee> e) {
    std::stringstream ss;

    ss << std::setw(10) << "ID" << std::setw(10) << "Rate" << std::setw(10) << "Hours" << std::setw(10) << "Wage" << std::endl;
    ss << "---------------------------------------------------------" << std::endl;

    for (int i = 0; i < e.size(); ++i) {
        employee curEmp = e.at(i);
        ss  << std::setw(10) << curEmp.id << std::setprecision(2) << std::fixed
            << std::setw(10) << curEmp.payrate << std::setprecision(2) << std::fixed
            << std::setw(10) << curEmp.hours << std::setprecision(2) << std::fixed
            << std::setw(10) <<  wagesForEmployee(curEmp) << std::endl;
    }

    return ss.str();
}

void displayEmployees(std::vector<employee> e) {
    std::cout << employeesToString(e) << std::endl;
}

void saveEmployeesToFile(std::vector<employee> e) {
    std::ofstream outputFile;
    std::string fileName;

    std::cout << "Enter a file name: ";
    // TODO: Safety checking for illegal file name characters, etc.
    std::cin >> fileName;
    fileName += ".pay";
    outputFile.open(fileName.c_str());
    outputFile << employeesToString(e);
    outputFile.close();

    std::cout << "Successfully saved to " << fileName;
}


texts: Simple advertisement blocker I did for my school project

texts:
I want to share and get some feedback on a simple advertisement blocking program I wrote for my school project, named StopADS!. The main idea of this code is to remove advertisements from websites to make the web browsing experience smoother. Pretty close to finishing my 2nd year of programming in high school so obviously it is not perfect. Works on any chromium based browser and some browsers on mobile. Moving forward, my plan is to develop this little project to a complete application for mobile users. Thank you all in advance for any feedback or testing, means a lot!
GUIDE HOW TO TEST THIS OUT IN YOUR BROWSER

Download the files

Extract the files to a folder or a place of your preference.

Go to the extension settings in your preferred browser.

Press load unpacked and locate the files

Enjoy!

Code example:
var enabled = true;
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if(enabled) {
            console.log("blocking:", details.url);
        }
        return {cancel: enabled };
    },
    {urls: blocked_domains},
    //{urls: ["<all_urls>"]}, /* replace with list of blacklisted urls */
    ["blocking"]
);


texts:
Background:

After reading this thought provoking book I decided to write a small library as an exercise.

goog.require('goog.structs.Map');

var MyModule = {};

MyModule.FormHelper = {
  /** @type {?Element} */
  form: null,
  /** @type {goog.structs.Map<string, string>} */
  errors: {},

  /** @param {!Element} element */
  init: function(formElement) {
    this.form = formElement;
  },

  /**
   * @param {!Element} element
   * @return {!Array<goog.structs.Map<string, Object>>}
   */
  getElementAttributes: function(element) {
    if (!element) return [];
    return [].slice.call(element.attributes).map(function(attr) {
      return {[attr.name]: attr.value};
    });
  },

  /**
   * @param {string} filterOn
   * @return {!Array<!Element>}
   */
  filterElements: function(filterOn) {
    return [].slice.call(this.form.elements).filter(function(element) {
      return element.hasAttribute(filterOn);
    });
  }
};

MyModule.Form = Object.create(MyModule.FormHelper);

MyModule.Form.validate = function() {
  /** @type {!Array<!Element>} */
  var elements = this.getRequiredElements();
  elements.reduce(function(map, element) {
    if (element.value == '') {
      map[element.name] = 'Required field cannot be empty';
    }
    return map;
  }, this.errors);
};

MyModule.Form.getRequiredElements = function() {
  return this.filterElements('required');
};

MyModule.createForm = function(name) {
  /** @type {!Element} */
  var formElement = document.forms[name];
  if (!formElement) {
    throw new Error('Form not found.');
  }
  var form = Object.create(MyModule.Form);
  form.init(formElement);
  return form;
};

var contactForm;
var callback = function(e) {
  e.preventDefault()
  contactForm.validate();
  console.log(contactForm.errors);
}

window.onload = function () {
  contactForm = MyModule.createForm('ContactForm');
  contactForm.form.addEventListener("submit", callback, false);  //Modern browsers
}

I am using Google closure for type checking and advance code optimizations.

I want to check if I am following a good object oriented design and practices?

Update 1

;(function(global, doc, lib) {
  var Form = {};

  Form.create = function(name) {
    var form = doc.forms[name];
    if (!form) {
      throw new Error('Form not found.');
    }
    this.formElement = form;
  };

  Form.elements = function() {
    return this.formElement.elements;
  };

  Form.filter = function(attr) {
    return [].slice.call(this.elements()).filter(function(element) {
      return element.hasAttribute(attr);
    });
  };

  Form.getAttributes = function(element) {
    if (!element) return [];
    return [].slice.call(element.attributes).map(function(attr) {
      return {[attr.name]: attr.value};
    });
  };

  Form.validate = function(formName) {
    var elements = this.filter('required');
    elements.reduce(function(error, element) {
      if (element.value == '') {
        error[element.name] = 'Required field cannot be empty';
      }
      return error;
    }, this.errors);
  };

  lib.validate = function(formName) {
    var form = Object.create(Form);
    form.create(formName);
    form.errors = [];
    form.validate();
    return form;
  };

})(window, document, window.lib || (window.lib = {}));

window.onload = function() {
  console.log(lib);
  console.log(lib.validate('foo').errors);
};


texts:
The OpenGL tutorial that I was following only used a single model to demonstrate various points. I wanted to draw more than one model. After some research, I came to the conclusion that I needed to create a vertex array object, once for each model, and than I can use it to access buffers and attributes for each model. In order to do that, I am using this game object struct.

(I'm not including the whole code because it is quite long.)

typedef struct GameObject {
    GLuint VertexArray;
    GLuint NumVertices;
    kmMat4 ModelMatrix;
} GameObject;

For each object I want to draw, I am using loader function, such as the following:

#include "GameObject.h"

static const GLfloat triangle_vertices[] = {
    0, 1, 0,
    -1, -1, 0,
    1, -1, 0
};

static const GLfloat triangle_colors[] = {
    0.2, 0.2, 0.2,
    0.5, 0.5, 0.5,
    0.8, 0.8, 0.8
};

GameObject *newTriangle()
{
    GameObject *triangle = malloc(sizeof(GameObject));

    GLuint VertexBuffer;
    GLuint ColorBuffer;

    // 1. Generate VertexArray for object
    glGenVertexArrays(1, &(triangle->VertexArray));

    // Bind it
    glBindVertexArray(triangle->VertexArray);

    // Create and fill buffers vertex and color buffers
    glGenBuffers(1, &VertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangle_vertices), triangle_vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(
           0,
           3,
           GL_FLOAT,
           GL_FALSE,
           0,
           (void*)0
    );

    glGenBuffers(1, &ColorBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, ColorBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangle_colors), triangle_colors, GL_STATIC_DRAW);

    glEnableVertexAttribArray(1);
    glVertexAttribPointer(
           1,
           3,
           GL_FLOAT,
           GL_FALSE,
           0,
           (void*)0
    );

    // unbind vertex array
    glBindVertexArray(0);

    triangle->NumVertices = (sizeof(triangle_vertices)/sizeof(GLfloat));
    kmMat4Identity(&(triangle->ModelMatrix));

    return triangle;
}

And I am using this function to draw each game object:

#include "GameObject.h"

void Draw(GameObject *go, kmMat4 *VP, GLuint MatrixID)
{
    kmMat4 MVP;
    kmMat4Multiply(&MVP,VP,&go->ModelMatrix);

    // Bind vertex array
    glBindVertexArray(go->VertexArray);

    // set mvp matrix
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, MVP.mat);

    // Draw object
    glDrawArrays(GL_TRIANGLES, 0, go->NumVertices);

    // Unbind VertexArray
    glBindVertexArray(0);
}

And this is my main loop:

while (!glfwWindowShouldClose(window))
{
    kmMat4 current_translation;
    GLfloat translatex = 0;
    GLfloat translatez = 0;

    double current_time = glfwGetTime();
    double delta_time = current_time - last_time;
    last_time = current_time;

    if (glfwGetKey( window, GLFW_KEY_RIGHT ) == GLFW_PRESS){
        translatex += 2 * delta_time;
    }

    if (glfwGetKey( window, GLFW_KEY_LEFT ) == GLFW_PRESS){
        translatex -= 2 * delta_time;
    }

    if (glfwGetKey( window, GLFW_KEY_UP ) == GLFW_PRESS){
        translatez -= 2 * delta_time;
    }

    if (glfwGetKey( window, GLFW_KEY_DOWN ) == GLFW_PRESS){
        translatez += 2 * delta_time;
    }

    kmMat4Translation(&current_translation, translatex, 0, translatez);
    kmMat4Multiply(&square->ModelMatrix, &current_translation, &square->ModelMatrix);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    Draw(triangle, &vp, MatrixID);
    Draw(square,   &vp, MatrixID);

    glfwSwapBuffers(window);
    glfwPollEvents();
}


texts:
I am learning Java and this is my solution for a program that will read two numbers in the range of 0 to 99 and multiply them. Input numbers are given in natural language e.g. for input thirty-two ten it should return 320. I have tried to do my best. Could someone please review this and suggest improvements, if any?

package assignments;
import java.util.*;
public class NaturalLanguageMultiply {
    private static final Map<String, Integer> numericValues = new HashMap<String, Integer>();
    private static final String WORD_SEPARATOR = "-";
    static {
        numericValues.put("zero", 0);
        numericValues.put("one", 1);
        numericValues.put("two", 2);
        numericValues.put("three", 3);
        numericValues.put("four", 4);
        numericValues.put("five", 5);
        numericValues.put("six", 6);
        numericValues.put("seven", 7);
        numericValues.put("eight", 8);
        numericValues.put("nine", 9);
        numericValues.put("ten", 10);
        numericValues.put("eleven", 11);
        numericValues.put("tweleve", 12);
        numericValues.put("thirteen", 13);
        numericValues.put("fourteen", 14);
        numericValues.put("fifteen", 15);
        numericValues.put("sixteen", 16);
        numericValues.put("seventeen", 17);
        numericValues.put("eighteen", 18);
        numericValues.put("nineteen", 19);
        numericValues.put("twenty", 20);
        numericValues.put("thirty", 30);
        numericValues.put("forty", 40);
        numericValues.put("fifty", 50);
        numericValues.put("sixty", 60);
        numericValues.put("seventy", 70);
        numericValues.put("eighty", 80);
        numericValues.put("ninety", 90);
    }

    private static int wordToNumber(String word) {
        String[] tokens = word.split(WORD_SEPARATOR);
        int number = 0;
        for(String token : tokens) {
            Integer numericValue = numericValues.get(token);
            if(numericValue == null) {
                throw new IllegalArgumentException("unknown token " + token + " in word " + word);
            }

            number += numericValue;
        }
        return number;
    }

    public static void main(String[] args) {

        if(args.length < 2) {
            System.out.println("argument missing");
            System.exit(1);
        }

        try {
            int firstNumber = wordToNumber(args[0]);
            int secondNumber = wordToNumber(args[1]);
            System.out.format("%d%n", firstNumber * secondNumber);
            System.exit(0);
        } catch(Exception e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}


texts:
This is a probe request packet sniffer using python/scapy. It sniffs Dot11ProbeReq packets and display the ssid, MAC of device and manufacturer name from the probe requests. Can also output the data to a log file if desired. Right now I feel the script is a bit slow and I can see it slow down from the first time I wrote it. It works but I know the code is nowhere as efficient as it could be. Can you point out my mistakes and let me know how I can write more efficient code?

#!/usr/bin/env python
# import all the needed libraries
import sys
from netaddr import *
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from subprocess import *
import datetime
import time

# clear the console
call(["clear"])

# set date-time parameters
today = datetime.date.today()
d=today.strftime("%d, %b %Y")
tf=time.strftime(" %H:%M")
t=time.strftime(" %H:%M:%S")

# define variables
clients = []
uni = 0
mach = []
manu =[]

# our packet handler
def phandle(p):
    global uni
    if p.haslayer(Dot11ProbeReq):
        mac = str(p.addr2)
        if p.haslayer(Dot11Elt):
            if p.ID == 0:
                ssid = p.info
                if ssid not in clients and ssid != "":
                    clients.append(ssid)
                    maco = EUI(mac)
            macf = maco.oui.registration().org
            print len(clients),mac+" ("+macf+") <--Probing--> "+ssid
            if args.log:
                f.write (str(len(clients))+" "+mac+" ("+macf+") //"+" <--Probing--> "+ssid+"\n")
                if mac not in mach:
                            mach.append(mac)
                            uni+=1
            elif mac not in mach:
            mach.append(mac)
                        uni+=1

# our main function
if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='PyRobe Help')
    parser.add_argument('interface', action="store", help="specify interface (ex. mon0)", default=False)
    parser.add_argument("-l","--log", dest="log",action="store_true", help="print log file")
    args = parser.parse_args()
    if args.log:
        f = open("ProbeLog"+str(today)+str(tf)+".txt","w")
        sniff(iface=args.interface,prn=phandle, store=0)
            print ("\n")
            print "Unique MACs: ",uni
        f.write ("\nUnique MACs: "+str(uni))
        f.write ("\nScan performed on: "+str(d)+" at"+str(t))
        f.close()
        print "Log successfully written. Exiting!"
    else:
        sniff(iface=args.interface,prn=phandle, store=0)
        print "\nSuccessfully Exited! No log file written."

I am basically looking for pointers on:

Handling command line arguments better
Calculating and assigning required memory/avoid leaks
Shortening the code to make it faster to execute

I am not looking for someone to edit my script and spoon feed me the solution, just point me in the right direction!

My Python version: 2.7.3 (default, Mar 13 2014, 11:03:55) [GCC 4.7.2]
My linux version: Distributor ID:Kali Description:Kali GNU/Linux 1.1.0 Release:1.1.0 Codename:moto Linux version 3.18.0-kali3-amd64 gcc version 4.7.2 Debian 4.7.2-5) ) #1 SMP Debian 3.18.6-1~kali2 (2015-03-02)


texts:
I'm new to react and I'm still using the life cycle methods, so my question is since componentDidMount() acts like a constructor I'm planning to initialize everything there:

render() {
        return (

                Done
                {
                    this.props.done.map((d) => (

                    <div className={`done ${this.state.isActive ? 'active' : ''}`} id={this.props.done.id}
                    onClick={(e) => {
                        this.props.setTaskID(d.id);
                        this.setToActive(e); //3.Call <-----
                        this.props.arrowStyleToDone();
                    }}>

                    ))
                }

        )
    }

    setToActive  //1.Declare <----
    componentDidMount() {
        //2.Initialize  <-----
        this.setToActive = (e) => {
            if(!e.target.classList.contains('active')) {
                e.currentTarget.classList.add('active');
                e.currentTarget.classList.add('border-done')
                this.props.closeAllTasks();
                this.props.closeAllDoing();
            } else {
                e.currentTarget.classList.remove('active');
                e.currentTarget.classList.remove('border-done')
                this.props.disableArrowButton();
            }
        }
    }
}

My idea is that if I declare everything inside the class which looks very ugly in my opinion, but then initializing everything on componentDidMount() my web app will be faster because it won't need to declare and initialize everything every render.

Is this correct? and should I put the declaring and initialization on top of render()? but the componenDidMount() is called after the initial render.


texts:
I used Pythons source code/documentation/textbook to come up with an abstract class and following subclasses.

My requirements are:

Domestic students don't require documentation
International student do require documentation (passports, etc..)

from abc import ABCMeta

class Student(metaclass=ABCMeta):

    def __init__(self, id, firstname, lastname):
        self.__id = id
        self.__firstname = firstname
        self.__lastname = lastname

    @property
    def iden(self):
        return self.__id

    @property
    def first_name(self):
        return self.__firstname

    @property
    def last_name(self):
        return self.__lastname

International Subclass:

from Student import Student
from copy import deepcopy

class International(Student):
    def __init__(self, iden, firstname, lastname, docuemnts):
        super().__init__(iden, firstname, lastname)

        self.__documents = deepcopy(docuemnts)
        self.__type_of_student = "International"

    @property
    def international_documents(self):
        return deepcopy(self.__documents)

Domestic Subclass:

from Student import Student

class Domestic(Student):

    def __init__(self, iden, firstname, lastname):
        super().__init__(iden, firstname, lastname)

        self.__type_of_student = "Domestic"

    @property
    def student_type(self):
        return self.__type_of_student

Have I constructed and implementation the abstract class correctly?


texts: Write a Java class "Sort" which implements the BubbleSort algorithm

texts:
For a further education I had to do the following task:

  Implement the BubbleSort algorithm within the Java class
  algorithm.Sort.

  Submit your solution to the JUnit system for automatic evaluation.

Here the source code of my Sort class. The requirements concerning the single methods I've added as comments.

package algorithm;

public class Sort
{
    /*
        Sort the complete field in ascending order.
    */
    public static void bubbleSort(int[] list)
    {
        Sort.bubbleSort(list, 0, list.length - 1);
    }

    /*
        Sort the field ascending from leftIndex to rightIndex.
        Implement the BubbleSort algorithm.
        One has to specify a lower and an upper index.
        These range of the array is then sorted by BubbleSort.
        The lower and the upper index have to be checked for validity.
    */
    public static void bubbleSort(int[] list, int leftIdx, int rightIdx)
            throws IllegalArgumentException
    {
        if (leftIdx < 0 || leftIdx > list.length - 1
                || rightIdx < 0 || rightIdx > list.length - 1)
        {
            throw new IllegalArgumentException("Left or right index invalid.");
        }

        for (int i = list.length; i > 1; i--)
        {
            for (int j = leftIdx; j < rightIdx; j++)
            {
                if (list[j] > list[j + 1])
                {
                    int tmp = list[j];

                    list[j] = list[j + 1];
                    list[j + 1] = tmp;
                }
            }
        }
    }

    // The largest element within the specified array-range
    // has to be moved to position i.
    // Basically just the inner loop of BubbleSort.
    // Parameter validity checks required.
    public static void bubbleUp(int[] list, int leftIdx, int i)
    {
        if (leftIdx < 0 || leftIdx > list.length - 1
                || i < 0 || i > list.length - 1)
        {
            throw new IllegalArgumentException("Left or right index invalid.");
        }

        while (leftIdx < i)
        {
            if (list[leftIdx] > list[leftIdx + 1])
            {
                int tmp = list[leftIdx];

                list[leftIdx] = list[leftIdx + 1];
                list[leftIdx + 1] = tmp;
            }

            leftIdx++;
        }
    }

    // Convert the array to a appropriate String representation!
    // Parameter validity checks required.
    public static String toString(int[] list, int start, int end)
    {
        if (start < 0 || start > list.length - 1
                || end < 0 || end > list.length - 1
                || start > end)
        {
            throw new IllegalArgumentException("Left or right index invalid.");
        }

        String ret = "";

        for (int i = start; i <= end; i++)
        {
            ret += list[i] + ", ";
        }

        return "[ " + ret.substring(0, ret.length() - 2) + " ]";
    }

    // Return the complete array as an appropriate String representation.
    public static String toString(int[] list)
    {
        return Sort.toString(list, 0, list.length - 1);
    }
}

Here's the Java class which I've made for myself, so I could test my code while developing:

package test;

import algorithm.Sort;
import static java.lang.System.out;

public class SortTest
{
    public static void main(String[] args)
    {
        int[] test = { 9, 16, 17, 5, 3, 18, 14, 4, 14, 17 };
        out.println("Before: " + Sort.toString(test) + "\n");

        Sort.bubbleSort(test);

        out.println("After: " + Sort.toString(test));

        /*  RESULT :
            Before: [ 9, 16, 17, 5, 3, 18, 14, 4, 14, 17 ]

            After: [ 5, 3, 4, 9, 14, 14, 16, 17, 17, 18 ]
        */
    }
}

My class passed the automated tests, so it might be correct formally. I would appreciate comments and critiques from other developers.


texts: Transforming markdown files in folders into a documentation

texts:
I start coding a simple application: I transform markdown files in folders into documentation.

My architecture is very flat. My code looks like a series of unit function called one after the other.

def main():
    config = get_user_config(os.getcwd())
    sources_dir = config['sources_dir']
    for root, dirnames, filenames in os.walk(sources_dir):
        for filename in fnmatch.filter(filenames, '*.md'):
            markdown_file_path = os.path.join(root, filename)

            html_block = transform_html_into_markdown(markdown_file_path)

            wrapped_html = '{{% extends "base.html" %}}{{% block content %}}{0}{{% endblock %}}'.format(html_block)

            html = render_html(wrapped_html, config)

            html_file_path = get_html_file_path(markdown_file_path, sources_dir)

            write_html_file(html_file_path, html)

What I really like:

I can unit test every function. Code is simple to understand, no fancy stuff.
Each function is in its own module.

What I do not like:

My main() method is growing until I create two functions to rule them all. I have the impression of hiding the dust under the carpet.
If I want for instance increase the number of process doing some calculation, I will probably need some hard refactoring.
Everything is synchronous.

Do you have some idea to improve my code? Should I try something else?


texts: Naive Bayes classifier for OKCupid profiles

texts:
I tried to write a naive Bayes classifier to classify OkCupid profiles, and I was wondering if you could give me feedback on my code.  The classifier performs no better than chance and the coding style is probably not great either.  I had a training set of 20 good profiles and 20 bad profiles, and a test set of 16 good and 29 bad, so I don't know if I am classifying poorly or if I just don't have enough data.

#!/usr/bin/python

# Naive Bayes classifier for OkCupid data.  The features are the words in
# the profile and the classes are HIGH and LOW.  This is used to
# predict the rating I would give a profile.

# TODO: tweak the classifier so it works better.

from subprocess import call
from math import sqrt

# File containing training data in the form "<rating> <username>"
TRAINING_DATA = "train.dta"

# File containing test set in the form "<rating> <username>"
TEST_DATA = "test.dta"

# Dictionary
dictionary = "TWL06.txt"

# Hash table containing words in highly-ranked profiles.
HIGH_WORDS = {}

# Hash table containing words in low-ranked profiles.
LOW_WORDS = {}

# Number of users in each category
hi = 0
low = 0

# Add training data to the hash tables.
t = open(TRAINING_DATA, 'r')
for user in t:
    rating = int(user.split(" ")[0])
    name = user.split(" ")[1]

    # Count users
    if rating == 1:
        hi += 1
    else:
        low += 1

    # Get data for each user
    call(["curl", "-o", "tmp.dta", "http://www.okcupid.com/profile/" + name])
    d = open("tmp.dta", 'r')

    # Get word list from user
    words = {}
    for line in d:
        for word in line.split(" "):
            if "/" in word or "=" in word or "<" in word or ">" in word or "()" in word or "&" in word or len(word) > 10:
                continue
            words[word.rstrip().lower()] = None
    d.close()

    # Add words in this word list to our master word lists
    for word in words:
        if rating == 1:
            if word in HIGH_WORDS:
                HIGH_WORDS[word] += 1
            else:
                HIGH_WORDS[word] = 1
        else:
            if word in LOW_WORDS:
                LOW_WORDS[word] += 1
            else:
                LOW_WORDS[word] = 1
t.close()

print HIGH_WORDS
print LOW_WORDS

# Classify a point, assuming training has already happened.
# P(C | F1 ... Fn) proportionate to P(C) * P(F1 | C) * ... * P(Fn | C)
def classify(username):
    # P(C)
    Phi = float(hi) / float(hi + low)
    Plow = float(low) / float(hi + low)
    ratio = Phi / Plow
    # Get data
    call(["curl", "-o", "tmp.dta", "http://www.okcupid.com/profile/" + username])
    d = open("tmp.dta", 'r')
    for line in d:
        for word in line.split(" "):
            # Calculate the probability of the feature given a class
            if word in HIGH_WORDS:
                numHi = float(HIGH_WORDS[word])
            else:
                numHi = 1
            if word in LOW_WORDS:
                numLow = float(LOW_WORDS[word])
            else:
                numLow = 1

            ratio = ratio * (numHi / float(hi)) / (numLow / float(low))
#            if word in HIGH_WORDS:
##                Phi = Phi * float(HIGH_WORDS[word]) / float(hi)
##            else:
##                Phi = Phi * (1 / float(hi))
#
#            if word in LOW_WORDS:
##                Plow = Plow * float(LOW_WORDS[word]) / float(low)
##            else:
##                Plow = Plow * (1 / float(low))

    print ratio
    if ratio > 1:
        return 1
    else:
        return 0

# Compute out of sample error on test set.
def getError():
    t = open(TEST_DATA, 'r')
    numUsers = 0.0
    total = 0.0
    for line in t:
        user = line.split(" ")[1]
        rating = int(line.split(" ")[0])
        prediction = classify(user)
        numUsers += 1.0
        if rating != prediction:
            total += 1.0
        print str(rating) + " " + str(prediction) + " " + user

    return total / numUsers

print getError()


texts: Parsing messages with fixed-width fields into Employee objects

texts:
I'm writing a application that reads from a queue of messages from a legacy mainframe system.

Some characteristics of message in the queue:

Message from the Q is always fixed length plain text : 64 char length
Each index or group of index indicates some meaning full data
The first 20 chars represent first name, next 20 surname, character following that represents gender, then next 8 chars denote date in yyyyMMdd format

I need to map these to Java objects. Here is the sample of what I'm doing.

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Slf4j
public class Solution {

    public static void main(String[] args){
        String input = "JOE                BLOGG                M19880101PX2018010199PNM";
        log.info("Input length 64 = ",input.length());
        log.info(empMapper(input).toString());
    }

    public static boolean boolMapper(char value){
        return (value == 'Y') ? true:false;
    }

    public static LocalDate dateMapper(String value){
        final String dateString = String.format("%s-%s-%s",value.substring(0,4),value.substring(4,6),value.substring(6));
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return LocalDate.parse(dateString, formatter);
    }

    public static Emp empMapper(String input){
        final Emp emp = new Emp();
        emp.setFirstName(input.substring(0,19).trim());
        emp.setSurName(input.substring(19,39).trim());
        emp.setGender(input.charAt(40));
        emp.setDob(dateMapper(input.substring(41,49)));
        emp.setEmpId(input.substring(49,61));
        emp.setJobType(input.charAt(61));
        emp.setShiftNeeded(boolMapper(input.charAt(62)));
        emp.setEmpLevel(input.charAt(63));
        return emp;
    }

    @Data
    @NoArgsConstructor
    public static class Emp{
        private String firstName;
        private String surName;
        private char gender;
        private LocalDate dob;
        private String empId;
        private char jobType;
        private boolean shiftNeeded;
        private char empLevel;
    }
}

  Output: Emp(firstName=JOE, surName=BLOGG, gender=M, dob=1988-01-01,
  empId=PX2018010199, jobType=P, shiftNeeded=false, empLevel=M)

My question is there a better solution for doing this from a performance point of view


texts: Trying to improve my javascript code in this simple challenge from coderbyte

texts:
Here is a slightly modified challenge from Coderbyte:

Determine if a given string is an acceptable. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.

For whatever reason, I have struggled mightily with this challenge. I tried to use a regular expression in my Booleans, I tried cascading if statements, I tried a while statement surrounding if statements, I tried to structure my code as a function. After hours of failure, I finally resorted to the following:

var str = prompt("Please enter a test string: ").split("");
answer = "true";

if (((str[0] != "+") && (str[0] != "=")) || ((str[str.length-1] != "+") && (str[str.length-1] != "="))){
  answer = "false";
}

for (var i = 1; i < str.length-1; i++){
  if (((str[i] != "+") && (str[i] != "=")) && (str [i-1] != "+" || str [i+1] != "+")){
      answer = "false";
  }
}

console.log(answer);

I think it works, but of all the possible solutions to this problem, I am guessing that it is toward the bottom in terms of efficiency and elegance. I'd really appreciate some guidance on how this could be improved.

Below is one of my "solutions" that did not work. Among other things, the Booleans are not evaluating correctly. I must be using the regular expressions incorrectly.

var str = prompt("Please enter a test string: ").split("");
answer = "true";

if ((str[0] === /[a-z]/gi) || (str[str.length-1] === /[a-z]/gi)){
    answer = "false";
}
for (var i = 1; i < str.length-1; i++){
  if (str[i] === /[a-z]/gi && (str [i-1] != "+" || str [i+1] != "+")){
      answer = "false";
  }

}

console.log(answer);


texts: Using the wildcard when importing packages

texts:
I am learning java and browsing posts on CodeReview and StackOverflow.

In my text Introduction to Java Programming- Y Daniel Liang it states:

  The wildcard import imports all classes in a package by using ...
  The information for the classes in an imported package is not read in
  at compile time or runtime unless the class is used in the program.
  The import statement simply tells the compiler where to locate the
  classes. There is no performance difference between a specific and a
  wildcard import declaration.

These are two examples:

This question:  (1)

import java.util.ArrayList;
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Bounds;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

This answer: (2)

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

Could these be written as:

(1)

import java.util.*
import javafx.beans.*
import javafx.collections.*
import javafx.geometry.*
import javafx.scene.*
import javafx.stage.*

and

(2)

import java. util.*

Are there exceptions to using the wildcard for importing?
What is considered the best practice when specifying imports?

I am not sure if this is best posted on code review or stackoverflow


texts:
Following Pimgd's question, I decided to take a look at the TIS-100 myself.

This is my solution to the 3rd challenge, building a differential converter.

Requirements:

  Read values from IN.A and IN.B
  Write IN.A - IN.B to OUT.P
  Write IN.B - IN.A to OUT.N

Instruction set:

I got the basics down, but I'm doing something terribly inefficient. All the calculations are done in the top two nodes and 4 nodes are doing nothing else than just passing along the data.

It's efficient in amount of instructions and memory, but not in computation cycles. There is no guide about what's idiomatic yet, but I suppose the computation cycles are top priority.

Where Pimgd's question was using an extra node he wanted to get rid of, I don't mind using extra nodes if that brings the amount of computation cycles down.

Code overview:

For convenience, I've also included the code in text.

Top left:

MOV UP, ACC
SAV
MOV ACC, RIGHT
SWP
SUB RIGHT
MOV ACC, DOWN

Top right:

MOV UP, ACC
SAV
SUB LEFT
MOV ACC, DOWN
SWP
MOV ACC, LEFT

Other nodes:

MOV UP, DOWN

Benchmarks:

Luckily, the TIS-100 system has an in-built measurement of cycles, nodes and instructions. So I know exactly how good or bad it performs in which area.

My solution is overall considered 'nominal'. Is my solution inefficient performance-wise? If yes, how should I bring the required amount of cycles down?


texts:
I was making a relatively large-scale project in Python as a learning experiment, and in the process I found that it would be useful to have a map (or, in Python, I guess they're called dictionaries) where a value could have multiple keys.  I couldn't find much support for this out there, so this is the implementation I ended up going with:

def range_dict(*args):
    return_val = {}
    for k,v in args:
        for i in k:
            return_val[i] = v
    return return_val

COINS = range_dict((range(1,15), None),
                     (range(15,30), "1d6x1000 cp"),
                     (range(30,53), "1d8x100 sp"),
                     (range(53,96), "2d8x10 gp"),
                     (range(96,101), "1d4x10 pp"))

I was told that this wasn't really a good way to achieve what I wanted to do, but I don't really understand why.  It works perfectly in my application.  What's wrong with this?  Is there a better, more Pythonic way to do this?


texts:
Just looking for some advice and I know using std namespace is bad but I didnt have the time to do all the using stuff. I want help on what here is good and what is bad practice :).

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class file {
public:
    file() = default;
    file(const string &fileN) : fileName(fileN) { if (!fileName) { cout << "Invalid file closing" << endl; fileName.clear(); fileName.close(); } }

    bool setWord(const string &tWord);
    bool searchFile(const string&);
    ostream &output(ostream&) const;
private:
    ifstream fileName;
    string word;
    int occured;
};

bool file::setWord(const string &tWord) {
    if (!tWord.empty()) {
        word = tWord;
        return true;
    }
    else {
        cerr << "The word your trying to set is empty" << endl;
        return false;
    }
}

bool file::searchFile(const string &tWord) {
    if (setWord(tWord)) {
        string temp;
        occured = 0;
        while (fileName >> temp) {
            if (temp == word) {
                ++occured;
            }
        }
        return true;
    }
    return false;
}

ostream &file::output(ostream &os) const {
    os << word << " occured " << occured << " times in your file";
    return os;
}

int main()
{
    file test("stdafx.h");
    if (test.searchFile("hey"))
        test.output(cout) << endl;
    return 0;
}


texts:
I've written an itty bitty tcp server, for educational purposes.

The program outputs a file if you input the correct hash (or whatever you set the environment variable to).

I've performed tests on the application through netcat ( nc localhost 9000 ) and everything is fine, the application works as intended, both in my docker container and running "standalone".

Here's the 80 lines of code.

package main

import (
        "fmt"
        "io"
        "io/ioutil"
        "net"
        "bytes"
        "os"
        "log"
)

var OUTPUT_FILE = os.Getenv("OUTPUT_FILE")
var SECRET_HASH = os.Getenv("SECRET_HASH")

func handleError(e error) {
        if e != nil {
                log.Fatal(e)
                panic(e)
        }
}

func printFromFile(connection net.Conn) {
        /* Read file */
        data, err := ioutil.ReadFile(OUTPUT_FILE)
        handleError(err)

        /* Close connection */
        io.WriteString(connection, string(data))
        connection.Close()
}

func invalidHashMessage(connection net.Conn) {
        io.WriteString(connection, fmt.Sprint("Invalid hash\n"))
}

func handleMessage(connection net.Conn) {
        buffer := make([]byte, 1024)

        reqLen, err := connection.Read(buffer)
        if reqLen == 0 {
                connection.Close()
                return
        }

        handleError(err)

        n := bytes.Index(buffer, []byte{0})
        message := string(buffer[:n-1])

        if message != SECRET_HASH {
                invalidHashMessage(connection)
                handleMessage(connection)
        } else {
                printFromFile(connection)
        }
}

func main() {

        if OUTPUT_FILE == "" || SECRET_HASH == "" {
                fmt.Print("You need to supply output file and hash to serve application\n")
                os.Exit(1)
        }

        /* Start listener */
        ln, err := net.Listen("tcp", ":9000")
        handleError(err)
        defer ln.Close()

        for {
                conn, err := ln.Accept()
                handleError(err)

                io.WriteString(conn, "Please type unique identifier:")
                go handleMessage(conn)
        }
}

So.. my questions are.

How would you handle concurrent connections? Making it real pretty. I have a certain feeling this could be improved upon, or is this way totally ok?
Am i formatting the message correctly (the file content) so that available clients/terminals that access this little application all works the same?
When i run this application through strace i get the following message which is saying that the port is already taken (?), but the application runs just fine. Trying to understand why strace outputs this.

 accept4(3, 0xc420051c00, [112], SOCK_CLOEXEC|SOCK_NONBLOCK) = -1 EAGAIN (Resource temporarily unavailable)


texts: SICP Exercise 1.3: Sum of squares of two largest numbers out of three, Prolog Version

texts:
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following:

  Exercise 1.3.  Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

My answer is this:

squareTwoLargest(X, Y, Z, R) :-
    ( X > Y -> A = X, B = Y ; A = Y, B = X ),
    R is A ^ 2 + max(B, Z) ^ 2.

My reason for learning Prolog is to understand the logic programming paradigm. So, how can I solve this exercise in good logic programming style?


texts: Session in Struts2 and Google App Engine

texts:
Im using Struts2 running in google app engine.

User can use their google and facebook account to login to the site. When a user login, i have:

session.put("email", email);

When a user log-out, I have

session.remove("email");

In Struts2 Action, I have the following:

public class ChapterAction extends ActionSupport implements SessionAware{

    private static final long serialVersionUID = 1L;
    private Map<String, Object> session;

    public Map<String, Object> getSession() {
        return session;
    }
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    public String add() throws Exception{
        String email = (String) session.get("email");
        if ( email == null)
            return LOGIN;

        //business logic here

        return SUCCESS;
    }
}

Please critic my code. Is the above usage of session OK and secure?

Thanks


texts: Read text file filled with numbers and tranfer to an array

texts:
This is my ProcessDataFileParallel.Java file. I'm taking numbers from a .txt file and putting it into an array in Java. While it works, I would like to improve the code and possibly change some algorithms to better alternatives.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class ProcessDataFileParallel {

public static void main(String[] args) throws IOException {
    int[] array = new int[100000];
    int index = 0;
    Scanner inputFile = null;
    Scanner scan = new Scanner(System.in);
    boolean running = false;

    String emptyString;
    FileReader file = new FileReader("dataset529.txt");
    BufferedReader br = new BufferedReader(file);
    emptyString = br.readLine();

    try {
        while ((emptyString = br.readLine()) != null) {
            array[index++] = Integer.parseInt(emptyString);

        }
    } finally {
        if (br.readLine() == null)
            br.close();
    }

    inputFile = new Scanner(file);

// Read File from Dataset529.txt
    if(inputFile != null){
        System.out.println("Number of integers in: "  + file);

        try{
            while (inputFile.hasNext() && inputFile.hasNextInt()){
                    array[index] = inputFile.nextInt();
                    index++;
                    inputFile.next();
                }

        }finally{
            inputFile.close();
        }

        // Print dataset529.txt to Array in Java with For Loop below.
        for (int ai = 0; ai < index; ai++){
            System.out.println("Array Index: " + "(" + ai + ")" + "== >" + " " + array[ai]);
        }

    System.out.println("How many Threads?");  // Scanner -  Ask user how many threads

    int n = scan.nextInt();  // Create variable 'n'  to handle whatever integer the user specifies.  nextInt() is used for the scanner to expect and Int.

    Thread[] myThreads = new Thread[n]; // Variable n placed here to determine how many Threads user wanted
    Worker[] workers = new Worker[n]; // Variable N placed here - the number user specified will determine # of workers.

    int range = array.length/n;  //divides the array into n threads (what scanner specifies)
    for (index = 0; index < n; index ++){
        int start = index*range;
        int end = start + range;
        workers[index] = new Worker(start,end, array);

    }

    for( index = 0; index < n; index++){
        myThreads[index] = new Thread(workers[index]);
        myThreads[index].start();
    }

    if (running){
         for (Thread t : myThreads) {
             if (t.isAlive()) {
                 running = true;
                 break;
             }
         }
     } while (running);

     for (Worker worker : workers) {
         System.out.println("Max = " + worker.getMax());
        }
     }

}
}

Worker class:

public class Worker implements Runnable {

            private int start;
            private int end;
            private int randomNumbers[];

            int max = Integer.MIN_VALUE;

            public Worker(int start, int end, int[] randomNumbers) {
                this.start = start;
                this.end = end;
                this.randomNumbers = randomNumbers;
            }

            public void run() {
                for (int index = start; index < end; index++) {

                    if (randomNumbers[index] >max)
                        max = randomNumbers[index];
                }
            }

            public int getMax() {
                return max;
            }

    }

Is there any way I can improve/condense my code?  Also, is there any way to possibly do alternatives that would be better?


texts:
I took it as a challenge to write a C++ program to find the first 10 amicable-number pairs.
Amicable numbers
Let's take 4. What are the proper divisors of 4?. They are 1 and 2. Their sum is 3.
Now let's do the same thing for the number 220. The sum of the proper divisors of 220 is 284.
The sum of proper divisors of the number 284 is 220.
If the sum of proper divisors of two numbers are equal to each other then they are amicable.
For example 284 and 220, whose proper factors sum to 220 and 284 respectively, are amicable.
This is my C++ program to find the first 10 amicable numbers.
#include<iostream>

int GetSumOfFactors(int num){
    int sum = 0;
    for(int i = 1;i < num/2+1;i++){
        if(num % i==0){
            sum+=i;
        }
    }
    return sum;
}
int main(){
    int sum_of_factors = 0;
    int counter = 0;
    int num = 0;
    for(;;){
        num++;
        sum_of_factors = GetSumOfFactors(num);
        if(num == sum_of_factors) continue;
        if (GetSumOfFactors(sum_of_factors) == num && num > sum_of_factors){
            std::cout << "Pair: " << num << " " << sum_of_factors << "\n";
            counter+=1;
        }
        if(counter == 10) break;
    }
    return 1;
}

To make sure I don't find the same pair twice, that means 220 to 284, just like 284 to 220, I keep an extra condition where the number should be greater than its sum of factors.
Output:
Pair: 284 220
Pair: 1210 1184
Pair: 2924 2620
Pair: 5564 5020
Pair: 6368 6232
Pair: 10856 10744
Pair: 14595 12285
Pair: 18416 17296
Pair: 66992 66928
Pair: 71145 67095

Process returned 1 (0x1)   execution time : 4.955 s
Press any key to continue.


texts: Cancelling an order with a side-effect of logging the operation

texts:
I have a data access layer method to cancel an order. This operation should have an associated "operation history" entry.

My first (naïve) implementation looks like this:

public void CancelOrder(int orderMastId, string reason)
{
    string order_id = orderMastId.ToString();
    var order = this.db.Commandes.Where(c => c.Order_Mast_Id == order_id);

    if (order == null || order.Count() == 0)
    {
        throw new EntityNotFoundException();
    }

    Parallel.ForEach(order, commande =>
        {
            string previousStatus = commande.Status;
            if (previousStatus != ShippingStatus.Printed)
            {
                // this is what marks the order as cancelled (legacy DB power!)
                commande.Status = ShippingStatus.Printed;

                // this table stores many operations on the order (status change, etc)
                var hist = new DB.Operations_History
                           {
                               Commande_id = commande.Commande_id,
                               Created_Date = DateTime.Now,
                               Feedback = reason,
                               Final_Shipper = string.Empty,
                               Final_Status = ShippingStatus.Printed,
                               Information = "API",
                               Initial_status = previousStatus,
                               Operation_id = 0,
                               Shipping_Info = string.Empty,
                               Shipping_Reference = string.Empty,
                               User_id = 0
                           };

                this.db.Operations_History.Add(hist);
            }
        });

    this.db.SaveChanges();
}

But this is a clear side-effect and in violation of single responsibility principle.

I'm guessing there exist a design pattern for this kind of thing, but I don't know which.

For instance, I could decide that the history entry is a kind of logging, and use (for instance) PostSharp attributes to "log" the history once the methods exits, but somehow that feels wrong, would create a whole logging structure only for operations on a single table, and might prove difficult: here the example history is very simple, but in reality there might be a bunch of rules on what to log and how exactly to log it (depending on what is logged and how, it's used differently).


texts:
I recently got to a certain exercise in a book I am reading, and am looking for feedback. It is a program in which the user picks a number and the computer uses algorithms to guess it. If there is any way that I can improve my code, feedback is really appreciated!

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(static_cast<unsigned int>(time(0))); //seed random number generator
    int compNumber = rand() % 100 + 1;

    int yourNumber;
    cout << "Please input a number between 1 and 100" << endl;
    cin >> yourNumber;

    cout << "Ok! I'm gonna try to guess it!" << endl;

    while (compNumber != yourNumber)
    {
        if (compNumber > yourNumber)
        {
            do
            {
                --compNumber;
            } while (compNumber != yourNumber);
        }

        else if (compNumber > yourNumber)
        {
            do
            {
                ++compNumber;
            } while (compNumber != yourNumber);
        }

    }

    cout << "I guessed it! Your number is " << compNumber << endl;

    return 0;

}


texts:
I have written a solution for two sum problem in variation. first is simple with two loops and another one is one loop and hash map.

But I wonder why the simple solution is faster than the efficent solution

simple solution -

func TwoSum(arr []int, s int) [][]int {
    var sum [][]int
    for i := 0; i < len(arr); i++ {
        for j := i + 1; j < len(arr); j++ {
            if arr[i]+arr[j] == s {
                sum = append(sum, []int{arr[i], arr[j]})
            }
        }
    }
    return sum
}

Hashmap solution -

func TwoSum1(nums []int, target int) [][]int {
    var r = make([][]int, 0)
    var m = make(map[int]int, 0)
    for p, i := range nums {
        j := target - i
        if pos, ok := m[j]; ok {
            if pos != p {
                r = append(r, []int{j, i})
            }
        } else {
            m[i] = p
        }
    }
    return r
}

also, I have written Benchmark

type args struct {
    arr []int
    s   int
}

var tests = []struct {
    name string
    args args
    want [][]int
}{
    {
        "One",
        args{[]int{3, 5, 2, -4, 8, 11},
            7,},
        [][]int{{5, 2}, {-4, 11}},
    },
}

func BenchmarkTwoSum(b *testing.B) {
    for i := 0; i < b.N; i++ {
        for _, tc := range tests{
            TwoSum(tc.args.arr, tc.args.s)
        }
    }
}

  BenchmarkTwoSum-4      3000000           382 ns/op

func BenchmarkTwoSum1(b *testing.B) {
        for i := 0; i < b.N; i++ {
            for _, tc := range tests{
                TwoSum1(tc.args.arr, tc.args.s)
            }
        }
    }

  BenchmarkTwoSum1-4     2000000           561 ns/op


texts:
I have a created small program that prints a sequence of prime numbers. Based on the origin code in here.

How can I improve this code?

#include <iostream>

template <std::size_t p, std::size_t i>
struct Run
{
    static const bool mValue = ((p % i) && Run<p, i - 1>::mValue);
};

template <std::size_t p>
struct Run<p, 1>
{
    static const bool mValue = true;
};

template <std::size_t i>
struct Prime
{
    Prime<i - 1> mPrime;
    static const bool mResult = Run<i, i - 1>::mValue;

    void print()
    {
        mPrime.print();

        if (mResult)
        {
            std::cout << "prime number: " << i << '\n';
        }
    }
};

template<>
struct Prime<1>
{
    static const bool mResult = false;

    void print()
    {
    }
};

int main()
{
    Prime<30> PrimeNumbers;
    PrimeNumbers.print();
}


texts:
I've implemented the Floyd Warshall algorithm in this problem.  However, as this is my first time in handling with adjacency list, I was not able to make it memory efficient.

I used a 1000*1000 and another list of 1000 size but I have seen solutions of people getting accepted with 100*100 size.  How can I make my graph array size less, or perhaps what is the best possible way to accept input in the adjacency list in graph?

P.S.: I tried using vector and map/pairs STL, but since I am not good in STL, I will be more than happy if a non STL solution is presented.

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
#define INF 1e9
int graph[1000][1000], m[1001], n;  //this is the array which I want to decrease
int main(){
    int u, v, flag=0, testCase = 1;
    while(scanf("%d%d", &u, &v), u||v){

        n = 0;
        memset(m, 0, sizeof(m));

        for(int i = 0; i < 1000; i++)
            for(int j=0; j<1000; j++)
            graph[i][j] = INF;

        if(!m[u])
        m[u] = ++n;

        if(!m[v])
        m[v] = ++n;

        graph[m[u]][m[v]] = 1;
        graph[m[u]][m[u]] = 0;
        graph[m[v]][m[v]] = 0;

        while(scanf("%d%d", &u, &v), u||v){
            if(!m[u])
            m[u] = ++n;

            if(!m[v])
            m[v] = ++n;

            graph[m[u]][m[v]] = 1;
            graph[m[u]][m[u]] = 0;
            graph[m[v]][m[v]] = 0;
        }

        for(int k = 1; k <= n; k++)
        for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);

        double s = 0.0;

        for(int i = 1; i <= n; i++)
        for(int j=1; j<=n; j++)
        s += graph[i][j];
        //cout<<s<<endl;
        s /= (double)n*(n-1);
        //cout<<s<<endl;
        printf("Case %d: average length between pages = %.3lf clicks\n",testCase++,s);
    }
    return 0;
    }

Running here


texts: Key-scanning macro in NASM Win16 against DOSBOX (Intel 8086)

texts:
Supports backspacing, but not wrapped backspacing.

%macro newline 0.nolist
    mov     ax, 0E0Dh
    int     10h
    mov     al, 0Ah
    int     10h
%endmacro

%macro getc 0.nolist
%%get:
    mov     ah, 11h
    int     16h        ; get keystroke status
    jnz     %%pressed
    hlt
    jmp     %%get
%%pressed:
    mov     ah, 10h
    int     16h        ; get the pressed key on "modern" keyboards
%endmacro

; %1 = string to write into
%macro scan 1
    pushaw
    mov     di, %1     ; prep for stosb
    xor     cx, cx
%%get:
    getc
    cmp     al, 13
    je      %%done     ; enter pressed
    cmp     al, 8
    je      %%bspace
    cmp     al, ' '
    jb      %%get      ; ignore most non-printing characters
    cmp     al, '~'
    ja      %%get

    push    bp
    mov     ah, 0Eh    ; print the valid character
    int     10h
    push    bp

    stosb              ; write the character to the string
    inc     cx
    cmp     cx, 80     ; ensure the buffer isn't exceeded
    jae     near %%done
    jmp     near %%get ; room for more
%%bspace:
    cmp     cx, 0
    je      %%get      ; ignore starting bspace

    push    bp
    mov     ax, 0E08h
    int     10h        ; bspace twice, to clear space
    mov     al, 32
    int     10h
    mov     al, 8
    int     10h
    pop     bp

    dec     di         ; overwrite character position
    dec     cx         ; step back a character
    jmp     %%get
%%done:
    xor     ax, ax
    stosb              ; append null-terminating character (zero)
    newline
    popaw
%endmacro


texts: Counting pairs that have a given difference in Java

texts:
You will be given an integer k and a list of integers. Count the number of distinct valid pair of integers (a,b) in the list for which a+k=b.

  For example, the array [1,1,1,2] has two different valid pairs:(1,1) and (1,2).
  Note that the three possible instances od pair (1,1) count as a single valid pair, as do the three possible instances of the pair (1,2). if k=1, then this means we have total of one 1 valid pair which satisfies a+k=b=>1+1=2, the pair (1,2).

My code:

public class PairArrayStream {

    public static void main(String[] args) {
        int k =1;
        List<Integer> input = Arrays.asList(1,1,1,2);
        HashSet<HashSet> hs = new HashSet<HashSet>();
        IntStream.range(0,  input.size())
        .forEach(i -> IntStream.range(0,  input.size())
            .filter(j -> i != j && input.get(i) - input.get(j) == k)
            .forEach(j -> {
                 HashSet inner = new HashSet<>();
                 inner.add(input.get(j));
                 inner.add(input.get(i));
                 hs.add(inner);
            })
    );
        System.out.println("OutPut "+hs.size());
}

}

Without java 8 features::

int k =1;
  List<Integer> input = Arrays.asList(1,1,1,2);
  HashSet<HashSet> hs = new HashSet<HashSet>();
   for(int i =0 ; i<numbers.size();i++){
       for(int j = i; j<numbers.size();j++){
           if(Math.abs(numbers.get(j)-numbers.get(i)) == k){
                HashSet inner = new HashSet<>();
                 inner.add(numbers.get(j));
                 inner.add(numbers.get(i));
                 hs.add(inner);
           }
       }
   }

Well, I am getting the correct output but 40% of the test cases gives me a timeout. Opinions and tactics are welcomed to make the code better and fast.


texts: Searching text, starring, flagging and joins

texts:
I have an interesting performance concern that I would like to address before it becomes a serious issue. I created a SQL Fiddle to demonstrate the query, and the explain statement can be seen on Depesz.

I have a collection phrases in different languages, and 'translations' that link phrase ids together (source and destination). The phrases can be searched by keyword in a particular source language, and find translations of that phrase in the destination language. The translations can also be starred and flagged, and the user id and translation id are held in respective tables for this functionality.

If a keyword and source language matches, those phrase ids are joined on the translations table; then, that set is joined on new_phrases again where the destination language matches. That set is also joined on favorite_translations and translation_flags, and if the user id matches in those sets, favorited and flagged are true, otherwise false.

SELECT P1.phrase_id as src_phrase_id,
        P1.author as src_author,
        P1.language as src_language,
        P1.text as src_text,
        P2.phrase_id as dst_phrase_id,
        P2.author as dst_author,
        P2.language as dst_language,
        P2.text as dst_text,
        P1.translation_id,
        P1.community_rating,
        CASE WHEN P1.favoriter_id = $1 THEN true
            ELSE false
            END
        as favorited,
        CASE WHEN P1.flagger_id = $1 THEN true
            ELSE false
            END
        as flagged
    FROM (
        SELECT P.phrase_id, P.author, P.language, P.text,
               T.translation_id, T.destination_id, T.community_rating,
               FT.user_id as favoriter_id, TF.user_id as flagger_id
        FROM new_phrases P
        INNER JOIN translations T ON P.phrase_id = T.source_id
        LEFT JOIN favorite_translations FT ON T.translation_id = FT.translation_id
        LEFT JOIN translation_flags TF ON T.translation_id = TF.translation_id
        WHERE P.tsv_text @@ plainto_tsquery($2)
        AND P.language = $3
        AND T.destination_language = $4
        ORDER BY T.community_rating DESC
        OFFSET $5
        LIMIT 25
        ) P1, new_phrases P2
    WHERE P2.phrase_id = P1.destination_id;

My concern is that the growth of these tables is going to cause a crazy cost increase. I limited the result set of the search to 25, and it's paginated. However, I'm fairly certain the favorite_translations and translation_flags joins are being performed on the set before it is limited to 25, and I'm not sure how to work around that if that's actually the case. Perhaps I'm doing the LEFT JOINs in the wrong spot?

What can I do to improve the performance of this query? I have gone through 5 iterations of this query, improving it each time, but I feel that more can be done. I'm just not sure how.

One thing addressed in the comments is the LIMIT clause. The text search results should be limited to 25 before any other JOINs are performed. However, I'm not incredibly experienced with SQL, and I'm pretty sure that the 3 joins are done before the 25 result LIMIT is applied, causing a massive slow-down. This could be the primary source of improvement (but I don't know how, thus the question)!


texts: Updating positions of enemies every frame

texts:
I am making a game for Android using Java and libGdx. I have an ArrayList of enemies that are updated each frame. The update method for the enemy looks like this:

public void update(float delta){

    if (waypointIndex < waypointCount){
        waypoint = path.getPoints().get(waypointIndex);

        distanceToWaypointX = waypoint.getX() - getCenterX();
        distanceToWaypointY = waypoint.getY() - getCenterY();

        directionToWaypoint = (float) Math.atan2(distanceToWaypointY, distanceToWaypointX);
        setRotation((float) Math.toDegrees(directionToWaypoint) - 180);

        translationX = (float) (Math.cos(directionToWaypoint) * getMovementSpeed() * delta);
        translationY = (float) (Math.sin(directionToWaypoint) * getMovementSpeed() * delta);

        distanceToWaypoint = (float) Math.hypot(distanceToWaypointX, distanceToWaypointY);

        if (distanceToWaypoint <= 5){
            waypointIndex++;
        }

        distanceTraveled += Math.sqrt(Math.pow(translationX, 2) + Math.pow(translationY, 2));

        translate(translationX, translationY);

    }
}

This works OK, but with 100 enemies the FPS starts to dip into the low 50's. I would like to keep a consistent 60 FPS and I plan to have more than 100 enemies on the screen at a time. How can i improve this code to make it more efficient?


texts: Is this an elegant/accurate simulation of the Monty Hall problem?

texts:
I'm trying to simulate the Monty Hall problem, to statistically determine if there is any benefit to changing my choice after a door containing a goat is open (testing this guy's Monty Hall theory on YouTube).

So, does this manage to simulate it properly? (Just for the curious: Changing doors doesn't seem to have any benefit, but I want to make sure my simulator isn't flawed).  I also want style help, if possible!

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

#define DOOR_COUNT 3
#define TEST_COUNT 1000000

void InitRandom();
int RunTest(char change);
void RandomizeDoors();
int GetRandom(int floor, int roof);
void OpenGoatDoor (int choice);
int OtherDoor (int choice);
int ChoiceWasCar(int choice);

char doors[DOOR_COUNT+1];

int main (const char argc, const char **argv)
{
    int run[2], yes[2];
    InitRandom();

    run[0] = 0;
    run[1] = 0;
    yes[0] = 0;
    yes[1] = 0;
    // Control Group
    for (int i = 0; i < TEST_COUNT; i++ ) {
        run[0]++;
        yes[0] += RunTest(0);
    }
    for (int i = 0; i < TEST_COUNT; i++ ) {
        run[1]++;
        yes[1] += RunTest(1);
    }
    printf("Control Group:\n\t%d tests run\n\t%d yes.\n\n", run[0], yes[0]);
    printf("Other Group:\n\t%d tests run\n\t%d yes.\n\n", run[1], yes[1]);
}

void InitRandom()
{
    unsigned int iseed = (unsigned int)time(NULL);
    srand (iseed);
}

int RunTest(char change)
{
    RandomizeDoors();
    int choice = GetRandom(1, DOOR_COUNT);
    //printf("Choice is: %d\n", choice);
    OpenGoatDoor(choice);
    if (change) {
        choice = OtherDoor(choice);
    }
    return ChoiceWasCar(choice);
}

void RandomizeDoors()
{
    char n = GetRandom(1,DOOR_COUNT);
    for (int i = 0; i <= DOOR_COUNT; i++) {
        doors[i] = n == i ? 1 : 0;
        //printf("Door %d is %d\n", i, doors[i]);
    }
//  printf("\n");
}

int GetRandom(int floor, int roof)
{
    int n;
    n = (rand()%(roof-floor));
    n += floor;
    return n;
}

void OpenGoatDoor (int choice)
{
    int doorCur = GetRandom(1, DOOR_COUNT);
    while ( doors[doorCur] == 1 || doorCur == choice ) {
        if (doorCur > DOOR_COUNT) {
            doorCur = GetRandom(1, DOOR_COUNT);
        } else {
            doorCur++;
        }
    }
    //printf("Opened Door is %d\n", doorCur);
    doors[doorCur] = -1;
}

int OtherDoor (int choice)
{
    int doorCur = 1;
    while ( doorCur == choice || doors[doorCur] == -1 ) {
        doorCur++;
    }
    return doorCur;
}

int ChoiceWasCar(int choice)
{
    return doors[choice] == 1;
}


texts:
I have a part of code that is loading a dataset and normalizing property values to [0, 1]. My implementation is:

import pickle
import numpy as np

# -- load data
prop_1    = list(np.random.rand(10)*20)
prop_2    = list(np.random.rand(10)*10)
prop_3    = list(np.random.rand(10)*30)

# -- normalize
l_bound = []
l_bound.append(min(prop_1))
l_bound.append(min(prop_2))
l_bound.append(min(prop_3))
u_bound = []
u_bound.append(max(prop_1))
u_bound.append(max(prop_2))
u_bound.append(max(prop_3))

prop_1 = (np.array(prop_1) - l_bound[0]) / (u_bound[0] - l_bound[0])
prop_2 = (np.array(prop_2) - l_bound[1]) / (u_bound[1] - l_bound[1])
prop_3 = (np.array(prop_3) - l_bound[2]) / (u_bound[2] - l_bound[2])

However, the normalizing part of the code does not look graceful. Any suggestions on how to improve it? Can do this using a loop?


texts: MVC web app writing to file in a threadsafe way

texts:
This is as much a code design question as a code review.  I am adding some temporary code to my website to record search terms used.  For now I'm also storing a few other fields.  This is an evaluation and if we decide to use the data I will convert this to save to a db (or possibly a persisting Redis store?!).

So far I have added some very basic code to get going

@RequestMapping(value = "search", method = RequestMethod.GET)
public ModelAndView searchSite(HttpServletRequest request, HttpServletResponse response, Model model) {

    WriteToFile_Temp(searchRequestBean.getTerm(), "searchSite"
            , (request.getHeader("X-FORWARDED-FOR") == null) ? request.getRemoteAddr() : request.getHeader("X-FORWARDED-FOR"));

    clearSearchRequest(model);

    ...

which calls

private void WriteToFile_Temp(String searchTerm, String callingFunction, String caller) {

    String logToFolder = System.getProperty("log.dir") + "\\SearchHistory.log" ;

    try (BufferedWriter bw = new BufferedWriter(new FileWriter(logToFolder, true))) {

        String content = searchTerm + "," + callingFunction + "," + LocalDateTime.now().toString() + "," + callerIP + System.getProperty("line.separator");

        bw.write(content);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

This is clearly a quick 'get going' piece of code but I'm wondering what the simplest way to make this resilient might be.  Is it enough to follow the advice in this similar c# question (Writing to file in a thread safe manner) and do something like this

namespace test
{
  public class Writer
  {
    public string Filepath { get; set; }
    private static object locker = new Object();

    public void WriteToFile(StringBuilder text)
    {
        lock (locker)
        {
            using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
            using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
            {
                writer.Write(text.ToString());
            }
        }

    }
  }
}

Or do you think I should be doing something more sophisticated.  I'm wondering for example whether, if and when I switch to a db model, although there will be less need to worry about concurrency, whether it would be worth firing off the write to file/db write on a different thread or whether, for such a small task, the overhead would be heavier than the task itself...

Apologies this is very open ended but I'm working on my own at the moment and any ideas, validation, criticism would be appreciated!


texts: Find all needles in the haystack and return their sum

texts:
This is based on a programming challenge I recently solved. However, since the writer of the challenge asked me not to disclose the question and/or it's answer, I modified it a little. If it doesn't make sense: my mistake.

The target is to find all numbers in a file and sum those. So if the following is found:

Sed ut 11 perspiciatis, unde omnis 11 iste natus 20 error sit

The result should be 42.

Floats like 0.42 will be considered equal to 42 in this challenge.

To generate example input, I took the revised version of my 'n x on the y' generator and made it run from 999. That's almost 5k lines of code, a nice amount to test against. The old code produces the same output, for those interested.

I was quite content with the performance. Now I'm wondering whether I could've written it better. Readability and maintainability are key, as usual.

The next iteration of this code will likely try to match keywords instead of arbitrary numbers. More on that in a later question.

haystack.py

# Sum all numbers in a haystack
import re

def getNumbers(inp):
    with open(inp, 'r') as f:
        return re.findall('[0-9]+', str(f.readlines()))

def calculateSum(results):
    total = 0
    for result in results:
        total += int(result)
    return total

def main(input_file='haystack.txt'):
    print calculateSum(getNumbers(input_file))

if __name__ == "__main__":
    main()


texts: Checking number of words in a string and assigning them to a value

texts:
I am learning Java and trying to write a program to check the number of words in a string and am trying append them to create username and email id. If the number of words in the name are 3 then the first name is the 1st word and last name is the 3rd word, where as when the number of works in the name are 2 the First name is the 1st word and the Last name is the 2nd word. To differentiate this I've used the IF condition. I just wanted to find out if the code is good enough or if there's a better way of doing it. Code is as below :

import java.io.*;

public class CreateUsername {
    public static void main(String[] args) throws IOException{

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Provide Name");
        String Username = br.readLine();

        char[] arr = Username.toCharArray();
        int i = 0;
        boolean notCounted = true;
        int counter = 0;
        while (i < arr.length)
        {
            if (arr[i] != ' ')
            {
                if (notCounted)
                {
                    notCounted = false;
                    counter++;
                }
            }
            else
            {
                notCounted = true;
            }
            i++;
        }
        System.out.println("words in the string are : " + counter);

        //Split the names and assign the Windows Username
        String FirstName = "";
        String firstLetterSurname = "";
        String Surname = "";
        String WindowsUsername = "";
        String EmailID = "";
        if(counter == 2)
        {
            System.out.println("Inside for count 2");
            FirstName = Username.split(" ")[0];
            Surname = Username.split(" ")[1];
            firstLetterSurname = String.valueOf(Surname.charAt(0));
            WindowsUsername = FirstName + "" + firstLetterSurname.toUpperCase();
            EmailID = FirstName + "." + Surname + "@test.com";
        }
        if(counter == 3)
        {
            FirstName = Username.split(" ")[0];
            Surname = Username.split(" ")[2];
            WindowsUsername = FirstName + "" + firstLetterSurname.toUpperCase() ;
            EmailID = FirstName + "." + Surname + "@test.com";
        }
        System.out.println("Windows Username is : " + WindowsUsername);
        System.out.println("Email ID is : " + EmailID);
    }
}


texts: Testing the same code with different input data

texts:
I would like to get an advice regarding how to test the same code with different input data.

I would like to test that method operationSucceeded will be invoked for all successful status codes. Here is how I can test (with Kiwi) single status code (i.e. 200):

it(@"should call operationSucceeded", ^{
    MKNetworkOperation *op =[[MKNetworkOperation alloc] initWithURLString:@"http://example.com/api" params:nil httpMethod:@"GET"];
    [op stub:@selector(notifyCache)];
    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:nil
                                                              statusCode:200
                                                             HTTPVersion:nil
                                                            headerFields:nil];
    [op stub:@selector(response) andReturn:response];
    [[op should] receive:@selector(operationSucceeded)];
    [op connectionDidFinishLoading:[NSURLConnection nullMock]];
});

For now I do next:

it(@"should call operationSucceeded", ^{
    NSArray *successCodes = @[@200, @201, @202, @203, @204, @205, @206];
    for (NSNumber *statusCode in successCodes) {
        MKNetworkOperation *op =[[MKNetworkOperation alloc] initWithURLString:@"http://example.com/api" params:nil httpMethod:@"GET"];
        [op stub:@selector(notifyCache)];
        NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:nil
                                                                  statusCode:[statusCode intValue]
                                                                 HTTPVersion:nil
                                                                headerFields:nil];
        [op stub:@selector(response) andReturn:response];
        [[op should] receive:@selector(operationSucceeded)];
        [op connectionDidFinishLoading:[NSURLConnection nullMock]];
    }
});

But the main problem here is that if my test fail for one of status codes it will say something like: "'Operation, should call operationSucceeded' [FAILED], expected subject to receive -operationSucceeded exactly 1 time, but received it 0 times" which is not very useful.

You can find full source code here.

Any advices are very welcome! =)


texts:
I have a class that I am using to generate 10 character alphanumeric 'tokens' (Strings) and writing them to a txt file.

I would like to be able to generate as many as possible as quickly as possible without producing any duplicates. This is what I have so far:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

public class TokenGenerator  {

  public static void main(String[] args) {

    for (;;) {
         getSaltString();
    }
 }

public static void getSaltString() {
    String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    StringBuilder salt = new StringBuilder();
    Random rnd = new Random();

    while (salt.length() < 10) { // length of the random string.
        int index = (int) (rnd.nextFloat() * SALTCHARS.length());
        salt.append(SALTCHARS.charAt(index));
    }
    String saltStr = salt.toString();
    writer(saltStr);
}

public static void writer(String code) {
    try {
        File file = new File("codes.txt");
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
        out.println(code);
        out.close();

    } catch (IOException e) {
       System.out.println("Dead");
    }
  }
}

I was wondering,

A: Is this an efficient way of generating the tokens?

B: How can I call this method using threads to generate them faster


texts:
I have written a function to multiply two numpy arrays.
def ra(self):
    """Multiply Rotation with initial Values"""
    rva = self.r_array() * self.va_array()
    rva = np.sum(rva, axis=1)  # Sum rows of Matrix
    rva = np.array([[rva[0]],  # Transpose Matrix
                    [rva[1]],
                    [rva[2]]])

where:

r_array has 3 rows and 3 columns
va_array has 3 rows and 1 column

I feel like this should be able to be written in one line. However, self.r_array() * self.va_array() always returns a 3 x 3 array.
Any suggestions would be greatly appreciated.
Cheers


texts: Replacing values in a file based on values in another file

texts:
I am writing Python code which reads through two text files and prints the output based on those two files. Basically, the first file, demo.txt, has a matrix of numbers and the second file, days.txt, has a value. Based on that value, many digits in the first file are replaced with the $, ?, or just a space.

Anyways, my code is working perfectly, but I would like to simplify it in a way that it is easier to understand for very new programmers. So you can break it into many parts, change the list comprehensions on line 17. Also, can we break up the with statement on line 12 as well?

def repl(ch,threshold):
    if ch.isdigit():
        if int(ch) < threshold:
            return '$'
        elif int(ch)> threshold:
            return " "
        else:
            return ch
    else:
        return '?'
lines = []
with open('data') as f, open("data.txt","r") as f2:
    threshold = int(f2.read().split('=')[-1])
    for line in f:
        line = line.strip()
        line = line.split()
        line = [repl(ch,threshold) for ch in line]
        lines.append(line)
    # reset to start of demo.txt
    f.seek(0)
    for line in f:
        print(line)

for line in lines:
    print()
    for el in line:
        print(el,end=" ")


texts:
I am required to create a bunch of object nodes to an object:

this.selectedText = e.text;
this.clipNo = e.clipNo;

if(!this.clipCollection.hasOwnProperty(this.category)) {
    this.clipCollection[this.category] = {};
}

if(!this.clipCollection.hasOwnProperty("grandClipCount")) {
    this.clipCollection.grandClipCount = 0;
}

if(!this.clipCollection[this.category].hasOwnProperty(['pageNo'+this.pageNumber])) {
    this.clipCollection[this.category]['pageNo'+this.pageNumber] = {};
    this.clipCollection[this.category]['pageNo'+this.pageNumber].pageServerInfo = this.pageServerInfo;
}

if(!this.clipCollection[this.category][this.category+"ClipCount"]) {
    this.clipCollection[this.category][this.category+"ClipCount"] = 0;
}

if(!this.clipCollection[this.category]['pageNo'+this.pageNumber].hasOwnProperty("clips")) {
    this.clipCollection[this.category]['pageNo'+this.pageNumber].clips = {};
    this.clipCollection[this.category]['pageNo'+this.pageNumber].clips['clip'+this.clipNo] = this.selectedText;
    this.clipCollection[this.category]['pageNo'+this.pageNumber].pageClipCount = 0;
}

this.clipCollection[this.category]['pageNo'+this.pageNumber].clips['clip'+this.clipNo] = this.selectedText;
this.clipCollection[this.category]['pageNo'+this.pageNumber].pageClipCount += 1;
this.clipCollection[this.category][this.category+"ClipCount"] += 1;
this.clipCollection.grandClipCount += 1;

Is there a short approach to minimize this code?


texts: Checking for balanced brackets in Python

texts:
I'm solving HackerRank "Stacks: Balanced Brackets" in Python.

  A bracket is considered to be any one of the following characters: (,
  ), {, }, [, or ].

  Two brackets are considered to be a matched pair if the an opening
  bracket (i.e., (, [, or {) occurs to the left of a closing bracket
  (i.e., ), ], or }) of the exact same type. There are three types of
  matched pairs of brackets: [], {}, and ().

  A matching pair of brackets is not balanced if the set of brackets it
  encloses are not matched. For example, {[(])} is not balanced because
  the contents in between { and } are not balanced. The pair of square
  brackets encloses a single, unbalanced opening bracket, (, and the
  pair of parentheses encloses a single, unbalanced closing square
  bracket, ].

  By this logic, we say a sequence of brackets is considered to be
  balanced if the following conditions are met:

  It contains no unmatched brackets. The subset of brackets enclosed
  within the confines of a matched pair of brackets is also a matched
  pair of brackets. Given  strings of brackets, determine whether each
  sequence of brackets is balanced. If a string is balanced, print YES
  on a new line; otherwise, print NO on a new line.

My code:

def is_matched(expression):
    if len(expression) % 2 != 0:
        return False

    opening = ("(", "[", "{")
    closing = (")", "]", "}")
    mapping = {opening[0]:closing[0],
               opening[1]:closing[1],
               opening[2]:closing[2]}

    if expression[0] in closing:
        return False

    if expression[-1] in opening:
        return False

    closing_queue = []
    for letter in expression:
        if letter in opening:
            closing_queue.append(mapping[letter])
        elif letter in closing:
            if not closing_queue:
                return False

            if closing_queue[-1] == letter:
                closing_queue.pop()
            else:
                return False

    return True

t = int(input().strip())
for a0 in range(t):
    expression = input().strip()
    if is_matched(expression) == True:
        print("YES")
    else:
        print("NO")

What could be improved here? What can be done to make my code more idiomatic (pythonic code)?

Is my implementation bad? Why is it?


texts:
As a Java native, I am always a little worried when doing Objective-C because of memory leaks and pointers flying at my head...

All comments are welcome on the Category below.  The Category functions are correct.

GitHub

#import "NSString+r47.h"

@implementation NSString (r47)
-(NSString *) r47String
{
    const char *_string = [self cStringUsingEncoding:NSASCIIStringEncoding];
    int stringLength = [self length];
    char newString[stringLength+1];
    int x;
    for( x=0; x<stringLength; x++ )
    {
        unsigned int aCharacter = _string[x];
        if( 0x20 < aCharacter && aCharacter < 0x7F ) // from ! to ~
            newString[x] = (((aCharacter - 0x21) + 0x2F) % 0x5E) + 0x21;
        else  // Not an r47 character
            newString[x] = aCharacter;
    }
    newString[x] = '\0';
    NSString *rotString = [NSString stringWithCString:newString encoding:NSASCIIStringEncoding];
    DLog(@"%@ = %@",self,rotString);
    return rotString ;
}

@end