texts: Parsing function for a server, using the Jansson library

texts:
I'm making a server in C that needs to parse JSON that follows oBIX protocol and I'm using the Jansson library for this. I've been programming in high level languages such as Java and C# for my entire career and the last time I touched C was way back in 7-8 years ago, so I'm mostly looking for guidance on writing C-style code.

Here's a sample JSON input from client to server:

{"obix":"obj","is":"obix:Request","rid":"1","children":[{"obix":"op","name":"add","is":"obix:Watch","children":[{"obix":"obj","is":"obix:WatchIn","children":[{"obix":"list","names":"hrefs","children":[{"obix":"uri","val":"/device/"}]}]}]}]}

So a function I have just needs to validate what kind of request the client is making. First, I write the following defines:

#define OBIX_REQUEST_INVALID -1
#define OBIX_REQUEST_WATCH 0
#define OBIX_REQUEST_UPDATE 1
....

Then in my callback function. I first validate whether it's a valid JSON input.

int callback_web_socket(struct libwebsocket_context * this,
                                   struct libwebsocket *wsi,
                                   enum libwebsocket_callback_reasons reason,
                                   void *user, void *in, size_t len)
{
    ....

    json_t *root;
    json_error_t error;

    root = json_loads(buf,0,&error);
    if (!root)
    {
         printf("\nInvalid JSON data.\n");
         break;
    }
    ....

If it's valid JSON, I call my parse function to determine request type

int request_type = obix_parse_request(root);
printf("\nRequest Type: %d\n", request_type);

And here's how my parse function looks like:

int obix_parse_request(const json_t *obix_root_obj) {
    json_t *obix_obj = json_object_get(obix_root_obj,"obix");

    if (!json_is_string(obix_obj) || strcmp(json_string_value(obix_obj),"obj") != 0) {
        return OBIX_REQUEST_INVALID;
    }

    json_t *first_child = json_object_get(obix_root_obj, "children");
    if (!first_child || !json_is_array(first_child)) {
        return OBIX_REQUEST_INVALID;
    }

    json_t *first_child_obj = json_array_get(first_child, 0);
    if (!first_child_obj || !json_is_object(first_child_obj)) {
        return OBIX_REQUEST_INVALID;
    }

    json_t *first_child_is_str = json_object_get(first_child_obj, "is");
    if (!first_child_is_str || !json_is_string(first_child_is_str)) {
        return OBIX_REQUEST_INVALID;
    }

    const unsigned char *request_type = json_string_value(first_child_is_str);
    if (strcmp(request_type, "obix:Watch") == 0) {
        return OBIX_REQUEST_WATCH;
    }

    ...
}

If I were coding in C#, this function would raise a huge red flag for lots of code duplication. But this is C, and I'm readily assuming the code duplication is part of my incompetency in C language.

How would you elegantly write this function? Aside from cleaning up the function, I'd like to hear some comments on my coding style.


texts: Converting Reverse Polish to Infix Notation in Java

texts:
I am trying to solve a programming challange that involves converting reverse polish notation to infix notation. For example: 1 3 + 2 4 5 - + / would be: ((1+3)/(2+(4-5))) My solution so far does work, but it's not fast enough. So I am looking for any optimization advice.

public class betteralgo {
    public static void main(String[] args) throws IOException {
        BufferedReader bi = new BufferedReader(new
        InputStreamReader(System.in));
        String line = bi.readLine();
        String[] input = line.split(" ");
        StringBuilder builder = new StringBuilder();
        Stack<String> stack = new Stack<String>();

        for(String e:input) {
            switch(e){
                case("+"):
                case("-"):
                case("*"):
                case("/"):
                    String i = stack.pop();
                    String k = stack.pop();
                    stack.push("(" + k + e + i + ")");
                break;
                default:
                    stack.push(e);
                }
            }
        System.out.println(stack.pop());
       }
    }


texts: Handling large amount s of ajax/POST commands

texts:
I'm currently creating a utility that is heavily AJAX orientated. I have a page called ajax.php which is handling all POST requests. It switches by the provided command, checks all the arguments exist then passes it off to the relevant class e.g.

case 'addperson':
    $name = $_POST['name'] ?? die('{"result":0, "data":"name not provided"}');
    $email = $_POST['email'] ?? die('{"result":0, "data":"email not provided"}');

    try {
        (new Person(new DB()))->addPerson($name, $email);
    }
    catch (Exception $e) {
        exit("{\"result\":0, \"data\":\"{$e->getMessage()}\"}");
    }
    exit('{"result":1}');

This works fine but was wondering how people generally go about handling big lists of $_POST arguments. Would you do the above, potentially have 20 lines of $arg = $_POST['arg'] or perhaps something like,

foreach (['name', 'state'] AS $arg) {
  $$arg = $_POST[$arg] ?? die("{\"result\":0, \"data\":\"$arg not provided\"}");
}

The other option is to not check it exists at all.

list($a, $b, $c) = [$_POST['a'], $_POST['b'], $_POST['c']];

Since I'm the only one working on this project, i can ensure i always provide the necessary data but this just seems bad and may create future issues (especially if I get a few helpers!)

Finally, what do you think about having the ajax.php confirm all arguments have been provided (not validated) rather than just checking for the command and passing off the $_POST array to a class which will then confirm all arguments have been provided?


texts:
I have a service with these methods:

Observable<User> getUsers();
Observable<Role> getUserRoles(String userId);

For each user, I want to get her roles and set them.

I have this method working:

private Observable<User> getUsersWithRoles() {
        return service.getUsers().flatMap(new Func1<User, Observable<User>>() {
            @Override
            public Observable<User> call(User user) {
                return Observable.combineLatest(Observable.just(user), service.getUserRoles(user).toList(), new Func2<User, List<Role>, User>() {
                    @Override
                    public User call(User user, List<Role> roles) {
                        user.setRoles(roles);
                        return user;
                    }
                });
            }
        });
    }

I don't like these parts so much:

Observable.just(user)
service.getUserRoles(user).toList()

Is there a cleaner way to build this Observable?


texts:
I was wondering about the Array built in methods in java 8. As there is no specific method other than Arrays.binarySearch. So for multidimensional array I wrote following method.
public int[] search(Integer[][] mat,int key)
    {
        int r=0,c=0;
        for(Integer[] a:mat)
        {
            if(Arrays.asList(a).contains(key)){
                c = Arrays.asList(a).indexOf(key);
                break;
            }
            else r++;
        }
        return new int[]{r+1,c+1};
    }

checking
 Integer[][] mat = {{1,2,3,99},{4,5,6,57},{7,8,9,89},{10,11,12,13}};
int [] rc = new int[2];
 rc = search(mat, 8);
 System.out.println(Arrays.toString(rc));
 rc = search(mat, 9);
 System.out.println(Arrays.toString(rc));
 rc = search(mat,10);
 System.out.println(Arrays.toString(rc));
 rc = search(mat, 1);
 System.out.println(Arrays.toString(rc));

output
[3, 2]
[3, 3]
[4, 1]
[1, 1]

I would like a review of efficiency and general code quality. Also any improvements I can do to make it better.


texts: Code to classify elements on np.array on lists


texts: PHP JPG image re-creation from original file

texts:
A third party can upload files via FTP to a client's webserver. These images should be displayed on a public-available webpage. The upload directory is not accessible via normal HTTP. To increase security I thought it might be a good idea to re-create the images and store it in the web-folder manually.

The import format is always JPG. The function will return the new filename if the image could be created or null otherwise.

Is there any way to improve it? Especially all the "early returns" look kind of ugly.

function processImage($filename, $importPath, $storagePath, $quality = 80) {
    $source = $importPath . $filename . '.jpg';
    $target = $filename . '_processed.jpg';
    $storage = $storagePath . $target;

    if (!file_exists($source)) {
        return null;
    }

    $image = imagecreatefromstring(file_get_contents($source));

    if (!$image) {
        return null;
    }

    $dimension = [
        imagesx($image),
        imagesy($image)
    ];

    $newImage = imagecreatetruecolor($dimension[0], $dimension[1]);

    if (!$newImage) {
        return null;
    }

    if (!imagecopyresampled($newImage, $image, 0, 0, 0, 0, $dimension[0], $dimension[1], $dimension[0], $dimension[1])) {
        return null;
    }

    if (!imagejpeg($newImage, $storage, $quality)) {
        return null;
    }

    return $target;
}

PS: The filename is available without the extension .jpg as a string. In case you worry about the first line.


texts: "Histogram of Oriented Gradients" (HOG) feature detector for computer vision

texts:
Here is a function that I've only slightly modified from its original context, found here.

Before mentioning anything else, it should be noted that I'm desperately trying to optimize this code for speed.  It presently takes about 5.25 seconds to execute and it appears as though the bottleneck is happening in the for-loop.

In a nutshell, this function expects the user to have SimpleCV installed and expects, at a minimum, to be passed a SimpleCV.Image instance.

Does anybody have some clever approach for speeding things up?  Ideally I'd be able to run this on a real-time webcam feed at 30 frames-per-second, but I'm not getting my hopes up.

from itertools import product
from math import floor, pi
import numpy as np
import cv2  # opencv 2

def findHOGFeatures(img, n_divs=6, n_bins=6):
    """
    **SUMMARY**
    Get HOG(Histogram of Oriented Gradients) features from the image.

    **PARAMETERS**
    * *img*    - SimpleCV.Image instance
    * *n_divs* - the number of divisions(cells).
    * *n_divs* - the number of orientation bins.

    **RETURNS**
    Returns the HOG vector in a numpy array

    """
    # Size of HOG vector
    n_HOG = n_divs * n_divs * n_bins

    # Initialize output HOG vector
    # HOG = [0.0]*n_HOG
    HOG = np.zeros((n_HOG, 1))
    # Apply sobel on image to find x and y orientations of the image
    Icv = img.getNumpyCv2()
    Ix = cv2.Sobel(Icv, ddepth=cv.CV_32F, dx=1, dy=0, ksize=3)
    Iy = cv2.Sobel(Icv, ddepth=cv.CV_32F, dx=0, dy=1, ksize=3)

    Ix = Ix.transpose(1, 0, 2)
    Iy = Iy.transpose(1, 0, 2)
    cellx = img.width / n_divs  # width of each cell(division)
    celly = img.height / n_divs  # height of each cell(division)

    #Area of image
    img_area = img.height * img.width

    #Range of each bin
    BIN_RANGE = (2 * pi) / n_bins

    # m = 0
    angles = np.arctan2(Iy, Ix)
    magnit = ((Ix ** 2) + (Iy ** 2)) ** 0.5
    it = product(xrange(n_divs), xrange(n_divs), xrange(cellx), xrange(celly))
    for m, n, i, j in it:
        # grad value
        grad = magnit[m * cellx + i, n * celly + j][0]
        # normalized grad value
        norm_grad = grad / img_area
        # Orientation Angle
        angle = angles[m*cellx + i, n*celly+j][0]
        # (-pi,pi) to (0, 2*pi)
        if angle < 0:
            angle += 2 * pi
        nth_bin = floor(float(angle/BIN_RANGE))
        HOG[((m * n_divs + n) * n_bins + int(nth_bin))] += norm_grad

    return HOG.transpose()


texts: Extract numerics from matrix A with logical matrix B

texts:
I have a matrix A containing numeric values and a matrix B containing 0/1s:

A <- matrix(1:25, 5, 5)
B <- matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0), 5, 5)

A                             B
1    6   11   16   21         0    0    1    0    0
2    7   12   17   22         0    0    0    0    1
3    8   13   18   23         0    0    0    0    1
4    9   14   19   24         0    0    1    0    0
5   10   15   20   25         0    0    1    0    0

I want to extract the elements of A where B==1 in row order. The desired result is:

11 22 23 14 15

I've come up with two possible ways to do this:

#1
rowSums(A*B)

#2
t(A)[as.logical(t(B))]

It seems like there should be a better (more elegant or faster) way to do this...


texts: Simple octal reader macro in Common Lisp

texts:
As an exercise, I've implemented a simple reader macro in Common Lisp (using SBCL).  It converts Octal (unsigned integers only) into numbers.

Usage:

* #z1234

668

The code:

(defun oct-string-to-number
  (string)
  "Converts an octal string to a number.  Only digits from 0 - 7 are accepted; sign or decimal point symbols will cause oct-to-number to fail"
  (setq place 1)
  (setq result 0)
  (setq digits '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7))
  (loop for char across (reverse string)
    do
    (setq pos (position char digits))
    (setq result (+ result (* pos place)))
    (setq place (* 8 place)))
  result)

(defun slurp-octal-digits
  (stream)
  (setq string (make-array 0 :element-type 'character :fill-pointer 0 :adjustable t))
  "Slurps all digits from 0 - 7 from a stream into a string, stopping at EOF, no data, or a non-digit character."
  (setq digits '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7))
  (with-output-to-string (out)
             (loop do
                   (setq char (read-char stream))
                   (setq isnum nil)
                   (if char
                   (progn
                     (setq isnum (find char digits))
                     (if isnum
                     (vector-push-extend char string)
                       (unread-char char stream))))
                   while (not (eq nil isnum))))
  string)

(defun octal-string-transformer
  (stream subchar args)
  "Slurps an octal number from stream, and converts it to a number.  Number must be an unsigned integer."
  (setq oct-string (slurp-octal-digits stream))
  (oct-string-to-number oct-string))

;; Sets #z to call octal-string-transformer, so e.g. #z1234 will evaluate to 668.  Use #z as SBCL has #o already :-)
(set-dispatch-macro-character
 #\# #\z
 #'octal-string-transformer)

I'm quite new to Common Lisp, so I'd greatly appreciate feedback on everything: formatting, style, idiom, correctness :-)

Edited to add: Actually, the formatting in the pasted code snippet is rendered oddly; indentation that is present when I edit vanishes when I submit.  So maybe be a bit gentle with feedback about the formatting ;-)


texts:
There is a test of OO knowledge called Iffy Tractor. The task is to refactor the code and make it as much flexible as possible for the future modifications.

I have placed the code here.

It was taken from here.

This is a kind of a part of the game with a tractor unit, which receives the commands from user. So the possible modifications are:

add different types of Tractors
add more types of movements, available only to selected types of tractors
add some logging for each movement of the tractor

How would you go about refactoring this code? I am not asking for new code of course, just some basic explanation of your idea with a scheme of classes.

Here is my code as a solution too, please criticize it in a most cruel manner possible:

An evident thing is to replace the orientation string with the vectors, thus removing the if-blocks. I will not dwell on this.

So my interfaces look like this:

public interface Unit {
}
public interface Land {
    void positionUnit(Unit unit, Location location, Orientation orientation);
    Orientation getUnitOrientation(Unit unit);
    Location getUnitLocation(Unit unit);
}
public interface Landscape {
    boolean isAvailable(Location location);
}
public interface GameOperator {
    public void runCommand(String command, Unit unit);
}

How can I implement the command-movement transition inside the GameOperator?

A simple if-block which calculates new position of the tractor based on command string and then changes it inside the Land via setPosition(..).
Implementations of the Action interface. Create a new one for each command or "stamps" the existing one, taken from the pool with actual values, if no multithreading is expected.

public class Move implements Action {
    private Land land;
    private Unit unit;
    public Move(Unit unit, Land land) {
        this.land = land;
        this.unit = unit;
    }
    @Override
    public void evaluate() {
        Location oldLocation = land.getUnitLocation(unit);
        Orientation oldOrientation = land.getUnitOrientation(unit);
        Location newLocation = new Location(oldLocation.getX() + oldOrientation.getX(), oldLocation.getY() + oldOrientation.getY());
        land.positionUnit(unit, newLocation, oldOrientation);
    }
}


texts: Making an array whose elements are defined by a struct

texts:
This might be a basic question for C. I'm making a struct called check_t and I want to make an array whose elements are of type check_t. This array is called enqueued. The struct check_t contains an integer x and a lock (for multi-threading).

typedef struct _check_t{
  int x;
  pthread_mutex_t lock;
} check_t;

void *check_init(check_t *c)
  c->x = 0;
  pthread_mutex_init(&c->lock,NULL);
}

check_t **enqueued;
for(i=0;i<w*h;i++){
  enqueued[i] = (check_t *)malloc(sizeof(check_t));
  check_init(&enqueued[i]);
}

Mostly, I'm wondering if this is the correct way to make/allocate space for an array of check_ts.


texts:
It seems it could be written shorter. It's especially annoying when I have to do this in multiple languages, so the button labels will be different.

<button id="egyes" class="btn btn-danger">Hide</button>&nbsp;some text
<button id="kettes" class="btn btn-warning">Hide</button>&nbsp;other text
<button id="harmas" class="btn btn-info">Hide</button>&nbsp;some more text
<button id="otos" class="btn btn-success">Hide</button>&nbsp;last button
<button id="showall" class="btn">Show all</button>

<script>
            $(document).ready(function() {
                $("#egyes").click( function() {
                    $("div.progress-danger").parent().fadeToggle();
                    if ($(this).html() == "Show") {
                        $(this).html("Hide");
                    } else {
                        $(this).html("Show");
                    }
                });
                $("#kettes").click( function() {
                    $("div.progress-warning").parent().fadeToggle();
                    if ($(this).html() == "Show") {
                        $(this).html("Hide");
                    } else {
                        $(this).html("Show");
                    }
                });
                $("#harmas").click( function() {
                    $("div.progress-info").parent().fadeToggle();
                    if ($(this).html() == "Show") {
                        $(this).html("Hide");
                    } else {
                        $(this).html("Show");
                    }
                });
                $("#otos").click( function() {
                    $("div.progress-success").parent().fadeToggle();
                    if ($(this).html() == "Show") {
                        $(this).html("Hide");
                    } else {
                        $(this).html("Show");
                    }
                });
                $("#showall").click( function() {
                    $("div.container > div > div.progress").parent().fadeIn();
                });
            });
</script>


texts: Speeding up a length calculation for a QGIS plugin

texts:
In a QGIS 2.0 plugin for windows, I calculate length and update a field with the values. It works, but takes a lot of time. Execution for this part only takes about ten minutes. Can anyone suggest anything to speed things up?

def calculatelength(self):
    idx = self.resLayer.fieldNameIndex('Longueur')
    caps = self.resLayer.dataProvider().capabilities()
    features = self.resLayer.getFeatures()
    for feature in features:
        if caps & QgsVectorDataProvider.ChangeAttributeValues:
            fid = feature.id()
            flen = feature.geometry().length()
            attrs = {idx : flen}
            self.resLayer.dataProvider().changeAttributeValues({fid : attrs})


texts: Parsing HTML table into Pandas DataFrame

texts:
There is a text (link clickable) file with HTML table. The table is a bank statement. I'd like to parse it into pandas DataFrame. Is there a way to do it more gracefully? I've started to learn Python recently so there is a good chance you guys can give me a good advice.

from bs4 import BeautifulSoup
import pandas as pd
with open("sber2.txt", "r", encoding = "UTF8") as f:
    context = f.read()
    soup = BeautifulSoup(context, 'html.parser')

rows_dates = soup.find_all(attrs = {'data-bind':'momentDateText: date'})
rows_category = soup.find_all(attrs = {'data-bind' : 'text: categoryName'})
rows_comment = soup.find_all(attrs = {'data-bind' : 'text: comment'})
rows_money = soup.find_all(attrs = {'data-bind' : 'currencyText: nationalAmount'})

dic = {
    "dates" : [],
    "category" : [],
    "comment": [],
    "money" : []
    }
i = 0
while i < len(rows_dates):
    dic["dates"].append(rows_dates[i].text)
    dic["category"].append(rows_category[i].text)
    dic["comment"].append(rows_comment[i].text)
    dic["money"].append(rows_money[i].text)
    '''
    print(
        rows_dates[i].text, rows_category[i].text,
        rows_comment[i].text, rows_money[i].text)
    '''
    i += 1

df = pd.DataFrame(dic)
df.info()
print(df.head())

Output:

RangeIndex: 18 entries, 0 to 17
Data columns (total 4 columns):
category    18 non-null object
comment     18 non-null object
dates       18 non-null object
money       18 non-null object
dtypes: object(4)
memory usage: 656.0+ bytes
       category                                   comment       dates    money
0  Supermarkets  PYATEROCHKA 1168         SAMARA       RU  28.12.2017  -456,85
1  Supermarkets  KARUSEL                  SAMARA       RU  26.12.2017  -710,78
2  Supermarkets  PYATEROCHKA 1168         SAMARA       RU  24.12.2017  -800,24
3  Supermarkets  AUCHAN SAMARA IKEA       SAMARA       RU  19.12.2017  -154,38
4  Supermarkets  PYATEROCHKA 9481         SAMARA       RU  16.12.2017  -188,80


texts: Unwrapping optionals for max of a 2D array in swift

texts:
I'm working in swift and I've got a custom class Array2D to handle fixed-width, two-dimensional arrays of integers. What I'm trying to do is write a simple, ideally-elegant function max() -> Int? to behave the same way as for a 1-D array: return nil if the array is empty, or else the maximum value in the array. I make no promises about the array contents being positive.

For the sake of simplicity, I'm writing these functions as freestanding rather than parts of a class here.

Broadly speaking, I'm trying to do this:

func max(array: [[Int]]) -> Int? {
  set up a variable for maximum value maxSoFar
  for row in array {
    if row.max() > maxSoFar { maxSoFar = row.max() }
  }
  return maxSoFar
}

What I'm struggling with is avoiding lots of nested optional handling: I have to handle the Int? returned by max for each row of the array, and it looks like I'll need maxSoFar to be an Int? as well, since I don't want to initialize it to zero since all the entries in the array could be negative.

So, a few options:

func max1(array: [[Int]]) -> Int? {
  if array.count == 0 || array[0].count == 0 { return nil }
  var maxval: Int = array[0][0]
  for row in array {
    if let rowmax = row.max() {
      if rowmax > maxval { maxval = rowmax }
    }
  }
  return maxval
}

func max2(array: [[Int]]) -> Int? {
   var maxval: Int?
   for row in array {
     guard let rowmax = row.max() else {
       return nil
     }
     guard let temp = maxval else {
       maxval = rowmax
       continue
     }
     if rowmax > temp {
        maxval = rowmax
     }
    }
    return maxval

Thoughts? Alternatives? I'd be delighted to learn a better way to handle this.


texts:
var argon2 = require('argon2')
var nano = require('nano')('http://127.0.0.1:5984')

var users = nano.db.use('users')

var private = {
  generateHash: (password, callback) => {
    argon2.generateSalt().then((salt) => {
      argon2.hash(password, salt).then((hash) => {
        callback(hash)
      })
    })
  }
}

var public = {
  register: (username, password, callback) => {
    var calledback = false
    users.list((error, body) => {
      if (error) {
        calledback = true
        callback('dbError')
      } else {
        body.rows.forEach((value) => {
          if (value.id === username) {
            calledback = true
            callback('userExists')
          }
        })
      }
      if (!calledback) {
        private.generateHash(password, (hash) => {
          users.insert({
            _id: username,
            hash: hash
          }, (error) => {
            if (error) {
              calledback = true
              callback('dbError')
            } else {
              calledback = true
              callback(false)
            }
          })
        })
      }
    })
  }
}

module.exports = public

I made a function for registrating a user in a CouchDB database. How could I make the code more readable?


texts: Handling HTTP status messages and multiple returns

texts:
I am new to Python and have written a function which calls an API and does some processing. Please review the code and explain what is the right and pythonic way.

def fetch_storedetails(api_link, zone_id, latitude, longitude):
    """

    :param api_link:
    :param zone_id:
    :param latitude:
    :param longitude:
    :return:
    """
    import requests
    store_details = requests.get(
        api_link + '/' + str(zone_id) + '/' + str(0) + '/' + str(latitude) + '/' + str(longitude),
        headers={'language': 'en'})
    print(store_details, store_details)
    print(store_details.json)
    s_details = store_details.json()
    if store_details.status_code == 400:
        return "'Sorry , we do not deliver to your selected address at this moment as it’s out of delivery reach."
    elif store_details.status_code == 404:
        return "Stores are not available in your location"
    elif store_details.status_code == 500:
        return "Internal server error"
    else:

        print(s_details)
        store_name = []
        store_address = []
        banner_image = []
        store_rating = []
        store_id = []

        for i in s_details['data']:
            store_name.append(i['businessName'])
            store_address.append(i['storeAddr'])
            banner_image.append(i['bannerLogos']['bannerimage'])
            store_rating.append(i['businessRating'])
            store_id.append(i['businessId'])

    return store_name, store_address, banner_image, store_rating, store_id


texts: Invoking function stored in a struct using Rust

texts:
I'm new to Rust, and I'm writing a basic command line input parser as a learning exercise. Commands entered on the command line are evaluated using the Cmd struct which contains the name of the command and a function to call when invoked. Though the code works, I find the use of the get_invocation function to be a little weird.

pub struct Cmd<T: FnMut()> {
    name: String,
    invocation: T,
}

impl<T: FnMut()> Cmd<T> {
    pub fn new(name: &str, invocation: T) -> Cmd<T> {
        Cmd {
            name: String::from(name),
            invocation,
        }
    }

    pub fn invoke(self) {
        self.get_invocation()();
    }

    fn get_invocation(self) -> T {
        self.invocation
    }
}

I am aware that I could use (self.invocation)() to directly call my struct function in invoke(), but that would involve setting the invoke self parameter to mutable, which would require me to make each instance of Cmd mutable if I wish to use the invoke() function. This is something I would like to avoid as, conceptually, nothing in the struct is being mutated. Is there a less odd / more idiomatic way to deal with stored function invocation in Rust, while still maintaining immutability? I also would appreciate any other pointers/tips on my code.


texts:
I thought of this implementation, and I want to get feedback from you.. what design would you use for printing first 100 prime numbers?

I used the fact that, if the number is not divisible by any prime less than itself, it will be a new prime.

    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(2); // first prime 2 goes to our collection
    int count = list.size(); // count is our size it will be max 100
    int number = 3;  // first prime number after 2 is 3

    while ( count != 100 ) // we want first 100 prime
    {
        boolean isPrime = true; // we assume that the number is prime
        for ( int i = 0; i < list.size(); i++ )
        {
            if ( number % list.get(i) == 0 ) // we check for every less prime
                isPrime = false; // however, if it is divided by any other less prime, isPrime will be false

        }

        if ( isPrime ) // if it stays true, we will add it to our collection
        {
            list.add(number);
        }

        number++; // we try every number
        count = list.size(); // count equals size of collection at every turn

    }

    System.out.println(list);


texts:
Can anyone give me recommendations on how to improve my code?

using System;
namespace mybinsearch2
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int key = int.Parse(Console.ReadLine());
            int[] arr = new int[n];  int min = 0;int max = n - 1;
            int mid = min + (max - min) / 2;int temp;
            for (int i = 0; i <= n - 1; i++)
            {
                arr[i] = i *5;
            }
            while (true)
            {
                temp = arr[mid];
                if (arr[mid] == key)
                {
                    Console.WriteLine("Position is: " + mid); break;
                }
                else if (arr[mid] < key) min = mid;
                else max = mid;
                mid = min + (max - min) / 2;
                if(arr[mid]==temp)
                {
                    Console.WriteLine("Not Found"); break;
                }
            }

       }
    }
}


texts: Porting x86 assembly that is used to increment a value

texts:
I'm working on a port of some existing inline x86_64 assembly code to AArch64 compatible assembly and would appreciate the feedback. I'll post below the original x86 and my ported AArch64 code.

The purpose of the original x86 code is to increment a long/double value and handle overflow. My main concern is that due to differences in syntax between the two architectures, I may be missing a step in my AArch64 code that was present in x86.

x86 Assembly

__asm__(
            "incq (%0)\n\t"
            "jno  0f\n\t"
            "movl $0x0, (%0)\n\t"
            "movl $0x43e00000, 0x4(%0)\n\t"
            "movb %1, %c2(%0)\n"
            "0:"
            :
            : "r"(&op1->value),
              "n"(IS_DOUBLE),
              "n"(ZVAL_OFFSETOF_TYPE)
            : "cc");

AARch64 Assembly

__asm__(
            "add %0, %0, #1\n\t"
            "bvc  0f\n\t"
            "mov %0, #0x0\n\t"
            "ldr x3, [%0, 0x4]\n\t"
            "mov x3, #0x43e00000\n\t"
            "ldr x3, [%0, %c2]\n\t"
            "mov x3, %1\n\t"
            "0:"
            :
            : "r"(&op1->value),
              "n"(IS_DOUBLE),
              "n"(ZVAL_OFFSETOF_TYPE)
            : "cc",
              "x3");


texts: MySQL queries to select messages related to a user, using UNION vs. OR

texts:
I'm just wondering if there is any improvements that can be made on my queries, as i've looked around and posts are saying to use UNION ALL instead of OR but with the performance times it looking like the OR condition works out better.

Could anyone please give me some advise on improving my queries?

Using UNION ALL:

Time taken: Showing rows 0 - 1 (2 total, Query took 0.0016 seconds.)

(SELECT direct_message.*
       FROM `direct_message`
       INNER JOIN direct_message_thread ON direct_message_thread.chat_id = direct_message.id
       WHERE direct_message.recipient_id = '10896'
         AND direct_message.school_id = '1'
         AND direct_message_thread.school_id = direct_message.school_id
       GROUP BY direct_message.id
       ORDER BY direct_message_thread.inserted DESC)
    UNION ALL
      (SELECT direct_message.*
       FROM `direct_message`
       INNER JOIN direct_message_thread ON direct_message_thread.chat_id = direct_message.id
       WHERE direct_message.creator_id = '10896'
         AND direct_message.school_id = '1'
         AND direct_message_thread.school_id = direct_message.school_id
       GROUP BY direct_message.id
       ORDER BY direct_message_thread.inserted DESC)
    UNION ALL
      (SELECT direct_message.*
       FROM `direct_message`
       LEFT JOIN direct_message_group ON direct_message_group.chat_id = direct_message.id
       INNER JOIN direct_message_thread ON direct_message_thread.chat_id = direct_message.id
       WHERE direct_message_group.staff_id = '10896'
         AND direct_message.school_id = '1'
         AND direct_message_thread.school_id = direct_message.school_id
       GROUP BY direct_message.id
       ORDER BY direct_message_thread.inserted DESC)

EXPLAIN OF QUERY

Using OR:

Time taken: Showing rows 0 - 1 (2 total, Query took 0.0011 seconds.)

SELECT direct_message.*,
       IFNULL(direct_message_group.staff_id, 0) AS staff_id
FROM `direct_message`
LEFT JOIN direct_message_group ON direct_message_group.chat_id = direct_message.id
INNER JOIN direct_message_thread ON direct_message_thread.chat_id = direct_message.id
WHERE ((direct_message.recipient_id = '10896'
        OR direct_message.creator_id = '10896'
        OR (direct_message_group.staff_id = '10896'
            AND direct_message_group.active = '0')))
  AND direct_message.school_id = '1'
  AND direct_message_thread.school_id = direct_message.school_id
GROUP BY direct_message.id
ORDER BY direct_message_thread.inserted DESC
LIMIT 0,
      25

EXPLAIN OF QUERY


texts: Guard from the missing and invalid function params

texts:
Is there a nicer way to guard all the inputs against missing and invalid param(s)? A long list of if statement at the top seems so hard to read.

 deliveryForCategory(code, category, dateStart, dateEnd) {
    if (!code) {
      throw Error(ERROR_MISSING_CODE);
    }

    if (!category) {
      throw Error(ERROR_MISSING_CATEGORY);
    }

    if (!DELIVERY_CATEGORIES.has(category)) {
      throw Error(ERROR_INVALID_CATEGORY);
    }

    if (!dateStart || !dateEnd) {
      throw Error(ERROR_MISSING_DATETIME);
    }

    return get(
      `${URL_APP_BASE}/accounts/${code}/delivery/${category}/${dateStart}/${dateEnd}`
    );
  }


texts:
I've written some code for testing Gilbreath's conjecture in python (2.x). The conjecture was shown (in the 90s) to be true up to n=1012. My code uses the primesieve module to quickly generate primes and, by ignoring blocks of 0s and 2s, only calculates values in the array when necessary. However, it's quite slow; it makes heavy use of dictionary lookup, addition and deletion, and I expect would benefit from modification of this aspect.

def gilbreath(nMax):
    import primesieve
    def fill(D, j, k):
        if (j, k-1) not in D:
            fill(D, j, k-1)
        D[(j, k)] = abs(D[(j+1, k-1)]-D[(j, k-1)])
        # remove unneeded entries
        if (j-1, k) in D:
            del D[(j, k-1)]
        if (j+1, k) in D:
            del D[(j+1, k-1)]
    primes = primesieve.Iterator()
    D = {}
    depthLeft, depth, maxDepth, nDepth = -1, -1, -1, -1
    for n in xrange(1, nMax+1):
        D[(n, 0)] = int(primes.next_prime())
        j, k = n, 0
        while (D[(j, k)] > 2) or (k <= depthLeft):
            if D[(j, k)] > 2:
                depth = k
            j -= 1
            k += 1
            fill(D, j, k)
            if (j == 1) and D[(j, k)] > 1:
                print "conjecture false at n = %d" %n
        depthLeft = depth
        if depth > maxDepth:
            maxDepth, nDepth = depth, n
    print "max depth %d at n = %d of %d" %(maxDepth, nDepth, nMax)


texts: Tkinter application with multiple windows

texts:
I'm creating an application that requires multiple tkinter windows. The code below works the way how I want it to work, but I'm not sure if I'm doing it in the proper way.

The first window (and in this case, the main window as well) contains three buttons as of now, 1 label which acts as a title, and a treeview.

The "Add Member" button is the only button that has functionality as of now. When clicked, it will pop a new window. That said window contains label.

To sum it up, I would like to humbly ask if I'm doing it properly, or there is a better and more accurate way of writing this code.

class Application(tk.Frame):
    def __init__(self,parent,*args,**kwargs):
        tk.Frame.__init__(self,parent)
        self.parent = parent
        self.parent.title("Senior Citizen Association")

        ttk.Label(text="SENIOR CITIZEN ASSOCIATION").grid(row=0,column=0,columnspan=5,sticky="n")
        ttk.Button(text="Add",command=self.add_member).grid(row=1,column=0,sticky="w")
        ttk.Button(text="Delete").grid(row=2,column=0,sticky="w")
        ttk.Button(text="Exit",command=lambda:self.parent.destroy()).grid(row=3,column=2,sticky="se")

        self.tree = ttk.Treeview(height=15,column=("First Name","Middle Initial","Last Name"))
        self.tree.heading("#0",text="First Name",anchor="w")
        self.tree.heading("#1",text="Middle Initial",anchor="w")
        self.tree.heading("#2",text="Last Name",anchor="w")
        self.tree.heading("#3",text="Status",anchor="w")
        self.tree.grid(row=1,column=1,rowspan=2,columnspan=2,sticky="nsew")

    def add_member(self):
        self.addMemberWindow = tk.Toplevel(self.parent)
        self.addClass = NewMember(self.parent,self.addMemberWindow)

class NewMember(tk.Frame):
    def __init__(self,parent,child,*args,**kwargs):
        tk.Frame.__init__(self,child)
        self.parent = parent
        self.child = child
        self.child.title("Add Member")

        ttk.Label(self.child,text="Add Member").grid(row=0,column=0,sticky="nsew")

if __name__ == "__main__":
    app = tk.Tk()
    Application(app)
    app.mainloop()


texts: Automatically select the table rows between two selected rows

texts:
The code is to check the rows in a table. If in a table two non consecutive rows are checked then all the in between rows should be selected by itself. Also, after selecting two rows, on selection of third row it should throw an error.

How can I simplify this code?

onSelectionChange: function(oEvent) {
        var aIndex = [];
        var k = 0;
        var z = 0;
        var sItem;
        var sContext;
        var vMatched;
        if (oEvent.getParameters().listItems[0].getSelected() === true) {
            if (oEvent.getParameters().selectAll === true) {
                for (var a = 0; a < this.getView().byId("monTable").getItems().length; a++) {
                    aIndex.push(a);
                }
            } else {
                for (k = 0; k < this.getView().byId("monTable").getItems().length; k++) {
                    sItem = this.getView().byId("monTable").getItems()[k].getBindingContext().sPath;
                    for (z = 0; z < this.getView().byId("monTable").getSelectedContextPaths().length; z++) {
                        sContext = this.getView().byId("monTable").getSelectedContextPaths()[z];
                        if (sItem === sContext) {
                            aIndex.push(k);
                        }
                    }
                }
            }
        } else {
            for (k = 0; k < this.getView().byId("monTable").getItems().length; k++) {
                sItem = this.getView().byId("monTable").getItems()[k].getBindingContext().sPath;
                for (z = 0; z < this.getView().byId("monTable").getSelectedContextPaths().length; z++) {
                    sContext = this.getView().byId("monTable").getSelectedContextPaths()[z];
                    if (sItem) {
                        vMatched = k;
                    }
                }
            }
            if (oEvent.getParameters().selectAll === false && this.getView().byId("monTable").getSelectedContextPaths().length === 0) {
                aIndex.splice(0, aIndex.length);
            } else {
                for (var j = 0; j < aIndex.length; j++) {
                    if (aIndex[j] === vMatched) {
                        aIndex.splice(j, 1);
                    }
                }
            }
        }
        var maxValue = aIndex[0];
        var minValue = aIndex[0];
        for (var i = 0; i < aIndex.length; i++) {
            if (aIndex[i] > maxValue) {
                maxValue = aIndex[i];
            }
            if (aIndex[i] < minValue) {
                minValue = aIndex[i];
            }
        }
        if (maxValue - minValue > 1) {
            if (aIndex.length > 2 && aIndex.length !== this.getView().byId("monTable").getItems().length) {
                for (var y = minValue; y <= maxValue; y++) {
                    if (this.getView().byId("monTable").getItems()[y].getSelected() === false) {
                        var sText = this.getOwnerComponent().getModel("i18n").getResourceBundle().getText("msgTxtgapSelection");
                        var sTitle = this.getOwnerComponent().getModel("i18n").getResourceBundle().getText("msgTitleInf");
                        this.dynamicNoneMessage(sText, sTitle);
                        //MessageBox.show("Bitte wählen Sie eine Folge ohne Lücken");
                    }

                }

            } else {
                for (var m = minValue; m <= maxValue; m++) {
                    this.getView().byId("monTable").getItems()[m].setSelected(true);

                }

            }
        }
    }`


texts:
A few days ago I saw this question on Stack Overflow.

I have tried to make a little demo to show the speed advantage of using 64-bit memory operations compared to 32-bit ones. So I wrote this code:

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

#define MEGABYTES 1024 * 1024
#define MEMORY_SIZE 100
#define LOOPS_START 100
#define LOOPS_STOP 10001

int main (int argc, const char * argv[])
{
    clock_t start, stop;
    int64_t* big_pile = malloc(MEGABYTES * MEMORY_SIZE * sizeof(char));

    for (int loops = LOOPS_START; loops < LOOPS_STOP; loops += 100)
    {
        start = clock();

        for (int i = 0; i < loops; i++)
        {
            for (int pos = 0; pos < MEGABYTES * MEMORY_SIZE * sizeof(char) / sizeof(int64_t); pos++) {
                big_pile[pos] = big_pile[pos] ^ big_pile[pos];
            }
        }

        stop = clock();
        double elapsed = (double)(stop - start) / CLOCKS_PER_SEC * 1000;
        double average = elapsed / loops;
        printf("Loops:\t%i\tElapsed time:\t%f\tAverage:\t%f\n", loops, elapsed, average);
    }

    free(big_pile);
}

I compile it under XCode on a MacBook Air running OSX Lion. This allow me to change the build target to 32- or 64-bit. When I run the program (and verify that the program is actually running in the correct bit-mode) I see no real difference in time.

Is this the right way to measure performance difference between 32- and 64-bit?
Is XCode/the compiler playing tricks on me?
Is there anything else wrong?

Note Sorry for the C. C isn't my native tongue ;-)

Solution findings

Writing 100 MB memory executing in 64-bit mode using 64-bit integer pointers takes ~47 seconds. Exceuting in 32-bit mode using 64-bit integer pointers takes ~70 seconds. Executing in 32-bit mode using 32-bit integer pointers takes ~90 seconds.


texts: Evaluate parenthesis expression for correct nesting and matching parens

texts:
Please review this solution for matching parens for correctness and nesting.

def matchParens(pstring):
    plist = [l for l in pstring]
    newlist = []
    if plist[0] == ')' or plist.count('(') != plist.count(')') or plist[-1::] == '(':
        return False
    while len(plist) > 0:
        head, *tail = plist
        if head == '(':
            newlist.append(plist.pop(plist.index(head)))
            right = tail.index(')')
            if isinstance(right, int):
                newlist.append(plist.pop(right))
            else:
                return False
        else:
            return False
    return True


texts:
Routine to merge two linked lists together and return a new merged list. One optimization I can think of is passing by reference instead of value. Any other suggestions ? Is there a shorthand to make lines 4 and 5 single/shorter?

template<class t>
Linkedlist<t> merge(Linkedlist<t> firstList, Linkedlist<t> secondList) {

/*4*/   Node<int> * current = ( firstList.head->data < secondList.head->data ) ? firstList.head : secondList.head;
/*5*/   Node<int> * other = ( firstList.head->data > secondList.head->data ) ? firstList.head : secondList.head;

    Node<int> * oldOther = nullptr;
    Node<int> * oldNext = nullptr;

    while ( current && other ) {
        if ( current->next == nullptr || current->next->data > other->data ) {
            oldOther = other;
            oldNext = current->next;
            current->next = other;
            other = oldNext;
            current = oldOther;
        } else {
            current = current->next;
        }
    }

    return ( firstList.head->data < secondList.head->data ) ? firstList : secondList;
}


texts: Mean π: Archimedes vs. Gauss - π computation through generalized means

texts:
I've written this simplified code to compute Pi for educational/demonstration purposes.

These methods are based upon the generalized means: see a presentation on Pi and the AGM.

Archimedes' method gives linear convergence, which means you get two extra bits of precision per iteration.

Gauss's method gives quadratic convergence, which means your precision doubles every iteration.

One can wrap these methods in timers or print current results to see how they converge.

Archimedes' method could have been used to disprove a millennia of false claims about Pi. Alas, history.

import decimal

def pi_arc():
    """Archimedes c. ~230 B.C.E."""
    a, b = D(3).sqrt() / D(6), D(1) / D(3)
    pi = 0
    while True:
        an = (a + b) / 2
        b = (an * b).sqrt()
        a = an
        piold = pi
        pi = 2 / (a + b)
        if pi == piold:
            break
    return D(str(pi)[:-3])

def pi_agm():
    """Gauss AGM Method c. ~1800 A.D. """
    a, b, t = 1, D(0.5).sqrt(), 1 / D(2)
    p, pi, k = 2, 0, 0
    while True:
        an = (a + b) / 2
        b = (a * b).sqrt()
        t -= p * (a - an)**2
        a, p = an, 2**(k + 2)
        piold = pi
        pi = ((a + b)**2) / (2 * t)
        k += 1
        if pi == piold:
            break
    return D(str(pi)[:-3])

if __name__ == "__main__":
    prec = int(input('Precision for Pi: '))
    """Plus 3 for error"""
    decimal.getcontext().prec = prec + 3
    D = decimal.Decimal
    print(pi_arc())
    print(pi_agm())


texts:
Imagine a game of Checkers, but you can move left right up down instead of diagonally. I have made an array to store liberties (available moves) and use if statements to update if a checker can move there.

Checkers can share liberties:

So the little black squares are liberties.

Here's my ugly if statement to update:

function updateLiberties(x, y, color)
{
    liberties[x][y] = 'None';

    if (color == 'white')
    {
        if (liberties[x + 1][y] == 'clear')
        {
            liberties[x + 1][y] = color;
        }
        else if (liberties[x + 1][y] == 'black')
        {
            liberties[x + 1][y] = 'both';
        }

        if (liberties[x - 1][y] == 'clear')
        {
            liberties[x - 1][y] = color;
        }
        else if (liberties[x - 1][y] == 'black')
        {
            liberties[x - 1][y] = 'both';
        }

        if (liberties[x][y + 1] == 'clear')
        {
            liberties[x][y + 1] = color;
        }
        else if (liberties[x][y + 1] == 'black')
        {
            liberties[x][y + 1] = 'both';
        }

        if (liberties[x][y - 1] == 'clear')
        {
            liberties[x][y - 1] = color;
        }
        else if (liberties[x][y - 1] == 'black')
        {
            liberties[x][y - 1] = 'both';
        }
    }

    if (color == 'black')
    {
        if (liberties[x + 1][y] == 'clear')
        {
            liberties[x + 1][y] = color;
        }
        else if (liberties[x + 1][y] == 'white')
        {
            liberties[x + 1][y] = 'both';
        }

        if (liberties[x - 1][y] == 'clear')
        {
            liberties[x - 1][y] = color;
        }
        else if (liberties[x - 1][y] == 'white')
        {
            liberties[x - 1][y] = 'both';
        }

        if (liberties[x][y + 1] == 'clear')
        {
            liberties[x][y + 1] = color;
        }
        else if (liberties[x][y + 1] == 'white')
        {
            liberties[x][y + 1] = 'both';
        }

        if (liberties[x][y - 1] == 'clear')
        {
            liberties[x][y - 1] = color;
        }
        else if (liberties[x][y - 1] == 'white')
        {
            liberties[x][y - 1] = 'both';
        }
    }
}

So a liberty can either be None (a checker is on it), clear (nothing is on it), black, white or both.

Any chance I make this look a little neater?


texts:
This nests Google Maps Event Listener for click or drag. How should I refactor the last part where it reuses the function getAddressComponents()? If there are other parts to be refactored, please do offer suggestions.

  function getAddressComponents() {
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        clearValue();
        if (results[0]) {
          // Get address_components
          for (var i = 0; i < results[0].address_components.length; i++)
          {
            var addr = results[0].address_components[i];
            if (addr.types[0] == 'street_address')
              $('#spot_street_address').val(addr.long_name);
          }
        } else {
          alert('No results found. Please revise the address or adjust the map marker.');
        }
      }
    });
  }

  // Add drag listener to marker for reverse geocoding
  google.maps.event.addListener(marker, 'drag', function() {
    getAddressComponents();
  });

  // Add click listener to marker for reverse geocoding
  google.maps.event.addListener(map, 'click', function(event) {
    marker.setMap(null);
    addMarker(event.latLng);
    getAddressComponents();
    google.maps.event.addListener(marker, 'drag', function() {
      getAddressComponents();
    });
  });

The map will have existing marker, which is draggable and geocodable. But once I click on the map to create a marker (thus, removing the existing marker), that new marker as I drag it, can't be geocodable. That's why I have to nest the listener to get it working. What have I done wrong?


texts: Building complex sentences based on a data structure

texts:
I really do not like how bad this looks. It is not readable and I am not sure if I need the stacked map's. There are a lot of iterations going on here (map, join, replace) and performance is really important, please help :(

Input:

const alternatives = [
  "flex",
  "float",
  [
    "background-size",
    "background-image"
  ]
]

Expected Output:

'Consider using 'flex', 'float' or 'background-size' with 'background-image' instead.'

Working Code:

const result = `Consider using ${alternatives
                 .map((alternative) => {
                   return Array.isArray(alternative)
                     ? alternative.map((a) => `'${a}'`).join(' with ')
                     : `'${alternative}'`;
                 })
                 .join(', ')
                 .replace(/, ([^,]*)$/, ' or $1')} instead.`


texts:
For the below question picked from here:

  Write make_inverse_dict(d) that returns a new dictionary with the
  'inverse' mapping. The 'inverse' mapping of a dictionary d is a new
  dictionary that maps each of d's values to all keys in d that
  mapped to it. For instance:

>>> d1 = {'call': 3, 'me': 2, 'maybe': 3}
>>> d2 = make_inverse_dict(d1)
>>> d2  # note that we know nothing about the order of dictionaries
{3: ('maybe', 'call'), 2: ('me',)}

  The ordering of the tuple of keys doesn't matter, i.e., d2 could
  have instead been {3: ('call', 'maybe'), 2: ('me',)}.

Below is the solution:

d1 = {'me': 2, 'call': 3, 'may be': 3}

def make_inverse_dict(d1):
    d2 = {}
    for key in d1:
        if d2.get(d1[key]) == None:
           d2[d1[key]] = (key,)
        else:
            d2[d1[key]] += (key,)
    return d2

d2 = make_inverse_dict(d1)

Additionally this is the recursive solution:

d1 = {'me': 2, 'call': 3, 'may be': 3}
def isEmpty(dictionary):
    for element in dictionary:
        if element:
            return False
    return True

def make_inverse_dict_recur(d1):
    temp = {}
    def make_inverse_dict():
        if not isEmpty(d1):
            tup = d1.popitem()
            if temp.get(tup[1]) == None:
                temp[tup[1]] = (tup[0], )
            else:
                temp[tup[1]] += (tup[0], )
            make_inverse_dict()
    make_inverse_dict()
    return temp

d2 = make_inverse_dict_recur(d1.copy())

Can we improve these solutions?


texts: Updating necessary data using just one function

texts:
My objective is to update necessary data using one function instead of having different functions to update different fields. So, I've created one and I think this is not really elegant, efficient or secure. I would seriously like a review if possible.

Key.

    $data is an array.
    $data[0] = column to update.
    $data[1] = new data.
    $data[2] = username of the user.

Code:

public function handleUserDataUpdate($data) {
    if($userMapper->validate($data) === true) {
        $userMapper->update($data);
    } else {
        $errors['count'] = count($errors);
        return $errors;
    }
}

UserMapper Class Methods:

public function validate($data) {
    switch ($data[0]) {
        case 'rank':
            if(empty($data[1])) {
                $errors[] = "The rank field cannot be empty!";
            }
            if(count($errors) > 0) {
                return $errors;
            } else {
                return true;
            }
            break;
        case 'display_name':
            if(empty($data[1]) || strlen($data[1]) < 3 || strlen($data[1] > 20)) {
                $errors[] = "The display name should contain at least 3 to 20 characters";
            }
            if(count($errors) > 0) {
                return $errors;
            } else {
                return true;
            }
            break;
    }
}
public function update($data) {
    $sql = "UPDATE users SET " . $data[0] . "=? WHERE username=?";
    $query = $this->db->prepare($this->sql);
    $query->bind_param('ss', $data[1], $data[2]);
    $query->execute();
    $query->close();
}


texts:
I've written a function in Haskell for calculating the entropy of a collection.  I'd like feedback on how the function could be rewritten to be more flexible/reusable, and also how to profile the function and how it could be tuned and/or modified for better performance.

import Data.List (foldl1')

entropy :: [Int] -> Int -> Int -> Double
entropy itemFrequencies totalElements logarithmicBase =
  -(foldl1' (+) $ map (\p -> p * (logBase b p)) probabilities)
    where
      is = map fromIntegral itemFrequencies
      l  = fromIntegral totalElements
      b  = fromIntegral logarithmicBase
      probabilities = map (\i -> i / l) $ is

For some background, the Entropy calculation is a core function used in building decision trees.  For more complex datasets and decision trees, this function would get called very often.  I'm working on a sequential implementation of the ID3 algorithm, which this entropy function is a part of, that I will later make parallel/concurrent as a separate exercise, and then I will eventually also write implementations of ID3's descendants: C4.5 and C5.0.

Please respect my desire to struggle on my own with the concurrency/parallelism aspect of rewriting this code, I'm only interested in any sequential improvements I could make for performance and any refactoring that could be done to make this code easier to maintain and reuse.


texts: Finding the first non-repeating character in a string

texts:
Below is a problem I encountered during an online course. There are a lot of similar questions asked on this, but I couldn't find a solution there as well as I believe my specific issue is a bit different from the rest.

  Given a string s, find the first non-repeating character in the string
  If there is no such character print ‘@’.  You are required to complete the function

  Input Format:    String s

  Output Format: First non-repeating character or @

  You are supposed to implement char
  char FirstNonRepeatedchar(char* str, int len): which takes a pointer to input string str and length of the string(including ‘\0’). The function should return either the first non repeating character or ‘@’

  Input Constraint: All input characters will be either lower or upper case english alphabets.

   str[i]  [a,z][A,Z]

  There will not be any space in the input string.

 /************ Prefix Code Begins*******************/
 #include <iostream>
 #include <string>
using namespace std;

//function finds the first non-repeating character
 char FirstNonRepeatedchar(const char* , int);

int main(){

int len;
string line;
getline (cin, line);

len = int(line.length());

cout << FirstNonRepeatedchar(line.c_str(), len);

return 0;
}
/******************* Prefix Code Ends******************/

Also, note I cannot change anything in the prefix code above. I wrote 2 solutions: first one below is giving correct output.

char FirstNonRepeatedchar(const char* str, int len){
    int count[26]={0};
    for(int i=0;i<len;i++)
    {
        count[*(str+i)]++;
    }
    for(int i=0;i<len;i++)
    {
        if(count[*(str+i)]==1)
        return *(str+i);
    }
return '@';
}

The above solution iterates the string twice. So, I tried to improve the complexity by implementing it using a hash.

char FirstNonRepeatedchar(const char* str, int len){
int count[26]={0};
int j;

char c;
if(isupper(*str)==1)
{ c='A';
}
else
c='a';
for(int i=0;i<len;i++)
{   j=*(str+i)-c;
    if(count[j]<0)
    ;
    else if(count[j]==0)
    count[j]=i+1;

    else if(count[j]>0)
    count[j]=-i;

}
int min=len+1;
for(int i=0;i<26;i++)
{
    if(count[i]>0 && count[i]<min)
    min=count[i];

}
if(min==len+1)
return '@';
else
return *(str+min-1);
}

Is the second solution I gave the most optimized solution possible for this problem?


texts:
I need help making this code more efficient but still functions the same, such as by making it access the Twitter API fewer times. When I run this code for like 1 min, I get an error from Twitter saying that it exceeds limits.

List<Status> tweets = result.getTweets();

       for (Status tweet : tweets) {

            if(!(tweet.getUser().getScreenName().toString().equals("gh") || tweet.getUser().getScreenName().toString().equals("gh"))){

                boolean found = false;

                List<Status> Stats=  tw.getHomeTimeline();
                for (Status StatList : Stats) {

                    if(StatList.getTweetText().equals(tweet.getTweetText())){
                        found = true;
                        break;
                        try {
                            System.out.println(tweet.getUser().getScreenName() );

                            Thread.sleep(2000);
                        } catch(InterruptedException ex) {
                            Thread.currentThread().interrupt();
                        }
                    }else{
                        // nothing here
                    }
                }
                if (found) // you can move this and the initialisation(boolean found = false) out side the upper if statement
                    System.out.println("false");
                else
                    System.out.println("turn");

            }else{
                System.out.println("blocked");
            }
        }


texts: Leetcode: divide without multiplication, division, and mod operator

texts:
I am new to this and would like to know some basic tips to make my coding more efficient, because on this question my code is obviously not efficient enough for the practice problem and I looked in the discussion and couldn't really find anything to help with this wall. (I am not a plagiarist)

The problem is from LeetCode Exercise 29. Divide 2 Integers:

  Divide two integers without using multiplication, division and mod operator.

  If it is overflow, return MAX_INT.

Here is the code

   //I know I am going to use only standard libraries and don't plan on any //name collisions
    using namespace std;

    class Solution {
    public:
        long long int divide(long long int dividend, long long int divisor) {
    //boolean that is used for negative numbers
        bool converted = false;
    //asnwer
        long long int count = 0;
    //if it brings up 0 then it would simply return 0
        if (divisor == 0) {
            cout<<count<<endl;
            return count;
        }
    //it's an attempt to handle over flow ,but the huge numbers are
    //still owning me
        if(divisor == 1)
            return dividend;
        if(dividend == INT_MIN && abs(divisor) == 1)
            return INT_MAX;

        while (dividend != 0) {
        //converting negitives to positive for simplicity of code
            if ((divisor < 0) && (dividend > 0)) {
                converted = true;
                divisor = -divisor;
            }
            else if ((divisor < 0) && (dividend < 0)){
                divisor = -divisor;
                dividend = -dividend;
            }
            else if ((divisor > 0) && (dividend < 0)){
                converted = true;
                dividend = -dividend;
            }
    //an attempt to try to get around this problem
            //if(dividend > 20000000000000000){
             //   dividend -= pow(divisor, 2);
             //   count += (pow(divisor, 2) - 1);
            //}
    //using subtraction to divide
            dividend -= divisor;
    //for calculation of remainders
            if (dividend < 0) {
                if (converted == true) {
                    cout<<-count<<" Remainder "<<dividend + divisor<<endl;
                    return -count;
                    break;
                }
                cout<<count<< " Remainder "<<dividend + divisor<<endl;
                return count;
                break;
            }
            count += 1;
        }
//converts negatives back to their negitive answer
        if (converted == true) {
            cout<<-count<<endl;
            return -count;
        }
        else{
//answer
            cout<<count<<endl;
            return count;
        }
    }
        };

I would love any help with this, since I would need to learn how to apply this to get better at programming.


texts:
I have the following script to reveal sections on a page if certain text in an  is clicked. How do I collapse all other sections if any one of them is selected and make it scalable for 20 items?

The following solution looks like it needs refactoring, and also when clicking icn_1, for instance, all other sections might already be hidden and putting an if for all sections for each click function seems very redundant.

$(document).ready(function() {
  $('section#1').hide();
  $('section#2').hide();
  $('section#3').hide();
  $('section#4').hide();

  function reveal1() {
  $("section#1").show("slow");
  $("section#2").hide("fast");
  $("section#3").hide("fast");
  $("section#4").hide("fast");
  }
  $(".icn_1").click(reveal1);

  function reveal2() {
  $("section#2").show("slow");
  $("section#1").hide("fast");
  $("section#3").hide("fast");
  $("section#4").hide("fast");
  }
  $(".icn_2").click(reveal2);

  function reveal3() {
  $("section#3").show("slow");
  $("section#1").hide("fast");
  $("section#2").hide("fast");
  $("section#4").hide("fast");
  }
  $(".icn_3").click(reveal3);

  function reveal4() {
  $("section#4").show("slow");
  $("section#1").hide("fast");
  $("section#2").hide("fast");
  $("section#3").hide("fast");
  }
  $(".icn_4").click(reveal4);
});


texts: Python script to demonstrate Fermat's Last Theorem, with option to restart

texts:
I am a beginner coder learning Python. This is a simple exercise from the thinkpython book. I would like to know if this circular referencing to restart the program the best way to do it. Also if you have other comments as to how to improve the code, please feel free to suggest.

def program_restart():
    print("Would you like to try again? ")
    prompt = input("type 'Y' to continue and 'N' to exit:\n")
    if prompt =="Y" or prompt == "y":
        user_input()
    return

def check_fermat(a,b,c,n):
    if a**n+b**n == c**n:
        print("Holy Smokes, Fermat was wrong!")
        print("---------------------------")
    else:
        print("No, that does not work!")
        print("---------------------------")
    program_restart()

def user_input():
    print("Let's see if Fermet was right. He claims that a^n+b^n=c^n cannot be True!")
    while True:
        try:
            a = int(input('Give a positive number bigger than 2 for "a":\n'))
        except ValueError:
            print ("Not a string, a number please.")
            continue

        if a > 2:
            a = int(a)
            break

    while True:
        try:
            b = int(input('Give a positive number bigger than 2 for "b":\n'))
        except ValueError:
            print ("Not a string, a number please.")
            continue

        if b > 2:
            b = int(b)
            break

    while True:
        try:
            c = int(input('Give a positive number bigger than 2 for "c":\n'))
        except ValueError:
            print ("Not a string, a number please.")
            continue

        if c > 2:
            c = int(c)
            break

    while True:
        try:
            n = int(input('Give a positive number for the exponent "n":\n'))
        except ValueError:
            print ("Not a string, a number please.")
            continue

        if n > 2:
            n = int(n)
            break

    check_fermat(a,b,c,n)

user_input()


texts: LeetCode: Intersection of two arrays ii C#

texts:
https://leetcode.com/problems/intersection-of-two-arrays-ii/

Please review for performance, I am having a problem with using TryGetValue, if someone can explain how this can be used in here.

  Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:

  Each element in the result should appear as many times as it shows in
  both arrays. The result can be in any order.

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/intersection-of-two-arrays-ii/
    /// </summary>
    [TestClass]
    public class IntersectionOfTwoArraysii
    {
        [TestMethod]
        public void IntersectionOfDouble2Test()
        {
            int[] nums1 = {1, 2, 2, 1};
            int[] nums2 = {2, 2};
            CollectionAssert.AreEqual(nums2, Intersect(nums1,nums2));
        }

        public int[] Intersect(int[] nums1, int[] nums2)
        {
            if (nums1.Length > nums2.Length)
            {
                return Intersect(nums2, nums1);
            }
            Dictionary<int, int> nums1Count = new Dictionary<int, int>();
            List<int> res = new List<int>();
            foreach (var num in nums1)
            {
                if (!nums1Count.ContainsKey(num))
                {
                    nums1Count.Add(num,1);
                }
                else
                {
                    nums1Count[num]++;
                }
            }

            foreach (var num in nums2)
            {
                if (nums1Count.ContainsKey(num) && nums1Count[num] > 0)
                {
                    res.Add(num);
                    nums1Count[num]--;
                }
            }

            return res.ToArray();
        }
    }
}


texts: Restructure of Express CORS middleware for unit test

texts:
How should one break this component down to better perform unit test on its behaviors?

Issues:

Authentication middleware component makes external request.
Must recognize preflight and final flight. (Exceptions)
Must verify path.
Only want to expose crossOriginRequest.

Please criticize anything you see wrong in logic and implementation!

EDITED: 3-28-16 @ 3:40pm PST

var httpErrors = require('./errors');
var authentication = require('./auth');

// CORS permission for paths.
var HEADERS = {
    "img": [
        "GET"
    ]
};

function _acceptsMethod(requestMethod, requestPath) {
    return HEADERS[requestPath].indexOf(requestMethod) >= 0;
};

function _getMethods(requestPath) {
    return HEADERS[requestPath].join();
};

function _getCorsRequest(req) {
    return {
        preflight: ("OPTIONS" == req.method),
        endpoint: (req.originalUrl.split('/')[2] || null)
    };
}

var crossOriginRequest = function(req, res, next) {
    if (req.headers['origin']) {
        req.cors = false;
        var cors = _getCorsRequest(req);

        // Access-Control-Allow-Origin needs to be set in preflight and flight.
        res.header('Access-Control-Allow-Origin', req.headers['origin']);
        if (cors.preflight && cors.endpoint) {
            if(!_acceptsMethod(req.headers["access-control-request-method"], cors.endpoint)){
                next(httpErrors.badRequest('Failed endpoint method requirments.'))
                return;
            }
            res.header('Access-Control-Allow-Methods', _getMethods(cors.endpoint));
            res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
        }

        if (!cors.preflight) {
            var auth = req.authentication = authentication.getAuthParameters(req);
            authentication.check(auth.endpoint, auth.auth, auth.cors)
                .then(function(user) {
                    user = JSON.parse(user);
                    if (user.data.cors) {
                        req.cors = true;
                        next();
                    } else {
                        next(httpErrors.forbidden('Access denied with CORS.', {
                            error: user.data.cors
                        }));
                        return;
                    }
                }).catch(function deniedAuth(err) {
                    next(httpErrors.forbidden('Access denied.', err));
                    return;
                }).done();
        } else {
            // Send empty body as to not overwrite "OK".
            res.status(200).send('');
        }
    } else {
        next();
    }
}

module.exports = crossOriginRequest;


texts: Arranging numbers in a circle such that the sums of neighbors and sums of diametric opposites are prime

texts:
I need to create a circle with numbers from 1 to n , however it is necessary to respect some rules:

  All numbers from 1 to n are used in the circle only once.
  The sum of two consecutive numbers is a prime number
  The sum of a number with what is diametrically opposite it is also a prime number

So I need to create an algorithm that receives an integer n
and determines whether there is a circle of size n, if it exists.

For example:

Program response: 1 6 7 16 15 8 5 12 11 18 13 10 3 4 9 14 17 2

I managed to get the expected result, but I do not know if I made the faster way, or if there is something badly written.

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JOptionPane;

public class QuintoDesafio {

    private static int j;
    private static int k;

    private static Vector primes  = new Vector();

    public static void main(String[] args)
    {

        long start = System.currentTimeMillis();

        ArrayList list = new ArrayList();

        primes.add( new Integer( 2 ) );
        primes.add( new Integer( 3 ) );
        primes.add( new Integer( 5 ) );
        primes.add( new Integer( 7 ) );
        primes.add( new Integer( 11 ) );
        primes.add( new Integer( 13 ) );
        primes.add( new Integer( 17 ) );
        primes.add( new Integer( 19 ) );
        primes.add( new Integer( 23 ) );
        primes.add( new Integer( 31 ) );
        primes.add( new Integer( 37 ) );
        primes.add( new Integer( 41 ) );

        String n = JOptionPane.showInputDialog( "Input n (even) ");
        int ene = Integer.parseInt( n );

        for ( int i=1; i <= ene; i++ ) {
            list.add( new Integer(i) );
        }
        exchange(list, 0);

        long end  = System.currentTimeMillis();
        System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end - start)));
    }

    static void exchange(ArrayList arr, int k){
        boolean passed = true;

        for(int i = k; i < arr.size(); i++){
            java.util.Collections.swap(arr, i, k);
            exchange(arr, k+1);
            java.util.Collections.swap(arr, k, i);
        }
        if (k == arr.size() -1){
            int half = arr.size()/2;

            for ( int j=0; j<arr.size(); j++ ) {
                int one = (int) arr.get(j);
                int two;
                if ( j+1 == arr.size() ) {
                    two = (int) arr.get(0);
                } else {
                    two = (int) arr.get(j+1);
                }
                Integer number_test = new Integer( one+two );
                if ( !primes.contains( number_test )) {
                    passed = false;
                }
            }

            for ( int j=0; j<half; j++ ) {
                int one = (int) arr.get(j);
                int two = (int) arr.get(j+half);
                Integer number_test = new Integer( one+two );
                if ( !primes.contains( number_test )) {
                    passed = false;
                }
            }
            if ( passed ) {
                System.out.println(java.util.Arrays.toString(arr.toArray()));
            }
        }
    }
}
```


texts:
I am going through the Coursera course  The Hardware/Software Interface and because it has already ended, I would not be able to get any feedback on the code.

The assignment is:

  LogicalShift: shift x to the right by n, using a logical shift. We can assume that 0 ≤ n ≤ 31.

I am wondering if shifting by n and then back by 1 is a good solution.

int logicalShift(int x, int n) {
  int ba = 1<<31; // set MSB to 1
    int a = x & ba; // MSB will be 1 if negative or 0 if positive number

    int numShifted = x>>n; //shift the number
    int msbShifted = (a >> n) << 1; //shift the MSB by n -1

    //if negative ^ the leading 1's to create a logical shift
    return msbShifted ^ numShifted;
}


texts:
I've made a prime number generator (for Project Euler).  It uses Euler's Sieve (a modified Sieve of Eratosthenes), with a mod 30 step.  I'd like to reduce the memory consumption to 4/15 what it currently is by keeping a boolean array only for the possibly prime remainders of 30.  I can't get it to work and also fear that this will slow down the program.

I've used

n[f/30*8+[zeroes, except 1,2,3,4,5,6,7 at 7,11,13,17,19,23,29][f%30]]

which seemed to not filter out any composite numbers.  How can I make this work and what other optimizations (aside from increasing the mod) can you suggest?  I need the primes up to about two billion.

//pes30.cxx
#include <vector>
#include <algorithm>
#ifndef _pes30_cxx_
#define _pes30_cxx_

typedef unsigned long long big;

const int offsets[]={6,4,2,4,2,4,6,2};

//fill a given vector with all primes under some value:
void sievePrimes(big max, std::vector<big> &p){
    big multiple;
    bool n[max];//array of whether or not each number is prime (30/8 too big!)
    p={2,3,5};//because the sieve skips all multiples of 2,3, and 5, start with them.
    for(big i=0; i<max; ++i)//initialize the array
        n[i]=true;
    //for every number marked prime less than max, mark its multiples with
    //    every number still marked prime over it as composite.
    for(big i=7, step=1; i<=max; i+=offsets[step], ++step==8?step=0:0){
        if(!n[i])//if i is not prime
            continue;
        p.push_back(i);//add i to the list of primes
        //finds every multiple of i and a (still marked) prime greater than i
        for(big j=i, step2=step; j<=max/i; j+=offsets[step2], ++step2==8?step2=0:0){
            if(!n[j])//skip nonprimes
                continue;
            multiple=j*i;//begin at i^2
            do{
                n[multiple]=false;
            }while((multiple*=j) <= max);
        }
    }
}
//test if a number is prime by searching a given list of primes for it:
inline bool isPrime(big n, std::vector<big> p){
    return std::binary_search(p.begin(), p.end(), n);
}
#endif

Note that this is a re-post with ... proper formatting, and while I appreciate  critiques of my coding style, I would also appreciate some advice about improving the array as well (storing only numbers n with n mod 30 prime or 1, but not 2, 3, or 5).


texts: C++ Grid gravity simulation opzimization (Kattis Falling Apples)

texts:
I have a solution for the Kattis Falling Apples problem (link).  The input is a grid of R rows (up to 50000) by C columns (up to 10).  At each timestep, apples (indicated by 'a') move down one cell into an empty space (denoted by .) or rest upon an obstacle (marked by #).

My solution exceeds time limit only at the last test case.  I'm thinking the while loop is the problem, but I have no idea what I could do to optimize it.

#include <iostream>

using namespace std;

int main()
{
    int r; // Grid rows
    int c; // Grid columns

    scanf("%d %d", &r, &c);

    char grid[r][c];

    // Establish grid
    for (int i = 0; i < r; i++) {
        char line[c];
        scanf("%s", &line);
        for (int j = 0; j < c; j++) {
            grid[i][j] = line[j];
        }
    }

    // Loop to change
    while (true) {
        bool change = false;

        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {

                if (grid[i][j] == 'a' && grid[i + 1][j] == '.') {
                    grid[i + 1][j] = 'a';
                    grid[i][j] = '.';
                    change = true;
                }

            }
        }

        if (!change) {
            break;
        }
    }

    // Print the grid
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            cout << grid[i][j];
        }
        printf("\n");
    }

    return 0;
}


texts: Depth First Search Using Stack in Python

texts:
I have implemented a depth first search using a stack (in a separate class). Any suggestions please on improvements for the below code:
class Stack:
    """(LIFO) queuing policy implemented using python list."""

    def __init__(self):
        self.list = []

    def push(self, item):
        """Push 'item' onto the stack."""
        self.list.append(item)

    def pop(self):
        """Pop the most recently pushed item from the stack."""
        return self.list.pop()

    def top(self):
        """Return the last element."""
        return self.list[-1]

    def is_empty(self):
        """Returns true if the stack is empty."""
        return len(self.list) == 0

def depth_first_search(graph, start):
    stack = Stack()
    stack.push(start)
    path = []

    while not stack.is_empty():
        vertex = stack.pop()
        if vertex in path:
            continue
        path.append(vertex)
        for neighbor in graph[vertex]:
            stack.push(neighbor)

    return path

def main():
    adjacency_matrix = {
        1: [2, 3],
        2: [4, 5],
        3: [5],
        4: [6],
        5: [6],
        6: [7],
        7: []
    }
    dfs_path = depth_first_search(adjacency_matrix, 1)
    print(dfs_path)

if __name__ == '__main__':
    main()


texts: Calls many stored dataframes, change them and combine them

texts:
I call many dataframes (using pickle), then I extract the interesting values of each one and finally combine them.  Is there a better way to do it? For example with a for loop  call them automatically instead of having to repeat the code many times?

#Dataframe 1
df_NB_E = pd.read_pickle('/Dataframes/Total Accuracy NB_E')

lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df_NB_E.index = pd.MultiIndex.from_product([lvl0, lvl1])

df_NB_E['Total Acc'] = df_NB_E.mean(axis=1).round(4)*100
df_NB_E=df_NB_E.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()

df_NB_E.rename(columns={'10x10':'NB_E'},inplace=True)

#Dataframe 2
df_LDA_E = pd.read_pickle('/Dataframes/Total Accuracy LDA_E')

lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df_LDA_E.index = pd.MultiIndex.from_product([lvl0, lvl1])

df_LDA_E['Total Acc'] = df_LDA_E.mean(axis=1).round(4)*100
df_LDA_E=df_LDA_E.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()

df_LDA_E.rename(columns={'10x10':'LDA_E'},inplace=True)

#Dataframe 3
df_DT_E = pd.read_pickle('/Dataframes/Total Accuracy DT_E')

lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df_DT_E.index = pd.MultiIndex.from_product([lvl0, lvl1])

df_DT_E['Total Acc'] = df_DT_E.mean(axis=1).round(4)*100
df_DT_E=df_DT_E.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()

df_DT_E.rename(columns={'10x10':'DT_E'},inplace=True)

#Dataframe 4
df_RF_E = pd.read_pickle('/Dataframes/Total Accuracy RF_E')

lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df_RF_E.index = pd.MultiIndex.from_product([lvl0, lvl1])

df_RF_E['Total Acc'] = df_RF_E.mean(axis=1).round(4)*100
df_RF_E=df_RF_E.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()

df_RF_E.rename(columns={'10x10':'RF_E'},inplace=True)

#Combining the 4 dataframes
pd.concat([df_NB_E, df_LDA_E, df_DT_E, df_RF_E], axis=1)


texts: Sample table-driven finite-state machine

texts:
We have interviewees write sample code, but now we want them to modify some simple working code. I came up with the following proposal, which is a syntax-directed interpreter implemented with a table-driven finite state machine. The interpreter simply accepts whitespace-delimited text and outputs "Hello" when it sees the case-insensitive command "HELLO". Any other input is an error.

This is a highly-simplified version of some C code converted to C# for the interview:

enum Lexeme
{
    Error,
    EOF,
    Whitespace,
    H, E, L, O
}

static Lexeme LexemeOfIntChar(int cIn)
{
    if (cIn < 0)
        return Lexeme.EOF;

    switch (Convert.ToChar(cIn))
    {
        case 'H':
        case 'h':
            return Lexeme.H;
        case 'E':
        case 'e':
            return Lexeme.E;
        case 'L':
        case 'l':
            return Lexeme.L;
        case 'O':
        case 'o':
            return Lexeme.O;
        case ' ':
        case '\t':
        case '\r':
        case '\n':
            return Lexeme.Whitespace;
        default:
            return Lexeme.Error;
    }
}

static void Main(string[] args)
{
    // Transition table.
    // Each row is a state, each column is the new state given the column lexeme.
    // State -1 is error. No need to define an Error row since we never transition from it.
    // State 7 is end. We never transition from this either.
    int[,] transition = {
      // Err,EOF, Ws,  H,  E,  L,  O       // Lexeme
        { -1,  7,  0,  1, -1, -1, -1 },    // 0 = Start
        { -1, -1, -1, -1,  2, -1, -1 },    // 1 = first H
        { -1, -1, -1, -1, -1,  3, -1 },    // 2 = first E
        { -1, -1, -1, -1, -1,  4, -1 },    // 3 = first L
        { -1, -1, -1, -1, -1, -1,  5 },    // 4 = second L
        { -1,  6,  6, -1, -1, -1, -1 },    // 5 = first O
        { -1,  7,  0,  1, -1, -1, -1 },    // 6 = 'HELLO'
    };

    int currentState = 0;   // 0 = Start
    while ((currentState >= 0) && (currentState != 7))
    {
        Lexeme t = LexemeOfIntChar(Console.Read());
        currentState = transition[currentState, (int)t];
        switch (currentState)
        {
            case -1: Console.WriteLine("Invalid character!"); break;
            case 6: Console.WriteLine("Hello"); break;  // 6 = saw 'HELLO' with terminal symbol
        }
    }
}

The proposed exercise is to extend this interpreter to accept a "HELP" command that will print out:

  "usage 'HelloScript <scriptfile'

This can be done in about a half-dozen changes.

A co-worker I asked this about was able to complete it in under 15 minutes, but wanted to argue about terminology, implementation, et al.

The intent is for it to be a simple exercise only to see if interviewees can understand and maintain existing code. How understandable and maintainable is it?


texts: Better way to template in simple coffee script

texts:
I am looking to see if there is a better way to refactor the creatMessage such that the logic of identifying message elements is outside the actual message formation itself..essentially get rid of if even before the message is being formatted..(a cleaner way not to mix logic with formatting)...Would it be possible?

variables = {
 "alpha" : "thomas"
}

prefix = "Mr"

meal = "Dinner"

favorites = [
 thomas: {
    food: chinese,
    drink: wine,
    dessert: cake
 }
]

createMessage = (variables, prefix, meal, cuisine) ->
  if not variables.alpha or not variables.alpha.length > 0
    "No alpha"
  message = ""
  message = message + "Alpha: @#{variables.alpha}"+"\n"
  if favorites[variables.alpha].food and favorites[variables.alpha].drink and favorites[variables.alpha].dessert
    message = message + "Favorites : #{favorites[variables.alpha].food} (#{favorites[variables.alpha].drink}) | #{(favorites[variables.alpha].dessert)}"
  else
    message = message + "No favorites"
  message = message + "\n"
  message = message + "#{prefix} #{variables.alpha} has ordered #{meal} of this #{cuisine} cuisine"
  message


texts:
I've got the following code in my calculator project:

private ITerm CalculatePostfixExpression(IEnumerable<ITerm> input)
{
    var tempResult = new Stack<ITerm>();
    foreach (var term in input)
    {
        if (term is IOperand)
        {
            tempResult.Push(term as IOperand);
        }
        if (term is IOperator)
        {
            tempResult.Push(ProceedOperation(term as IOperator, tempResult));
        }
    }
    return tempResult.Peek();
}

Now it's violating the open-closed principle, so I'm asking for a help to improve my code.

It's kinda like a "Replace Conditional with Polymorphism" but I can't understand how to use it in my case.


texts: Fastest way to count non-zero pixels using Python and Pillow

texts:
I have a Python script that creates a diff of two images using PIL. That part works fine. Now I need to find an efficient way to count all the non-black pixels (which represent parts of the two images that are different). The diff image is in RGB mode.

My initial cut was something like this:

return sum(x != (0, 0, 0) for x in diffimage.getdata())

Then I realized that the diffs were usually constrained to a portion of the image, so I used getbbox() to find the actual diff data:

bbox = diffimage.getbbox()
return sum(x != (0, 0, 0) for x in diffimage.crop(bbox).getdata()) if bbox else 0

This has the advantage of being VERY fast when the image is all black since bbox is None in that case and no pixel counting need be done.

I still wasn't satisfied, so I decided to try using more of the built-in PIL methods to avoid the generator expression with the Python conditional that needed to be evaluated for each pixel. I came up with:

bbox = diffimage.getbbox()
if not bbox: return 0
return sum(diffimage.crop(bbox)
                    .point(lambda x: 255 if x else 0)
                    .convert("L")
                    .point(bool)
                    .getdata())

This is about five times faster than the previous version. The basic steps are:

Crop to the bounding box to avoid counting black pixels
Convert all non-zero values in each channel to 255. This way, when we later convert it to grayscale, all non-black pixels are guaranteed to have non-zero values. (Because a pixel might differ in only one channel, and only by a small amount, some pixels that are not actually black might end up as black in grayscale mode, because only a fraction of that channel's value makes its way to grayscale.) BTW, the function isn't evaluated for each pixel but only once for each possible pixel value to make a lookup table, so it's very fast.
Convert to grayscale.
Convert all non-zero pixels to 1 using bool.
Sum all the pixel values.

Can I do better?


texts: Comparing an active record result with an array of object in a rspec test

texts:
Is the test flexible?

  describe "self.sort" do
    before(:each) do
      @tee = FactoryGirl.create :author, nickname: "tee jia hen", user: FactoryGirl.create(:user)
      @jon = FactoryGirl.create :author, nickname: "jon", user: FactoryGirl.create(:user)
      @tee_article1 = FactoryGirl.create :article, author: @tee, title: "3diablo"
      @tee_article2 = FactoryGirl.create :article, author: @tee, title: "1people"
      @jon_article = FactoryGirl.create :article, author:@jon, title: "2game"
    end

    it ", it should sort articles base on title" do
      Article.sort("title", "asc").should == [@tee_article2, @jon_article, @tee_article1]
    end

  end


texts: Speed up a monte carlo simulation with nested loop

texts:
I would like to know if there is a more efficiency way to speed up below code. It uses a procedure where subsampling is required in the nested loop (which a previous answer helped to make more efficient).

R has a tendency to hang when B=500, although computer OS isn't unduly affected. The goal is to run the below code with B=1000 and using larger m values(m=75, m=100, m=150)

I have detailed the procedure in the code below and included a link to a reproducible data set.

#Estimation of order m `leave one out' hyperbolic efficiency scores

#The procedure sequentially works through each observation in `IOs' and
#calculates a DEA order M efficiency score by leaving out the observation
# under investigation in the DEA reference set

# Step 1: Load the packages, create Inputs (x) and Outputs (y), choose
# m(the order of the partial frontier or reference set to be used in DEA)
# and B the number of monte carlo simulations of each m order DEA estimate

# Step 2: For each observations a in x, x1 and y1
#are create which 'leaves out' this observation.

# Step 3: From these matrices subsamples (xref, yref) of size [m,] are
# taken and used in DEA estimation.

# Step 4: The DEA estimation uses the m subsample from step 3
# as a reference set and evaluates the efficiency of the observation that
# has been 'left out'
#(thus the first two arguments in DEA are matrices of order [1,3] )

# Step 5: Steps 3 and 4 are repeated B times to obtain B simulations of the
# order m efficiency score and a mean and standard deviation are
# calculated and placed in effm.

# IOs data can be found here: https://dl.dropbox.com/u/1972975/IOs.txt
# From IOs an Input matrix (x[1376,3]) and an Output matrix (y[1376,3])
# are created.

library(Benchmarking)
x <- IOs[,1:3]
y<-IOs[,4:6]
A<-nrow(x)
effm <- matrix(nrow = A, ncol = 2)
m <- 50
B <- 500
pb <- txtProgressBar(min = 0,
                     max = A, style=3)

for(a in 1:A) {
  x1 <- x[-a,]
  y1 <- y[-a,]
  theta <- numeric(B)
  xynrow<-nrow(x1)
  mB<-m*B
  xrefm <- x1[sample(1:xynrow, mB, replace=TRUE),] # get all of your samples at once(https://stackoverflow.com/a/13629611/1176697)
  yrefm <- y1[sample(1:xynrow, mB, replace=TRUE),]
  deaX <- as.matrix(x[a,], ncol=3)
  deaY <-as.matrix(y[a,], ncol=3)

  for(i in 1:B){
    theta[i] <- dea(deaX, deaY, RTS = 'vrs', ORIENTATION = 'graph',
                    xrefm[(1:m) + (i-1) * m,], yrefm[(1:m) + (i-1) * m,], FAST=TRUE)
  }

  effm[a,1] <- mean(theta)
  effm[a,2] <- sd(theta) / sqrt(B)
  setTxtProgressBar(pb, a)
}
close(pb)


texts: Showing different forms for user type with Django/Python in views.py

texts:
I have 4 user account types, realtor, insurance broker, auto insurance agent, and mortgage broker. Each one of the users will have a different form for each to submit. I have the following in views.py to render the form:

def _get_form(profile, postdata=None):
    # @TODO - come up with a better solution to render forms on user types than this.
    form = None

    if profile.affiliate_type == UserProfile.INSURANCE_BROKER:
        if postdata:
            form = InsuranceBrokerForm(postdata, instance=profile)
        else:
            form = InsuranceBrokerForm(instance=profile)
    elif profile.affiliate_type == UserProfile.AUTO_DEALERSHIP:
        if postdata:
            form = AutoDealershipForm(postdata, instance=profile)
        else:
            form = AutoDealershipForm(instance=profile)
        form = AutoDealershipForm
    elif profile.affiliate_type == UserProfile.MORTGAGE_BROKER:
        if postdata:
            form = MortgageBrokerForm(postdata, instance=profile)
        else:
            form = MortgageBrokerForm(instance=profile)
    elif profile.affiliate_type == UserProfile.REALTOR:
        if postdata:
            form = RealtorForm(postdata, instance=profile)
        else:
            form = RealtorForm(instance=profile)
    return form

and it's being used like so:

@login_required
def affiliate_form(request, template_name="affiliates/affiliate_form.html"):
    user = request.user
    profile = get_object_or_404(UserProfile, user=user)
    form = _get_form(profile)
    if profile.user != user:
        return HttpResponseForbidden("Forbidden. Please try again.")
    if request.method == 'POST':
        postdata = request.POST.copy()
        form = _get_form(postdata)
        if form.is_valid():
            form.save()
            messages.success(request, 'Your lead has been created.')
            url = urlresolvers.reverse('affiliates')
            return redirect(url)
    else:
        form = _get_form(profile)

    return render(request, template_name, {
        'form': form
    })

As you can see, I am calling _get_form(profile) but this seems dirty. Is there a cleaner way to go about this?


texts: Using set for unordered, unique list of elements

texts:
In C++11 we have the option of using std::unordered_set if we require a list of elements that have no duplicates but order is not important.

In C++03 we don't have this options, although we can use the std::set to achieve something similar. Let's consider the following code:

std::set<ElementType, std::NotEqualTo<ElementType>> unorderedSet;
unorderedSet.insert(some_element);
unorderedSet.insert(other_element);
unorderedSet.insert(some_element);

//... more stuff with the set

This will, basically produce a set that will store the elements in the order they were inserted while preventing duplicates. Note that ElementType simply  can't  have less than or greater than operator. It doesn't make sense, semantically speaking.

Anyway, since I am using std::NotEqualTo instead of a LessThan functor, as it is requested by the set, I am not feeling very comfortable with this code. I do know that set is using something such as

if first element < second element
    //insert accordingly
else if second element < first element
    //insert accordingly
else
   //they are equal

but in the same time, theoretically, my code will be failing if the checks were more strict such as

if first element < second element AND !(second element < first element)
//...

My questions are:

There are any potentially problems that could arise from using this construct?
What other alternatives I have to achieve the same thing in a more readable form? I do not plan to write my own unordered set just for this scenario and can't really use any external libraries. Only standard library available in C++03.

Edit: I am unable to make use of "less than" operator between my elements. I can decide if they are equal or not but I can't say which one is smaller than other. With the default set functor the code won't even compile as "operator<" is not found. This is why I wanted to model the functor with equal operator in the first case.

I am also aware that it is not valid, however, the code will produce the desired results. From my understanding it will expand to something such as:

if first element != second element
    // place first element
else if second element != first element
    // this is buggy, but should never be executed; first condition will always be true, unless the elements are equal.
else
    //here the elements are equal .


texts: Pretty print uptime given seconds and omit unnecessary strings

texts:
Given an integer number of seconds, return a string which represents in human readable format the number of days/hours/minutes/seconds that are equivalent.

from datetime import datetime, timedelta

def GetTime(sec):
    d = datetime(1,1,1) + timedelta(seconds=sec)
    days = (d.day-1,'d',' ') if (d.day-1 > 0) else ('','','')
    hours = (d.hour, 'h', ' ') if (d.hour > 0) else ('', '', '')
    mins = (d.minute, 'm', ' ') if (d.minute > 0) else ('', '', '')
    secs = (d.second, 's', ' ') if (d.second > 0) else ('', '', '')
    time_format = days + hours + mins + secs
    format_str = '{}'*len(time_format)

    return format_str.format(*time_format)

I think there might be a better way to do the formatting to omit values that are zero instead of combining tuples and exploding them in the format string.