texts: Swift class to check ApplePencil reachability

texts:
I've implemented a class that lets you check out whether there is an ApplePencil connected to the device or not.

import Foundation
import CoreBluetooth

class ApplePencilReachability: NSObject {

    fileprivate let centralManager = CBCentralManager()

    var pencilReachabilityDidChangeClosure:((_ isAvailable: Bool) -> Void)?

    var isPencilReachable = false
    var timer: Timer?

    convenience init(didChangeClosure:@escaping ((_ isAvailable: Bool) -> Void)) {

        self.init()

        centralManager.delegate = self

        pencilReachabilityDidChangeClosure = didChangeClosure
    }

    @objc fileprivate func checkReachability() {

        let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [CBUUID(string: "180A")])
        let wasPencilReachable = isPencilReachable

        isPencilReachable = peripherals.contains(where: isApplePencil)

        if wasPencilReachable != isPencilReachable {

            pencilReachabilityDidChangeClosure?(isPencilReachable)
        }

        if isPencilReachable {

            timer?.invalidate()
        }
    }

    fileprivate func isApplePencil(peripheral: CBPeripheral) -> Bool {

        return peripheral.name == "Apple Pencil"
    }
}

// MARK: CBCentralManagerDelegate

extension ApplePencilReachability: CBCentralManagerDelegate {

    func centralManagerDidUpdateState(_ central: CBCentralManager) {

        if central.state == .poweredOn {

            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(checkReachability), userInfo: nil, repeats: true)
        }
        else {

            timer?.invalidate()

            pencilReachabilityDidChangeClosure?(false)
        }
    }
}

It really like to get some tipps to improve this class and make it more 'swifty', if possible :)

This class is also available open-source on Github so feel free to submit Pull-Requests for improvements :)

While writing this class I was inspired by HAS' answer on StackOverflow on this topic.


texts: Multithreaded telnet chat server in Java

texts:
I have writed a multithreaded telnet chat application in Java. In main method I run telnet server. In server class at run method I bind in specified port (8189) and I spawn listener threads for every client. In every client listener (MessageHandler class) I print welcome message, prompt user for nickname and I listen for messages in loop. Server.sendAll method propagates message in created telnet chat room at bound port. If user enter "BYE" message, then it parts chat room.

App.java:

package pl.hubot.dev.telnet_chat;

public class App {
    public static void main(String[] args) {
        Server.run();
    }
}

Server.java:

package pl.hubot.dev.telnet_chat;

import java.io.IOException;
//import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

class Server {
    static void run() {
        try {
            int i = 1;
            ServerSocket serverSocket = new ServerSocket(8189);
            //serverSocket.bind(new InetSocketAddress("192.168.1.2", 8189));

            while (true) {
                Socket incoming = serverSocket.accept();
                System.out.println("Spawning " + i);
                new MessageHandler(incoming);
                i++;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    static void sendAll(String message){
        for (MessageHandler handler : handlers) {
            handler.getOut().println(message);
        }
    }

    static List<MessageHandler> getHandlers() {
        return handlers;
    }

    private static List<MessageHandler> handlers = new ArrayList<MessageHandler>();
}

MessageHandler.java:

package pl.hubot.dev.telnet_chat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class MessageHandler extends Thread {
    MessageHandler(Socket incoming) {
        this.incoming = incoming;
        this.start();
    }

    @Override
    public void run() {
        try {
            try {
                Server.getHandlers().add(this);

                InputStream inputStream = incoming.getInputStream();
                OutputStream outputStream = incoming.getOutputStream();

                Scanner in = new Scanner(inputStream);
                out = new PrintWriter(outputStream, true /* autoFlush */);

                out.println("dev::hubot.pl - Telnet Chat Demo");

                out.println("Choose your nick:");
                String nick = "";
                nick = in.nextLine();

                out.println("Hello! Enter BYE to exit.");

                boolean done = false;
                while (!done && in.hasNextLine()) {
                    String line = in.nextLine();
                    Server.sendAll(nick + ": " + line);
                    if (line.trim().equals("BYE"))
                        done = true;
                }
//          } catch (InterruptedException ex) {

            } finally {
                incoming.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    PrintWriter getOut() {
        return out;
    }

    private Socket incoming;
    private PrintWriter out;
}


texts:
I am working on making it so I can move a Rectangle using my arrow keys but what I have currently isn't working.

I initially had it so the Rectangle moved on it's own when I started the program. It moves based on the values of xVelocity and yVelocity. When I change those to 0 the object is stationary (as expected). But when I make it so they are initially 0 and when you press an arrow key the velocity changes, the object doesn't move. Any help?

Here is my Main class, Shapes. I have the keyListener in here print out the Velocity value when I press DOWN so I know it is changing the velocity properly.

package square;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Shapes extends JFrame {

public static int WIN_WIDTH = 400;
public static int WIN_HEIGHT = 400;

private Paddle paddle = new Paddle();

public Shapes() {
    Panel panel = new Panel();

    setSize(WIN_WIDTH, WIN_HEIGHT);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    add(panel);
    panel.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if(keyCode == KeyEvent.VK_DOWN) {
                paddle.yVelocity = -4;
                System.out.println(paddle.yVelocity);
            }
            if(keyCode == KeyEvent.VK_UP) {
                paddle.yVelocity = 4;
            }
            if(keyCode == KeyEvent.VK_RIGHT) {
                paddle.xVelocity = 4;
            }
            if(keyCode == KeyEvent.VK_LEFT) {
                paddle.xVelocity = -4;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }
    });
    setVisible(true);
}

public static void main(String[] args) {
    new Shapes();
}
}

Here is my Paddle class where the shape's values are stored, drawn, and updated. I have the velocities set to 0 initially

package square;

import java.awt.*;

public class Paddle {

int RECT_WIDTH = 200;
int RECT_HEIGHT = 100;
int x = Shapes.WIN_WIDTH/2-100;
int y = Shapes.WIN_HEIGHT/2-50;
int xVelocity = 0;
int yVelocity = 0;

public void paint(Graphics g) {
    g.setColor(Color.red);
    g.fillRect(x, y, RECT_WIDTH, RECT_HEIGHT);
}

public void update() {
    x += xVelocity;
    y += yVelocity;
    if(x < 0 || x > Shapes.WIN_WIDTH) {
        xVelocity = -xVelocity;
    }
    if(y < 0 || y > Shapes.WIN_HEIGHT) {
        yVelocity = -yVelocity;
    }
}
}

And finally my Panel class

package square;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Panel extends JPanel implements ActionListener {

Paddle paddle = new Paddle();
Timer timer;

public Panel() {
    this.setFocusable(true);
    timer = new Timer(5,this);

    timer.start();
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    paddle.paint(g);
}

public void update() {
    paddle.update();
}

@Override
public void actionPerformed(ActionEvent e) {
    repaint();
    update();
}
}


texts:
I've been working on a parser for shop receipts which extracts data about the payment. Here is the text that I'm parsing:

  * Vic107Payment
    Text: PINNEN
    TicketData: POI: 12345678
KLANTTICKET
--------------------------------
Terminal:                 ABC123
Merchant:                 123456
Periode:                    1234
Transactie:             12345678

MAESTRO
(A0000000012345)
MAESTRO
Kaart:       xxxxxxxxxxxxxxx1234
Kaartserienummer:              0

BETALING
Datum:          01/01/2020 04:15
Autorisatiecode:          123ABC

Totaal:                 1,00 EUR

Leesmethode: NFC Chip

    CardTypeId: 1234
    CardTypeText: MAESTRO
    ReceiptNumber:
    DrawerAmount: 1,00
    Number: 1
    DrawerId: drawers/default
    DrawerNumber: 1
    Amount: 1,00
    IsCancelable: True
===

Here is the code that parses this fragment from the receipt. Now my concern is that people will find it difficult to read and/or difficult to maintain, so I was wondering whether it could be improved in any way?

def parse_card_payment(product):
    # cp stands for card payment
    cp_poi = None
    cp_terminal = None
    cp_merchant = None
    cp_period = None
    cp_transaction = None
    cp_card = None
    cp_card_serial_number = None
    cp_date = None
    cp_authorisation_code = None
    cp_total = None
    cp_card_type_id = None
    cp_card_type_text = None
    cp_drawer_id = None
    cp_drawer_amount = None
    cp_cancelable = None
    cp_card_type = None

    for line in product.strip().split('\n'):
        if 'POI' in line:
            cp_poi = line.split(':')[1].strip()
        elif 'Terminal' in line:
            cp_terminal = line.split(':')[1].strip()
        elif 'Merchant' in line:
            cp_merchant = line.split(':')[1].strip()
        elif 'Periode' in line:
            cp_period = line.split(':')[1].strip()
        elif 'Transactie' in line:
            cp_transaction = line.split(':')[1].strip()
        elif 'Kaart:' in line:
            cp_card = line.split(':')[1].strip()
        elif 'Kaartserienummer' in line:
            cp_card_serial_number = line.split(':')[1].strip()
        elif 'Datum' in line:
            cp_date = line.split(':')[1].strip()
        elif 'Autorisatiecode' in line:
            cp_authorisation_code = line.split(':')[1].strip()
        elif 'Totaal' in line:
            cp_total = line.split(':')[1].strip()
        elif 'CardTypeId' in line:
            cp_card_type_id = line.split(':')[1].strip()
        elif 'CardTypeText' in line:
            cp_card_type_text = line.split(':')[1].strip()
        elif 'DrawerAmount' in line:
            cp_drawer_amount = line.split(':')[1].strip()
        elif 'DrawerId' in line:
            cp_drawer_id = line.split(':')[1].strip()
        elif 'Cancelable' in line:
            cp_cancelable = line.split(':')[1].strip()
        elif 'Leesmethode' in line:
            cp_card_type = line.split(':')[1].strip()

    cp = {'cp_poi': cp_poi,
          'cp_terminal': cp_terminal,
          'cp_merchant': cp_merchant,
          'cp_period': cp_period,
          'cp_transaction': cp_transaction,
          'cp_card': cp_card,
          'cp_card_serial_number': cp_card_serial_number,
          'cp_date': cp_date,
          'cp_authorisation_code': cp_authorisation_code,
          'cp_total': cp_total,
          'cp_card_type_id': cp_card_type_id,
          'cp_card_type_text': cp_card_type_text,
          'cp_drawer_id': cp_drawer_id,
          'cp_drawer_amount': cp_drawer_amount,
          'cp_cancelable': cp_cancelable,
          'cp_card_type': cp_card_type}
    return cp


texts: Rotate a string of integers to match index

texts:
t is number of tests; each test contains two lines: n and sequence
n is number of integers
sequence is a sequence of integers from 1..n (e.g. '3 6 1 2 4 5' if n is 6)
Rotate sequence until you maximize the number of integers that match their position in the string. (e.g. '3 6 1 2 4 5' should output '1 2 4 5 3 6'). Print the answer sequence for each test.

Here is the working code. It seems to satisfy the conditions above.
Would be very grateful for any guidance to make it more efficient!
def rotate_left(seq):
    return seq[1:] + [seq[0]]

def is_in_position(seq):
    in_position = 0
    for idx, val in enumerate(seq, start=1):
        if int(val) == idx:
            in_position += 1
    return in_position

t = int(raw_input()) #number of tests
while t:
    n = int(raw_input()) #number of integers
    sequence = str(raw_input()).split() #sequence of integers from 1..n

    if not n:
        break

    max_score, answer_sequence = 0, 0

    for i in range(n):
        sequence = rotate_left(sequence)
        sequence_score = is_in_position(sequence)
        if max_score < sequence_score:
            max_score = sequence_score
            answer_sequence = sequence
            answer_sequence = ' '.join(answer_sequence)
        if max_score >= 0.5 * len(sequence):
            break
    if answer_sequence:
        print(answer_sequence)
    t -= 1


texts: Efficiency of grid generated by for-in loop

texts:
I've spend the last several hours working on a loop designed to take items in an array and arrange them as a so to speak "gird" of UIButtons. As far as I've been able to see through testing this code works perfectly.

However, I am new to creating loops and I was wondering if anyone could give me any pointers on how I could make this code cleaner/more efficient for future coding purposes.

I know my question is very similar to Optimize sorting of Array according to Distance (CLLocation), but I'm really hoping to get some tips on a "per case" basis. Thank you for your time.

- (void)myMethod
{
    NSArray *array = [[NSArray alloc] initWithObjects:@"Item #1", @"Item #2", @"Item #3", @"Item #4", @"Item #5", @"Item #6", @"Item #7", @"Item #8",  nil];

    BOOL leftOkay = NO;
    BOOL centerOkay = NO;
    BOOL rightOkay = NO;
    int left = 0;
    int center = 1;
    int right = 2;
    int yOrigin = 0;
    int spaceBetweenItems = 5;
    UIButton *leftButton;
    UIButton *centerButton;
    UIButton *rightButton;

    for (int i = 0; i < [array count]; i++)
    {
        if (left < [array count]) {
            leftButton = [[UIButton alloc] initWithFrame:CGRectMake(spaceBetweenItems, yOrigin + spaceBetweenItems, 100, 150)];
            [leftButton setTitle:[array objectAtIndex:left] forState:UIControlStateNormal];
            [leftButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [leftButton setBackgroundColor:[UIColor cyanColor]];
            [myScrollView addSubview:leftButton];
            leftOkay = YES;
        }
        if (center < [array count]) {
            centerButton = [[UIButton alloc] initWithFrame:CGRectMake(110, yOrigin + spaceBetweenItems, 100, 150)];
            [centerButton setTitle:[array objectAtIndex:center] forState:UIControlStateNormal];
            [centerButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            [centerButton setBackgroundColor:[UIColor yellowColor]];
            [myScrollView addSubview:centerButton];
            centerOkay = YES;
        }
        if (right < [array count]) {
            rightButton = [[UIButton alloc] initWithFrame:CGRectMake(215, yOrigin + spaceBetweenItems, 100, 150)];
            [rightButton setTitle:[array objectAtIndex:right] forState:UIControlStateNormal];
            [rightButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
            [rightButton setBackgroundColor:[UIColor purpleColor]];
            [myScrollView addSubview:rightButton];
            rightOkay = YES;
        }
        if (leftOkay == YES && centerOkay == YES && rightOkay == YES) {
            yOrigin = yOrigin + leftButton.frame.size.height + (spaceBetweenItems * 2);
            leftOkay = NO;
            centerOkay = NO;
            rightOkay = NO;
        }

        left    = left    + 3;
        center  = center  + 3;
        right   = right   + 3;
    }
    myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width, yOrigin + leftButton.frame.size.height + (spaceBetweenItems * 2));
}


texts:
This is the adder method of my binary calculator. I did not cover for the case that someone passes a non binary number into the calculator yet.

I am pretty sure I have covered every other edge case for the calculator. I am trying to learn refactoring and how to look for simpler ways to do things. I know that I have a bunch of if's, but I don't know any other way I could have made the logic for this. Could someone mentor me through how they would refactor my code and why?

class BinaryCalculator:

    def bit_adder(self, number1, number2):
        num_a = self.num_to_list(number1)
        num_b = self.num_to_list(number2)
        maxx = max(len(num_a), len(num_b))
        minn = min(len(num_a), len(num_b))

        if minn == len(num_b):
            smaller = num_b
            num_b = [0] * (maxx - minn)
            for i in smaller:
                num_b.append(i)
        else:
            smaller = num_a
            num_a = [0] * (maxx - minn)
            for i in smaller:
                num_a.append(i)

        print " ",''.join(map(str, num_a))
        print "+",''.join(map(str, num_b))
        print '----------'
        carry_bit = 0
        answer = [0] * (maxx + 1)

        for bit in xrange(maxx - 1, -1, -1):
            sum_bit = 0
            if num_a[bit] == num_b[bit]:
                if num_a[bit] == 1:
                    if carry_bit == 0:
                        carry_bit += 1
                    else:
                        sum_bit = 1
                else:
                    if carry_bit == 1:
                        sum_bit = 1
                        carry_bit -= 1

            else:
                if carry_bit == 1:
                    sum_bit == 0
                else:
                    sum_bit = 1
            answer[bit + 1] = sum_bit

        if carry_bit == 1:
            answer[0] = 1

        print ''.join(map(str, answer))

    def num_to_list(self, num):
        num = str(num)
        list_to_return = []
        for bit in range(len(num)):
            list_to_return.append(int(num[bit]))
        return list_to_return

c = BinaryCalculator()

c.bit_adder(10011001, 1001)


texts: Multiple random falling objects animation in Java

texts:
I am new to programming but I tried to make my code as readable as possible! Hopefully you can see what it does before you run the program. I did not implement a ups or fps controller, the animation may be fast for some computers and slower for others. I also tried to use the information provided to me from my first code review. Eventually I will be making this concept into a dodge the meteors type game.

Game class:

import javax.swing.*;
import java.awt.*;

public class Game extends JPanel {

    //changing these values will change the size of the game, while still remaining functional
    //within the size limit specified.
    public static final int WINDOW_WIDTH = 600;
    public static final int WINDOW_HEIGHT = 400;

    //Creates a Square object Array
    Square[] squareArray = new Square[20];

    public Game() {

        //initializes square objects
        for (int i = 0; i < squareArray.length; i++)
            squareArray[i] = new Square();
    }

    public void paint(Graphics graphics) {

        //makes background black
        graphics.setColor(Color.black);
        graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

        //paints square objects to the screen
        for (Square aSquareArray : squareArray) {
            aSquareArray.paint(graphics);
        }
    }

    public void update() {

        //calls the Square class update method on the square objects
        for (Square aSquareArray : squareArray) aSquareArray.update();
    }

    public static void main(String[] args) throws InterruptedException {

        Game game = new Game();
        JFrame frame = new JFrame();
        frame.add(game);
        frame.setVisible(true);
        frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Raining Multiple Squares");
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        while (true) {
            game.update();
            game.repaint();
            Thread.sleep(10);
        }
    }
}

Square class:

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Square extends JPanel {

    private int squareXLocation;
    private int squareSize;
    private int squareYLocation = -squareSize;
    private int fallSpeed = 1;
    Random rand = new Random();

    /*
    //creates a random value inside the window and stores it in squareXLocation
    */
    public int generateRandomXLocation(){
        return squareXLocation = rand.nextInt(Game.WINDOW_WIDTH - squareSize);
    }

    /*
    //creates a random value between 1-50 and stores it in squareWidth
    */
    public int generateRandomSquareSize(){
        return squareSize = rand.nextInt(50);
    }

    /*
    //creates a random value that is not zero and stores it in fallSpeed(so squares do not get stuck at 0 speed)
    */
    public int generateRandomFallSpeed(){
        return fallSpeed = rand.ints(1, 1, 10).findFirst().getAsInt();
    }

    /*
    //paints the square with the variables generated in the random methods
    */
    public void paint(Graphics g){
        g.setColor(Color.CYAN);
        g.fillRect(squareXLocation,squareYLocation,squareSize,squareSize);
    }

    /*
    //sets the squareWidth and square fallSpeed to a random value for every square created
    */
    public Square(){
        generateRandomXLocation();
        generateRandomSquareSize();
        generateRandomFallSpeed();
    }

    public void update(){

        //changes the squares xLocation and fallSpeed if the created square reaches the bottom of the screen
        if(squareYLocation >= Game.WINDOW_HEIGHT){
            generateRandomXLocation();
            generateRandomFallSpeed();
            generateRandomSquareSize();
            squareYLocation = -squareSize;
        }

        //moves the square down if the square is inside the window
        if(squareYLocation <= Game.WINDOW_HEIGHT){
            squareYLocation += fallSpeed;
        }
    }
}


texts: Parsing the first two command-line arguments and extracting the remainder

texts:
My program can be called like this:

FakeDpi someInteger someExecutable [parametersForSomeExecutable]

For example:

FakeDpi 120 "C:\Program Files (x86)\...\excel.exe" /X "C:\Users\...\myFile.xlsx"

should result in

dpi = 120
exe = C:\Program Files (x86)\...\excel.exe
args = /X "C:\Users\...\myFile.xlsx"

args should be extracted as verbatim as possible, since I don't know which argument parsing method the target program uses.

It works, but it seems like a lot of code for such a seemingly "simple" task. Please tell me if I'm reinventing the wheel somewhere along the way:

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

void parseCommandLine(int &dpi, std::wstring &exe, std::wstring &args);
void showUsage();
std::wstring parseStringArgument(std::wistringstream& ss);
int parseIntArgument(std::wistringstream& ss);

/* Return values:
   0 = Success
   1 = Invalid arguments
 */
int main()
{
    // Command line parameters
    int dpi;
    std::wstring exe;
    std::wstring args;

    // Parse command line manually, so that we can forward the
    // target program command line completely unmodified.
    try
    {
        parseCommandLine(dpi, exe, args);
    }
    catch (const std::invalid_argument& e)
    {
        std::wcerr << e.what() << "\n\n";
        showUsage();
        return 1;
    }

    // Do work
    ...
    return 0;
}

void showUsage()
{
    std::wcerr << "Usage: FakeDpi Dpi Command [Command-Line Arguments]\n\n"
        << "Example: FakeDpi 120 \"C:\\Program Files\\...\\myApp.exe\" myFile.xls\n";
}

void parseCommandLine(int &dpi, std::wstring &exe, std::wstring &args)
{
    std::wistringstream ss(GetCommandLineW());

    parseStringArgument(ss); // Skip own program name
    dpi = parseIntArgument(ss);
    exe = parseStringArgument(ss);

    std::getline(ss, args);
}

// Parses one space-delimited argument from the stream. If
// the argument is enclosed in double quotes, it may contain
// spaces and it is returned without the quotes.
std::wstring parseStringArgument(std::wistringstream& ss)
{
    if (ss.eof())
    {
        throw std::invalid_argument("End of argument list reached.");
    }

    std::wstring ret;

    wchar_t delim = L' ';
    if (ss.peek() == L'"')
    {
        delim = L'"';
        ss.ignore();    // skip starting quote
    }
    std::getline(ss, ret, delim);
    if (delim == L'"')
    {
        if (ss.eof())
        {
            throw std::invalid_argument("Closing quote not found.");
        }
        ss.ignore();    // skip closing quote
    }

    ss >> std::ws;
    return ret;
}

int parseIntArgument(std::wistringstream& ss)
{
    std::wstring s = parseStringArgument(ss);

    wchar_t *end;
    errno = 0;
    int ret = wcstol(s.c_str(), &end, 10);

    if (errno != 0
        || s.empty()    /* could be checked earlier, but this is not time critical */
        || *end != '\0' /* trailing non-numeric content */)
    {
        throw std::invalid_argument("Input is not a valid integer.");
    }

    return ret;
}

Note: I deliberately ignore the "argument ends with an even/uneven number of backslashes" madness of Windows command-line parsing, since it does not make sense for any of the parameters to end in a backslash.


texts: Python function to hash a python function

texts:
I'm working on a sort of distributed build system. The system allows execution of snippets of scripts as build steps. I need to be able to hash these snippets of code in a way that comments and doc strings don't affect the hash. I'm getting part way there by using the ast module to parse the code, then doing an ast.dump and hashing the resulting string. The natural next step for me is to clear the first Expr(str()) node in the body of every FunctionDef node.

This is the best solution I've found so far.

Is there a better way to solve this problem?

import ast
import hashlib
import inspect

def _remove_docstring(node):
    '''
    Removes all the doc strings in a FunctionDef or ClassDef as node.
    Arguments:
        node (ast.FunctionDef or ast.ClassDef): The node whose docstrings to
            remove.
    '''
    if not (isinstance(node, ast.FunctionDef) or
            isinstance(node, ast.ClassDef)):
        return

    if len(node.body) != 0:
        docstr = node.body[0]
        if isinstance(docstr, ast.Expr) and isinstance(docstr.value, ast.Str):
            node.body.pop(0)

#-------------------------------------------------------------------------------
def hash_function(func):
    '''
    Produces a hash for the code in the given function.
    Arguments:
        func (types.FunctionObject): The function to produce a hash for
    '''
    func_str = inspect.getsource(func)
    module = ast.parse(func_str)

    assert len(module.body) == 1 and isinstance(module.body[0], ast.FunctionDef)

    # Clear function name so it doesn't affect the hash
    func_node = module.body[0]
    func_node.name = ""

    # Clear all the doc strings
    for node in ast.walk(module):
        _remove_docstring(node)

    # Convert the ast to a string for hashing
    ast_str = ast.dump(module, annotate_fields=False)

    # Produce the hash
    fhash = hashlib.sha256(ast_str)
    result = fhash.hexdigest()
    return result

#-------------------------------------------------------------------------------
# Function 1
def test(blah):
    'This is a test'
    class Test(object):
        '''
        My test class
        '''
    print blah
    def sub_function(foo):
        '''arg'''
print hash_function(test)

#-------------------------------------------------------------------------------
# Function 2
def test2(blah):
    'This is a test'
    class Test(object):
        '''
        My test class
        '''
    print blah
    def sub_function(foo):
        '''arg meh'''
print hash_function(test2)


texts: A like/unlike system using MySQL and PDO

texts:
I have created a Like/Unlike system. The user clicks one to indicate a "like", and clicks again to "unlike" it. Currently I do that like this:

try {                                             -- like
    $stm1 = $db_conn->prepare("INSERT into votes (post_id, user_id) VALUES (?, ?)");
    $stm1->execute(array($post_id, $_SESSION['id']));

} catch(PDOException $e){
    if ((int) $e->getCode() === 23000) {          -- unlike
        $stm2 = $db_conn->prepare("DELETE FROM votes WHERE post_id = ? AND user_id = ?");
        $stm2->execute(array($post_id, $_SESSION['id']));

    } else {
        $error = true;
    }
}

Note: $e->getCode() === 23000 means row is duplicate. because there is a unique index on post_id and user_id columns.

Well my code works as well. Just when a professional programmer see it, he says: your algorithm is wrong and you shouldn't delete something when insert fails (on duplicate).

Well, should I change my current code? What's wrong with it? Trust me it works perfectly :) ..!


texts:
I'm using an open source program called MElt which lemmatize (give the lemma example:giving-->give) of words. MElt works on Linux and it's programmed in Perl and Python. So far it's working good but it take way too much time to give the results. I looked into the code and located the loop responsible for this:

while (<LEFFF>) {
  chomp;
  s/ /_/g;
#  s/(\S)-(\S)/\1_-_\2/g;
  /^(.*?)\t(.*?)\t(.*?)(\t|$)/ || next;
  $form = $1; $cats = $2; $lemma = $3;
  #print "$form \n";
  #print "$cats \n";
  #print "$lemma \n";
  if ($lower_case_lemmas) {
    $lemma = lc($lemma);
  }
  if ($it_mapping) {
    next if ($form =~ /^.+'$/);
    next if ($form eq "dato" && $lemma eq "datare"); # bourrin
    next if ($form eq "stato" && $lemma eq "stare"); # bourrin
    next if ($form eq "stata" && $lemma eq "stare"); # bourrin
    next if ($form eq "parti" && $lemma eq "parto"); # bourrin
    if ($cats =~ /^(parentf|parento|poncts|ponctw)$/) {$cats = "PUNCT"}
    if ($cats =~ /^(PRO)$/) {$cats = "PRON"}
    if ($cats =~ /^(ARTPRE)$/) {$cats = "PREDET"}
    if ($cats =~ /^(VER|ASP|AUX|CAU)$/) {$cats = "VERB"}
    if ($cats =~ /^(CON)$/) {$cats = "CONJ"}
    if ($cats =~ /^(PRE)$/) {$cats = "PREP"}
    if ($cats =~ /^(DET)$/) {$cats = "ADJ"}
    if ($cats =~ /^(WH)$/) {$cats = "PRON|CONJ"}
    next if ($form =~ /^(una|la|le|gli|agli|ai|al|alla|alle|col|dagli|dai|dal|dalla|dalle|degli|dei|del|della|delle|dello|nei|nel|nella|nelle|nello|sul|sulla)$/ && $cats eq "ART");
    next if ($form =~ /^quest[aei]$/ && $cats eq "ADJ");
    next if ($form =~ /^quest[aei]$/ && $cats eq "PRON");
    next if ($form =~ /^quell[aei]$/ && $cats eq "ADJ");
    next if ($form =~ /^quell[aei]$/ && $cats eq "PRON");
    next if ($form =~ /^ad$/ && $cats eq "PREP");
    next if ($form =~ /^[oe]d$/ && $cats eq "CONJ");
  }
  $qmlemma = quotemeta ($lemma);
  for $cat (split /\|/, $cats) {
    if (defined ($cat_form2lemma{$cat}) && defined ($cat_form2lemma{$cat}{$form}) && $cat_form2lemma{$cat}{$form} !~ /(^|\|)$qmlemma(\||$)/) {
      $cat_form2lemma{$cat}{$form} .= "|$lemma";
    } else {
      $cat_form2lemma{$cat}{$form} = "$lemma";
      $form_lemma_suffs = "@".$form."###@".$lemma;
      while ($form_lemma_suffs =~ s/^(.)(.+)###\1(.+)/\2###\3/) {
        if (length($2) <= 8) {
          $cat_formsuff_lemmasuff2count{$cat}{$2}{$3}++;
          if ($multiple_lemmas) {
            $cat_formsuff_lemmasuff2count{$cat}{$2}{__ALL__}++;
          }
        }
      }
    }
  }
}

The variable LEFFF is a dictionary composed of 490489 lines.  So, the loop is comparing the words with all the dictionary lines one by one.  This is too much. Any ideas how to optimize this?

Here's a preview of how LEFFF is structured:

touant  VPR touer   0
intimiste   NC  intimiste   1
intimiste   ADJ intimiste   0
phonologiques   ADJ phonologique    1
condescendirent V   condescendre    1
enchaussez  VIMP    enchausser  1
enchaussez  V   enchausser  0
riotiez VS  rioter  1
riotiez V   rioter  0
Eyzin-Pinet NPP Eyzin-Pinet 1
dentaires   NC  dentaire    0
dentaires   ADJ dentaire    1
classe  VIMP    classer 0
classe  VS  classer 1


texts:
I'm trying to build a URL to call the SharePoint Search REST API in TypeScript. The interesting part is building the querytext, which is done by my buildQueryText method. In my case it takes two parameters: A content type to search for and a array of select properties.

buildQueryText(contentType: string, selectProperties: string[]): string {
    var contentTypeQuery = "'" + "SPContentType:" + contentType + "'";

    var selectPropertiesQuery = "";
    if (selectProperties.length !== 0) {
        selectPropertiesQuery = "&selectproperties=" + "'";
        selectProperties.forEach((property, index) => {
            if (index < selectProperties.length - 1) {
                selectPropertiesQuery += property + ",";
            } else {
                selectPropertiesQuery += property + "'";
            }
        });
    }

    return `${contentTypeQuery}${selectPropertiesQuery}&clienttype='Custom'`;
}

I'm calling the method like this:

buildQueryText("SearchItem", ["prop1", "prop2", "prop3"])

and expecting the following output:

"'SPContentType:SearchItem'&'selectproperties=prop1,prop2,prop3'&clienttype='Custom'"

I'm looking for a way to improve the selectPropertyQuery part and make it more readable, as it seems quite messy. And i'm aware that there is no real validation of the inputs.


texts: Random number generator based on a hash of the time

texts:
from time import time

def baseRandom():
    return hash(str(time()))

def randFromZero(maximum):
    return baseRandom() % maximum

def randRange(minimum, maximum):
    return randFromZero(maximum - minimum) + minimum

I ask what's wrong because it seems so simple and stupid. This is something I just thought up one day and put together in 5 minutes, but it seems to generate even and unpredictable results. I've done a couple of simple tests like generating a lot of numbers and looking at the variance between the amount of times each number is generated, and using it to create a little grid which has tiles that are either black or white with equal probability, in which I saw no clear patterns. Hopefully someone who knows a thing or two about this can educate me.


texts:
I'm optimising our codebase and currently, the slowest part of the code is a method called calculateResourceZ which is used in projections. I'm looking for suggestions on areas of improvement. It needs the accuracy so it has to use doubles.

double calculateResourceZ(const double resource0, const double fwAtWicket, const double decimalOversRemaining, const double lambdaLocal, const double power) const {
    if (fwAtWicket == 0) {
        return 0;
    }

    const double resourceZPart1 = resource0 * fwAtWicket * pow(lambdaLocal, (power + 1.0));
    const double fg = calculateFunctionG(lambdaLocal, decimalOversRemaining);

    const double resourceZPart2 = (1.0 - exp(-((decimalOversRemaining * expDecay * fg * pow(lambdaLocal, -power)) / fwAtWicket)));
    return resourceZPart1 * resourceZPart2;
}

double calculateFunctionG(const double lambda, const double oversRemaining) const {
    if (version < Version::OCT2014) {
        return 1;
    }

    if (oversRemaining == 0 || lambda == 0) {
        return 0;
    }

    const double alphaLambda = calculateAlphaLambda(lambda);
    const double betaLambda = calculateBetaLambda(lambda);

    return pow((oversRemaining / 50.0), -(1.0 + alphaLambda + betaLambda * oversRemaining));
}

double calculateAlphaLambda(const double lambda) const {
    return -1.0 / (1.0 + c1 * (lambda - 1) * exp(-c2 * (lambda - 1.0)));
}

double calculateBetaLambda(const double lambda) const {
    return -c3 * (lambda - 1.0) * exp(-c4 * (lambda - 1.0));
}


texts:
Problem Statement:

  First Case: Where inclusion and exclusion both are not empty so that means inclusion overrides anything in exclusion so for that algorithm is like this:

  If key is either equal to 155 or 156 and if temp is there in inclusion
  then go into that if loop and do whatever you want. But if temp is not
  there in inclusion then don't do anything.

  Second Case: Where inclusion is null and exclusion is not null so that means now you need to exclude everything present in exclusion string, so the algorithm is like this:

  If key is either equal to 155 or 156 and if temp is not there in exclusion then do whatever you want to do in that else loop otherwise don't do anything.

  Third Case: If key is not equal to 155 or 156 then do whatever you want to do in that loop.

Is there any way we can improve this code in terms of performance, readability, accuracy? as when I see this it contains lot of if/else statements to make the above problem works

P.S: Things that I am doing in each if/else loop is same everytime.

Cases1: Where input parameters can be-

String inclusion = null; // It can be null also
String exclusion = "100;77";

String temp = "0"; // It can change anytime

Cases2: Where input parameter can be-

String inclusion = "0"; // It can be null also
String exclusion = null;

String temp = "0"; // It can change anytime

Below is the code in which above input parameters can be used:

for(TesxAttrKey key: pdsxWriteRequest.getAttrKeys()){

if((key.equals("156") || key.equals("155"))) {
    if(inclusion != null && !inclusion.trim().isEmpty()) {
        if(inclusion.matches("(^|.*;)" + temp + "(;.*|$)")) {
            //Check the DsxAttrValue has a Synthesizer
            if(metadata!=null){
                Synthesizer synthesizer = metadata.getSynthesizer();
                if(synthesizer!=null){
                    //Synthesize the attribute
                    DsxAttrValue synthesizedVal =
synthesizer.synthesize(key, record);
                    val = synthesizedVal;
                }
            }
            if(val!=null){
                writeRecord.getAttrs().put(key, val);
            }
        }
    } else {
        if(!exclusion.matches("(^|.*;)" + temp + "(;.*|$)")) {
            //Check the DsxAttrValue has a Synthesizer
            if(metadata!=null){
                Synthesizer synthesizer = metadata.getSynthesizer();
                if(synthesizer!=null){
                    //Synthesize the attribute
                    DsxAttrValue synthesizedVal =
synthesizer.synthesize(key, record);
                    //if(synthesizedVal!=null){
                    val = synthesizedVal;
                    //}
                }
            }
            if(val!=null){
                writeRecord.getAttrs().put(key, val);
            }
        }
    }
} else {
    //Check the DsxAttrValue has a Synthesizer
    if(metadata!=null){
        Synthesizer synthesizer = metadata.getSynthesizer();
        if(synthesizer!=null){
            //Synthesize the attribute
            DsxAttrValue synthesizedVal = synthesizer.synthesize(key, record);
            //if(synthesizedVal!=null){
            val = synthesizedVal;
            //}
        }
    }
    if(val!=null){
        writeRecord.getAttrs().put(key, val);
    }

}

Is there any way we can improve this code in terms of performance, as I have lot of if/else loops to solve the above problem?


texts: Vectorize or otherwise speed up a double for loop

texts:
I have this function containing some loops and a double for loop. What it does is set up a matrix first to store results in (the task at hand is comparing genomes) and then with sliding window, calculate the differences between sequences. It's very slow for very long sequences, I was hoping somebody know how to speed this up, the part causing the bottleneck is:

n1 <- 0

  for(i in seq(windowp1)) {

    n1 <- n1+1
    n2 <- 0
    setTxtProgressBar(prog, n1)
    for(i in seq(1:ncol(Distances))) {
      n2 <- n2+1

      Distances[n1,n2] <- sum(x[pairs[n2,1],c(windowp1[n1]:windowp2[n1])] != x[pairs[n2,2],c(windowp1[n1]:windowp2[n1])])

    }

    Distances2 <- (Distances/winsize)*100

  }

Where windowp1 is a vector of numbers defining the start of each window. Distances is the pre-made matrix for the results, it has as many cols as there are pairwise comparisons of sequences and as many row's as there are sliding window frames, determined by windowp1 and windowp2. The differences between the sequences are calculated simply by the hamming distance. The loop 1 ticks up the window, the second loop then ticks over to do all comparisons between sequences to do in the window, then the first loop ticks to select the next window. The final line makes the hamming distances in the matrix a % of the widowsize.


texts: Best way to split array to two sub-arrays, with maximum absolute difference between them

texts:
Given array a, we want to find an index k in range [0, a.length-1] such that:

Math.abs( (a[0]+a[1]+...a[k-1]) - (a[k] + a[k+1] + ... + a[a.length-1]) )

is maximal (in case k == 0, the result above is the sum of a elements).

Below is the code I wrote.
Please tell me your opinion about it - run time, correctness and coding conventions.

public static int sumArray(int[] a) {
    int sum = 0;
    int len = a.length;

    for (int i = 0; i < len; i++) {
        sum += a[i];
    }

    return sum;
}

public static int findMaxDif(int[] a) {
    int left = 0;
    int right = sumArray(a);
    int max = Math.abs(right);
    int maxIndex = 0;
    int difI;
    int len = a.length - 1;

    for (int i = 0; i < len; i++) {
        left += a[i];
        right -= a[i];
        difI = Math.abs(left - right);

        if (difI > max) {
            max = difI;
            maxIndex = i + 1;
        }
    }

    return maxIndex;
}

Simple tests that I wrote and work fine:

public static void main (String[] args) {
    int[] a1 = {1,2};
    if (findMaxDif(a1) == 0) {
        System.out.println("test1 pass");
    }

    int[] a2 = {-1,2};
    if (findMaxDif(a2) == 1) {
        System.out.println("test2 pass");
    }

    int[] a3 = {2,-1};
    if (findMaxDif(a3) == 1) {
        System.out.println("test3 pass");
    }

    int[] a4 = {-5,-4,4,3};
    if (findMaxDif(a4) == 2) {
        System.out.println("test4 pass");
    }
}


texts: C++ Vector memory management in Game of Life

texts:
I'm writing a simulator for Conway's Game of Life (http://en.wikipedia.org/wiki/Conway's_Game_of_Life) in C++ and I'm trying to make the code as idiomatic as possible.

The central object is a double array to represent the board:

typedef vector<vector<bool> > Board;

My main method has a Board b as a local variable, and I'm passing the board to several methods that update the board, draw the board, and so on.  Is it better (that is, more efficient and/or idiomatic) to use methods like

void update(Board *board);

int main() {
   Board b;
   //...
   update(&b);
   //...
}

or in this way:

void update(Board & board);

int main() {
   Board b;
   //...
   update(b);
   //...
}

Which is the proper choice for idiomatic C++?


texts:
I am looking for help for two things.

proof of correctness (the tests have passed, but I do not now how to prove it correct)
Improvements on the Algorithm Efficiency.

The algorithm goes through 2 arrays arrays through permutations. The ordering is set up based on the array index, NOT the number inside the index. Noteably, if both parallel arrrays are set up diffrent, the algorithm should run fine.The algorithm then adds the function to the sum, which estimates computes the series.
Code is below.

def f(x:float, y:float, a:float)->float:
    """
    param x:float, x coordinate
    param y:flaot, y coordinate
    param a:float, paramter of the curve
    """
    return x + (y * a)

def main():
    """
    algorithm:
    Suppouse arrays are orderd by thier index and NOT the element inside
    Go through an ordering which meets that (one ordering is enough)
    add on the function at that point to the sequence
    """
    x = [1.0, 2.0, 3.0]
    y = [2.0, 3.0, 4.0]
    a = 2.0
    seq = [0.0] * len(x)
    for row in range(0, len(x) + 1):
        for col in range(0, len(x) + 1):
            for at in range(row, col):
                seq[at] = seq[at] + f(x[at], y[at], a)
    print(seq)

if __name__ == "__main__":
    main()


texts: Manipulate JSON data from the client with JavaScript

texts:
I am making an application in which the user has the ability to add, remove, and edit JSON data through DOM interaction. I have created a working JavaScript-only prototype that accepts certain variables to manipulate certain elements of the JSON data, although it is rather messy and seems rather impossible for me to implement with the DOM.

Right now, my current structure is:

  Example Modding Session

  Modding Section

  A mod
  A mod

  Another Modding Section

  A mod
  A mod
  A mod

  Another Modding Session

  Modding Section

  Another mod
  Another mod
  Another mod

  Modding Section

  Another mod

Which has worked fine for me, however, my functions are very repetitive, which I would like to fix.

var addSession = function(sessionName) {

    var selfSessionName = sessionName || undefined;
    if(!selfSessionName) return;

    moddingSessions.push({
        "name": selfSessionName,
        "sections": []
    });

}

Here you may start to see a pattern:

var addSection = function(sectionName, sessionName) {

    var selfSessionName = sessionName || undefined,
        selfSectionName = sectionName || undefined;
    if(!selfSectionName || !selfSectionName) return;

    for(var i = 0; i < moddingSessions.length; i++) {
        if(moddingSessions[i].name === selfSessionName) {
            moddingSessions[i].sections.push({
                "name": selfSectionName,
                "mods": []
            });
        }
    }

}

And here:

var addMod = function(modContent, sectionName, sessionName) {

    var selfSessionName = sessionName || undefined,
        selfSectionName = sectionName || undefined,
        selfModContent  = modContent  || undefined;
    if(!selfModContent || !selfSectionName || !selfSectionName) return;

    for(var i = 0; i < moddingSessions.length; i++) {
        if(moddingSessions[i].name === selfSessionName) {
            for(var j = 0; j < moddingSessions[i].sections.length; j++) {
                if(moddingSessions[i].sections[j].name === selfSectionName) {
                    moddingSessions[i].sections[j].mods.push(modContent);
                }
            }
        }
    }

}

As you can see, it works, but isn't very effective. I also have no idea how to handle each and every parameter when using this with DOM interaction. I hope there is a better way to achieve the same functionality.


texts: "Extending" the Swift 2 ErrorType protocol

texts:
I am building a simple REST client in Swift 2. The methods the client offers can return errors. Every method returns the same errors (network problem, unauthorized, etc...). But each method can also return "specialized" error, than are needed only for the method itself.

I am trying to "extend" my ErrorType enum to match those "specialized" errors. This is my code:

// Specialized error type
public protocol CommandError: ErrorType {}

// A command that does not have specialized errors
public enum NoCommandError: CommandError {}

// The "Authorize" method returns errors
public enum AuthorizeError: CommandError {
    case WrongAuthorizeCode
    case WrongRequestId
}

// The errors the client can return
public enum ClientError<T: CommandError>: ErrorType {
    case Deserialization
    case Networking(internalError: NSError)
    case CommandError(commandError: T)
    case Unknown
}

// For any method that does not return specialized errors
public typealias ClientErrorDefault = ClientError<NoCommandError>

And I can easily pattern-match on the errors depending on which method I call. Here is an example:

func testAuthorize() -> ClientError<AuthorizeError> {
    return ClientError.CommandError(commandError: AuthorizeError.WrongAuthorizeCode)
}

func testOther() -> ClientErrorDefault {
    return ClientError.Deserialization
}

func matchError() {
    let error = testAuthorize()
//    let error = testOther()

    switch error {
    case .Deserialization: print("Deserialization")
    case .Networking(let e): print("Networking: \(e)")
    case .Unknown: print("Unknown")
    case .CommandError(let e): print(e)
    }
}

matchError()

(My playground code)

What do you think about this solution ?


texts: PyQt GUI with setObjectName on all components to enable functional testing

texts:
Inspired by Test-Driven Development with Python by Harry Percival, I'm trying to implement functional testing of a PyQt GUI. I'm finding that, in order for tests to find the GUI components, I need the actual code to include lots of .setObjectName lines as a "hook". This makes the actual program code very redundant. For example:

    modelsWidget = QWidget()
    modelsWidget.setObjectName('modelswidget')
    modelsLayout = QVBoxLayout()
    modelsLayout.setObjectName('modelslayout')

    twoSingletButton = QRadioButton('Two uncoupled spin-1/2 nuclei')
    twoSingletButton.setObjectName('twosingletbutton')
    abButton = QRadioButton('Two coupled spin-1/2 nuclei\n ("AB quartet)')
    abButton.setObjectName('abbutton')

and then the functional tests would look up components by name, e.g.:

def test_view_switch(self):
    """The user clicks on the radio button for the AB model, and sees that the
    view has changed to that for the AB model."""
    initialView = self.ui.stackedWidget.currentWidget()
    abButton = self.getToolbar.findChild(QRadioButton, 'abbutton')
    abButton.click()
    finalView = self.ui.stackedWidget.currentWidget()
    assert initialView is not finalView
    assert finalView.objectName() == 'ABwidget'

(OK, that's probably poor craftsmanship, with two asserts in a single test, but it demonstrates the nature of the test strategy.)

I don't see a good way around this. It's a lot more direct to use a statement such as:

self.Gui.findChild (QDoubleSpinBox, 'va')

than:

self.Gui.stackedWidget.currentWidget.layout.itemAtPosition(2, i).widget()

in the tests. The former is assuming that the main code uses the same widget names, and the latter is assuming that the main code uses the exact same hierarchy to place a widget. Neither may truly be mandatory to provide the desired "look/feel" of the GUI.

Am I going about functional testing a PyQt GUI the wrong way? Is there a more proper way for a test to find, or refer to, GUI components?


texts: Generic method for obtaining enum items in an ushort object

texts:
The idea is to perform a bit-wise scan of an ushort provided to find any and all matches within an enum collection.

The code I developed is as follows:

public List<T> GetEnumItemsFromUshort<T>(ushort input) where T : struct, IComparable, IConvertible, IFormattable
    {
        var output = new List<T>();
        foreach (T enumValue in Enum.GetValues(typeof(T)))
        {
            if ((input & enumValue.ToUInt16(new CultureInfo("en-US"))) == enumValue.ToUInt16(new CultureInfo("en-US")))
            {
                output.Add(enumValue);
            }
        }
        return output;
    }

As you can see, I use a generic type to define the return type.

I searched the site and found that constraining the generic type with the following struct, IComparable, IConvertible, IFormattable, makes it behave like an enum.

The code generates a list of the enum provided to contains the matches found.

Then it proceeds to scan the input value to find any and all items that masked (a bit-wise operation as stated before) do match.

If a match is found it adds the enum case to the return list.

I want to know whether this is a good or bad implementation and ways to make it better, it performs as expected but I feel like there's room for optimization.

To provide an example, suppose the following enum and input:

public ushort sample = 6;

public enum SampleCases
{
    Case1 = 0x1,
    Case2 = 0x2,
    Case3 = 0x4,
    Case4 = 0x8,
}

The output for this code would be a List of type SampleCases with 2 items, Case2 and Case 3 since both (bit-wise) are contained in the sample provided. Tell me if this works as an example for you.


texts:
I have a dictionary:

x = {'[a]':'(1234)', '[b]':'(2345)', '[c]':'(xyzad)'}

and a dataframe

df = pd.DataFrame({'q':['hey this is [a]', 'why dont you [b]', 'clas is [c]']})

I want to append the values from dictionary to the corresponding keys.

My expected output is:

                       q
0   hey this is [a](1234)
1  why dont you [b](2345)
2      clas is [c](xyzad)

Here's my solution:

x = {k: k+v for k,v in x.items()}

def das(data):
    for i in x.keys():
        if i in data:
            data = data.replace(i, x[i])
    return data

df['q'] = df['q'].apply(lambda x: das(x))
print(df)

Is there a way to improve this?

I have to update a dictionary by appending a key infront of values. Then I use apply to replace the values.

I am looking for more efficient solution.


texts:
I have some code which moves the users position up, right, down or left depending on the direction entered.

function up(field, player) {
    player.column = player.column + 1;
    field[player.row][player.column] = 'P';
}

function right(field, player) {
    player.row = player.row + 1;
    field[player.row][player.column] = 'P';
}

function down(field, player) {
    player.column = player.column - 1;
    field[player.row][player.column] = 'P';
}

function left(field, player) {
    player.row = player.row - 1;
    field[player.row][player.column] = 'P';
}

The code works fine for what I need, but I was curious if there is a more efficient way of writing the 4 functions above? As in maybe use one function rather than 4?

note
Edge cases will be implemented - if the next position is greater than the dimensions of the field, etc. So I'm not sure if this will impact making it more efficient


texts: VBA - faster way to list out files in a folder & subfolders

texts:
I have written a VBA code in excel (basically through combining various codes from others -_-") to list out the path, file name, file size & extension of all files under a folder and the sub-folders there-under.

Is it possible to improve the efficiency for collecting the same info?

Sub MainList()
    Set folder = Application.FileDialog(msoFileDialogFolderPicker)
    If folder.Show <> -1 Then Exit Sub
    xDir = folder.SelectedItems(1)
    Cells(3, 1) = Now()
    Call ListFilesInFolder(xDir, True)
    Cells(5, 1) = Now()
End Sub

Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
    Dim xFileSystemObject As Object
    Dim xFolder As Object
    Dim xSubFolder As Object
    Dim xFile As Object
    Dim rowIndex As Long
    Dim folder_index As Integer
    Dim file_extension As String
    Dim file_type As String
    Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
    Set xFolder = xFileSystemObject.GetFolder(xFolderName)
    folder_index = Range("B65536").End(xlUp).row + 1
    rowIndex = Range("F65536").End(xlUp).row + 1
    Cells(folder_index, 2).Select
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=xFolder.Path, TextToDisplay:=xFolder.Path

    For Each xFile In xFolder.Files
        file_extension = LCase(xFileSystemObject.GetExtensionName(xFile.Path))
        If file_extension = "pdf" Then
            file_type = "PDF"
        ElseIf Left(file_extension, 3) = "doc" Then
            file_type = "DOC"
        ElseIf Left(file_extension, 2) = "xl" Then
            file_type = "XLS"
        ElseIf Left(file_extension, 3) = "msg" Then
            file_type = "MSG"
        ElseIf Left(file_extension, 3) = "zip" Then
            file_type = "ZIP"
        ElseIf Left(file_extension, 3) = "ppt" Then
            file_type = "PPT"
        Else
            file_type = ""
        End If
        Cells(rowIndex, 6).Select
        ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=xFolder.Path, TextToDisplay:=xFolder.Path
        Cells(rowIndex, 7).Select
        ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=xFile.Path, TextToDisplay:=xFile.Name
        Cells(rowIndex, 8).Formula = file_type
        Cells(rowIndex, 9).Formula = xFile.Size
        Cells(rowIndex, 10).Formula = xFile.DateLastModified
        Cells(rowIndex, 11).Formula = file_extension
        rowIndex = rowIndex + 1
    Next xFile

    If xIsSubfolders Then
        For Each xSubFolder In xFolder.SubFolders
            ListFilesInFolder xSubFolder.Path, True
        Next xSubFolder
    End If

    Set xFile = Nothing
    Set xFolder = Nothing
    Set xFileSystemObject = Nothing

End Sub


texts: Walk recursively through dictionaries and return result without using global variable

texts:
I need to walk through several nested dictionaries in a recursive way and return a value of the type property.

How my code could be improved? Especially, how to do it without a global variable?

field_mapping = {
  "logic_index" : {
    "mappings" : {
      "Patient" : {
        "Diagnosis.Diagnosis_Start_Date" : {
          "full_name" : "Diagnosis.Diagnosis_Start_Date",
          "mapping" : {
            "Diagnosis_Start_Date" : {
              "type" : "date",
              "format" : "strict_date_optional_time||epoch_millis"
            }
          }
        }
      }
    }
  }
}

def get_field_type(mapping):
    ftype = 'string'

    def parse_mapping(mapping):
        global ftype
        for key, item in mapping.iteritems():
            if isinstance(item, dict):
                parse_mapping(item)
            elif key == 'type':
                ftype = item
        return ftype

    ftype = parse_mapping(mapping)
    return ftype

ftype = get_field_type(field_mapping)
print(ftype)


texts:
I want to send a string with the following path, and I want to verify if this is the right way to do that in JavaScript.

Is this the right way to use the return in an if/else, or there is shorter way?
Is the indexOf using correctly?

https://test.com/plugins/plug/pluginr/poc/fact

function isExt(path) {

  if(path.indexOf("/plug/pluginr/")) {

    return true;

  }
  else {

    return false;

  }

}


texts:
As part of a personal project I am working on in python, I have started writing a command line utility to convert .hdf files into a JSON file. Before the conversion is done however, I have written some validation code to check that the file exists, has the correct extension, and has the correct basic format.

Here is the code so far

import sys
import h5py
from pathlib import Path

# -------------------------------------------------
# Utility classes defined below.
# -------------------------------------------------
class Validator:
    def print_help_text():
        print("The processor.py utility is designed to take a single argument, the path")
        print("to a NASA EarthData Global Fire Emissions Database GFED4.1s_yyyy.hdf5 file.")
        print("Example - $ ./preprocess.py some/directory/GFED4.1s_2015.hdf5\n")

        print("If a valid file path is passed to the utility it should output individual JSO")
        print("files for each month, that contain data in the format required to train the")
        print("emissions predictor.\n")

        print("By default the new files will be ouput to the same directory that contains")
        print("the script. Alternatively, you can provide a second argument with a path to")
        print("another directory for the output files to be placed in.")

    def valid_hdf_file(path_string):
        valid_extensions = ("hdf","hdf4","hdf5","h4","h5", "he2", "he5")
        if path_string.split(".")[-1] in valid_extensions:
            if Path(path_string).is_file():
                return True
            else:
                print("\n'" + path_string + "' is not a valid file.\n")
                return False
        else:
            print("\nThe input file must be an HDF file with a correct extension.\n")
            return False

    def valid_arguments(arguements):
        args = len(arguements)
        if (args == 2 or args == 3) and arguements[1] != "--help":
            path_to_data = arguements[1]
            return Validator.valid_hdf_file(path_to_data)
        else:
            Validator.print_help_text()
            return False

    def valid_leaf_groups(group, month, hdf_file):
        groups_and_leaves = {
            "biosphere": ("BB", "NPP", "Rh"),
            "burned_area": ("burned_fraction",),
            "emissions": ("C", "DM")
        }
        valid = True
        for leaf in groups_and_leaves[group]:
             full_group = group + "/" + ("%02d" % month) + "/" + leaf
            if full_group not in hdf_file:
                valid = False
                print("Expected group '" + full_group + "' not in HDF file.")
        return valid

    def valid_hdf_structure(hdf_file):
        valid = True
        for group in ("ancill/basis_regions", "lon", "lat"):
            if group not in hdf_file:
                valid = False
                print("Expected group '" + group + "' not in HDF file.")
        for group in ("biosphere", "burned_area", "emissions"):
            for month in range(1,13):
                full_group = group + "/" + ("%02d" % month)
                if full_group not in hdf_file:
                    valid = False
                    print("Expected group '" + full_group + "' not in HDF file.")
                else:
                    valid = valid and Validator.valid_leaf_groups(group, month, hdf_file)
        return valid

# -------------------------------------------------
# Script starts here.
# -------------------------------------------------

if __name__ == "__main__":
    if not Validator.valid_arguments(sys.argv):
        sys.exit()

    filename = sys.argv[1]
    print("Processing - " + filename)
    hdf_file = h5py.File(filename, 'r')

    if not Validator.valid_hdf_structure(hdf_file):
        sys.exit()

    print("Basic structure of hdf file confirmed to conform to GFED4 format.")


texts: Shell script that creates and deletes symbolic links

texts:
Right now I am working on an install and uninstall script for my vim configuration files. The install script links files and directories and the uninstall script deletes those links. I just want to make sure that this code is somewhat safe, are there better ways of doing the same thing? Here is the code I have right now:

Install Script:

#!/bin/bash
# The install script for my vim dotfiles.
# Find the location of the script.
SCRIPT_DIRECTORY="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# The source directory and target directories.
SOURCE_LOCATION="$SCRIPT_DIRECTORY/src" # Contains the files and directories I want to work with.
TARGET_LOCATION="$SCRIPT_DIRECTORY/test-home" # The location I want to link to, in production this would be "~/"

# Link the files from source to the target with a dot appended to the front.
find $SOURCE_LOCATION -mindepth 1 -maxdepth 1 -printf "%P\n" | while read file; do
    echo "Linking $SOURCE_LOCATION/$file to $TARGET_LOCATION/.$file"
    ln -s "$SOURCE_LOCATION/$file" "$TARGET_LOCATION/.$file"
done

Uninstall Script:

#!/bin/bash
# The uninstall script for my vim dotfiles.
# Find the location of the script.
SCRIPT_DIRECTORY="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# The source directory and target directories.
SOURCE_LOCATION="$SCRIPT_DIRECTORY/src" # Contains the files and directories I want to work with.
TARGET_LOCATION="$SCRIPT_DIRECTORY/test-home" # The location I want to link to, in production this would be "~/"

# Remove the links the install script would create.
find $SOURCE_LOCATION -mindepth 1 -maxdepth 1 -printf "%P\n" | while read file; do
    echo "Removing $TARGET_LOCATION/.$file"
    rm -I "$TARGET_LOCATION/.$file"
done


texts: ES6 Javascript (React) code that maps and filters JSON data

texts:
I have the following code in my React app that creates tags out of JSON data:

const files = Object.values(gist.files);
const tags = files.map((file) => {
    let tag = file.language ? file.language : 'Plain Text';
    return tag;
});
let unique = [...new Set(tags)];
const unique_tags = unique.map((tag) => {
    return <Tag value={tag}/>;
});

The code starts by creating an array out of the files' JSON object, next it maps through the files array and returns the value of the language key (Javascript, C, etc.) and if its not undefined, returns plaintext. After that, it filters so there are only unique tags. Finally, it maps through the unique tags and returns a React component.

As you can see, there are two maps and one filter. I feel like this could be done more efficiently.

The JSON is coming from the GitHub Gist API.
For example: https://api.github.com/gists/25c75fa76cf151568d12


texts:
I am trying to make an easy-to-use non-recursive make script that works with several directories.

Everything is packed here.:

Directory structure

/           - root
/bin        - where executable(s) will be made
/obj        - where .o and .d files will be made
/include    - any external includes
/lib1       - library 1 plus its include files
              suppose we have four files here:
              file11.cc, file11.h
              file12.cc, file12.h
/main       - the program
              suppose we have one file here:
              main.cc
              but it includes file11.h and file12.h

Here are the makefiles:

/Makefile

MYCC        = g++

# ======================================================

CF_INCL_EXTRA   :=

CF_DEPS     = -MMD -MP
CF_INCL     = -Iinclude $(CF_INCL_EXTRA)
CF_OPTIM    =
CF_WARN     = -Wall -Wconversion -Wpedantic

CF_MISC     = -D_FILE_OFFSET_BITS=64

CF_ALL      = -std=c++11    \
            $(CF_DEPS)  \
            $(CF_INCL)  \
            $(CF_OPTIM) \
            $(CF_WARN)  \
            $(CF_MISC)

CXX     = $(MYCC) $(CF_ALL)

# ======================================================

LD_ALL      =
LL_ALL      = -lstdc++

LINK        = $(MYCC) $(LD_ALL) -o $@ $^ $(LL_ALL)

SRC     = $(wildcard *.cc)

# ======================================================

A       = bin/
O       = obj/

# ======================================================
# ======================================================
# ======================================================

SUBDIRS = lib1 main

include $(addsuffix /Makefile, $(SUBDIRS))

clean:
    rm -f \
        $(O)*.o     \
        $(O)*.d

/Makefile.sub

$(O)%.o: $(SRC_DIR)%.cc
    $(CXX) \
            -c $<       \
            -o $@

-include $(SRC:%.cc=%.d)

In each of the $(SUBDIRS), there must be a Makefile.

/lib1/Makefile

SRC_DIR := $(dir $(lastword $(MAKEFILE_LIST)))

CF_INCL_EXTRA += -I$(SRC_DIR)

include Makefile.sub

all: $(O)file11.o $(O)file12.o

/main/Makefile

SRC_DIR := $(dir $(lastword $(MAKEFILE_LIST)))

include Makefile.sub

all: $(A)main

$(A)main: $(O)main.o $(O)file11.o $(O)file12.o
    $(LINK)


texts: Entering two integers and returning a decimal fraction

texts:
After a couple of small programs in Python we are now asked to do some basic stuff in Java. I don't really know where to start to improve this and whether it's even necessary.

This is an exercise, so the resulting message for when the denominator is zero should not be taken too seriously.

import java.io.*;

/**
 * Class: GetRationalNumber
 * Takes two integers (numerator and denominator) and
 * return them as a decimal fraction.
 */
class GetRationalNumber {
    public static void main(String[] args) throws IOException {
        int p, q;

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

        System.out.println("Numerator: ");
        p = Integer.parseInt(userInput.readLine());

        System.out.println("Denominator: ");
        q = Integer.parseInt(userInput.readLine());

        if(q == 0) {
            System.out.println(
                "Divison by zero can cause serious trouble to the universe!"
            );
            System.exit(0);
        }

        System.out.println("Result:\n" + (double) p / (double) q);
    }
}


texts: Pulling financial data via IEX Cloud API

texts:
I am pulling some financial data from the IEX Cloud API. Since it is a paid API w/ rate limits, I would like to do this as efficiently as possible (i.e., as few calls as possible). Given that the tickers list is likely to have thousands of indexes (oftentimes with duplicates), is there a better/more efficient way than what I'm currently doing?

(Feel free to use the token in the code, as there is no limit to the number of API calls that you can make to sandboxed data.)

import os
from iexfinance.stocks import Stock
import iexfinance
import pandas as pd

# Set IEX Finance API Token (Test)
os.environ['IEX_API_VERSION'] = 'iexcloud-sandbox'
os.environ['IEX_TOKEN'] = 'Tsk_5798c0ab124d49639bb1575b322841c4'

# List of ticker symbols
tickers = ['MSFT', 'V', 'ERROR', 'INVALID', 'BRK.B', 'MSFT']

# Create output Dataframe
output_df = pd.DataFrame(columns=['Net Income', 'Book Value'])

# Loop through companies in tickers list
for ticker in tickers:

    # Call IEX Cloud API, and output to Dataframe
    try:
        company = Stock(ticker, output_format='pandas')

        try:
            # Get income from last 4 quarters, sum it, and store to temp Dataframe
            df_income = company.get_income_statement(period="quarter", last='4')
            df_income['TTM'] = df_income.sum(axis=1)
            income_ttm = int(df_income.loc['netIncome', 'TTM'])

            # Get book value from most recent quarter, and store to temp Dataframe
            df_book = company.get_balance_sheet(period="quarter")
            book_value = int(df_book.loc['shareholderEquity'])

        # If IEX Cloud errors, make stats = 0
        except (iexfinance.utils.exceptions.IEXQueryError, TypeError, KeyError) as e:
            book_value = 0
            income_ttm = 0

        # Store stats to output Dataframe
        output_df.loc[ticker] = [income_ttm, book_value]

    except ValueError:
        pass

print(output_df)


texts: Favorite Game List utilizing vectors and iterators

texts:
So in learning c++ I have to make a little program that makes a game list that can add games to the list, remove games, and display the list, and it has to use vectors and iterators, so I made the program and need feedback on how to improve it and make it cleaner/better

// Favourite Game list
// Program using vectors and iterators

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<ctime>
#include<cctype>
#include<cstdlib>

using namespace std;

int main()
{
    bool quit = false;
    string game_name;
    vector<string> gameList;
    vector<string>::iterator myIterator;
    vector<string>::const_iterator iter;
    int choice;
    while (!quit)
    {
        cout << "1: Add a Game to List" << endl;
        cout << "2: Remove a Game from the List" << endl;
        cout << "3: List all the Games on the List" << endl;
        cout << "4: Exit the Program" << endl;
        cin >> choice;

        switch (choice)
        {
        case 1:
            cout << "Enter the Game Name to add" << endl;
            cin >> game_name;
            gameList.push_back(game_name);
            break;
        case 2:
            for (iter = gameList.begin(); iter != gameList.end(); ++iter)
                cout << *iter << endl;
            cout << "Here is the list of games enter the one to remove" << endl;
            cin >> game_name;
            iter = find(gameList.begin(), gameList.end(), game_name);
            cout << *iter << "This is the game we will remove" << endl;
            gameList.erase(iter);

            break;

        case 3:
            cout << "Your Games" << endl;
            for (iter = gameList.begin(); iter != gameList.end(); ++iter)
                cout << *iter << endl;
            break;

        case 4:
            quit = true;
            cout << "You chose quit! The Program Will Close Now" << endl;

        }

    }

    return 0;
}


texts:
I have an angle where I need to convert a 'normal' angle to an isometric angle (116 degrees), and I came up with this function. It works, but I was wondering if the math could be optimized/simplified, or if this is the way to go. It's for a mobile game.

public static inline var ISO:Float = 0.45378560551; // (116-90) / 180 * PI=;

function convert(angle:Float):Float
{
  angle -= Math.PI; // corrected angle

  var randomChoosenDistance = 2.0; // could be anything, I'm only interested in final angle.

  // calculate new line, using isometic angle.
  var x1 = Math.cos(angle - ISO);
  var x2 = Math.cos(angle - ISO) * randomChoosenDistance;
  var y1 = Math.sin(angle);
  var y2 = Math.sin(angle) * randomChoosenDistance;

  var dx = x1 - x2;
  var dy = y1 - y2;

  angle = Math.atan2(dy, dx);
  return angle;
}

Can I get the new angle, without calculating the angle between the temporary points I'm creating at the moment?


texts: Numerical Double Integration using numba and scipy

texts:
Please see the following code. I am using it to calculate the double integration. Please help me to improve the code.

import numpy as np
from scipy import integrate
from scipy.special import j1
from scipy.special import j0
from numpy import sin
from numpy import cos
from numpy import pi
import time
import numba as nb
from numba import jit
from numba import cfunc
from numba.types import intc, CPointer, float64
from scipy import LowLevelCallable
from matplotlib import pyplot as plt

q = np.linspace(0.03, 1.0, 1000)
start = time.time()
length = 20000
pd = 0.1
radius = 40
start = time.time()

def jit_integrand_function(integrand_function):
    jitted_function = jit(integrand_function, nopython=True)
    @cfunc(float64(intc, CPointer(float64)),error_model="numpy",fastmath=True)
    def wrapped(n, xx):
        ar = nb.carray(xx, n)
        return jitted_function(ar[0], ar[1], ar[2])
    return LowLevelCallable(wrapped.ctypes)

@jit_integrand_function
def f(theta,z,q):
    def ff(theta, z, q):
        l = length / 2
        qz = q * sin(theta)
        qr = q * cos(theta)
        return (4 * pi * sin(qz * l) * z * j1(qr * z) / (qr * qz)) ** 2

    def g_distribution(z, radius, pd):
        c = radius
        s = pd * c
        return (1 / s)) * np.exp(-0.5 * (((z - radius) / s) ** 2))

    return ff(theta,z,q)*g_distribution(z,radius,pd)* sin(theta)

def lower_inner(z):
    return 0.

def upper_inner(z):
    return 120.

y = np.empty(len(q))
for n in range(len(q)):
    y[n] = integrate.dblquad(f, 0, 1*pi/180, lower_inner, upper_inner,args=(q[n],))[0]

end = time.time()
print(end - start)
plt.loglog(q,y)
plt.show()

Also, I was wondering if I can use GPU for the above code? How much gain I would have for the trouble(I have zero knowledge of programming for GPU use)?


texts:
I'm doing some practice questions from the book Cracking the coding interview and wanted to get some people to review my code for bugs and optimizations.

Question:

  Write a method to decide if two strings are anagrams or not.

/*
Time complexity: O(n^2)
Space complexity: O(n)
*/
bool IsAnagram(std::string str1, std::string str2)
{
    if(str1.length() != str2.length())
        return false;
    for(int i = 0; i < str1.length();i++)
    {
        bool found = false;
        int j = 0;
        while(!found && j < str2.length())
        {
            if(str1[i] == str2[j])
            {
                found = true;
                str2[j] = NULL;
            }
            j++;
        }
        if(!found)
            return false;
    }
    return true;
}


texts:
I have written a merge sort in C and would like any advice on how to improve it. Any advice helps to make the code better!
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

static void mergesort_helper(void *array, uint32_t index, uint32_t length, size_t size_element, int32_t compare(void *, void *), void *storage)
{
   uint32_t i, j, k;
   if(length == 1)
   {
      /*printf("\n%d, %d\n", index, length);*/
      return;
   }

   mergesort_helper(array, index, length / 2, size_element, compare, storage);

   if(length % 2 == 0)
      mergesort_helper(array, (index + (index + length)) / 2, length / 2, size_element, compare, storage);
   else
      mergesort_helper(array, (index + (index + length)) / 2, length / 2 + 1, size_element, compare, storage);

   /*sorting part*/
   i = index;
   j = (index + (index + length)) / 2;
   k = 0;
   while(i < (index + (index + length)) / 2 || j < (index + length))
   {
      if(i < (index + (index + length)) / 2 && (compare(array + i * size_element, array + j * size_element) <= 0 || j >= (index + length)))
      {
          memcpy(storage + k * size_element, array + i * size_element, size_element);
          i++;
      }
      else if(j < (index + length) && (compare(array + i * size_element, array + j * size_element) > 0) || i >= (index + (index + length)) / 2)
      {
          memcpy(storage + k * size_element, array + j * size_element, size_element);
          j++;
      }
      k++;
   }
   memcpy(array + index * size_element, storage, length * size_element);
}

/*
   array -  to be sorted
   length - exclusive
   size_element - how big is one element
*/
void mergesort(void *array, uint32_t length, size_t size_element, int32_t compare(void *, void *))
{
   void *storage;
   if(length == 0)
      return;

   storage = malloc(size_element * length);
   mergesort_helper(array, 0, length, size_element, compare, storage);
   free(storage);
}

/*user code*/
int32_t compare(void *ptr1, void *ptr2)
{
   int32_t *temp_ptr1, *temp_ptr2;
   temp_ptr1 = (int32_t *)ptr1;
   temp_ptr2 = (int32_t *)ptr2;

   if(*temp_ptr1 < *temp_ptr2)
      return -1;
   else if(*temp_ptr1 > *temp_ptr2)
      return 1;

   return 0;
}

int main(void)
{
   uint32_t i;
   int32_t array[] = {6, 4, 3, 2, 7, -100, 1, 0, 5, 8, -100, 8};

   for(i = 0; i < sizeof(array) / sizeof(array[0]); i++)
   {
      printf("%d ", array[i]);
   }
   printf("\n");

   mergesort(array, sizeof(array) / sizeof(array[0]), sizeof(array[0]), &compare);

   for(i = 0; i < sizeof(array) / sizeof(array[0]); i++)
   {
      printf("%d ", array[i]);
   }
   printf("\n");
   return 0;
}


texts:
I feel like I can vastly improve this. Any ideas?

// get orientation of device
getOrientation();

// animate
var num = 400;

if( $('body').hasClass("landscape") ) {
    $('.example').animate({'bottom', 0});
} else {
    $('.example').animate({'bottom', num});
}

function getOrientation(){

    switch(window.orientation) {
     case -90:
     case 90:
    $('body').addClass("landscape");
        // alert('landscape');
        break;
     default:
       //alert('portrait');
       $('body').addClass("portrait");
       break;
     }
}

window.onorientationchange = function() {
  getOrientation();
};


texts: Efficiently/pythonically calculating new Dataframe rows

texts:
I'm new to Pandas, and slightly new to Python as well (but not development in general). I've got a chunk of code that works, but it feels like I'm missing out on the Pandas/Python way of doing something, and would love some feedback.

In short, I'm doing calculations over a fixed period of time (say 60 months) where I apply a bunch of different financial calculations to generate various debits and credits. In this example I'm calculating gross incomes. I have models that represent the Incomes, and want to create Dataframes with the corresponding data that I can eventually sum together for final answers.

Full code for experimentation is available at https://repl.it/repls/BlissfulShabbyColdfusion and repeated here:

### Income Models: ###
start_date   end_date     amount   yearly_raise
2019-01-01   2025-01-01   100.0    0.03
2020-01-01   2022-01-01   200.0    0.

### Base DataFrame: ###
            YearOffset
2019-01-01           0
2020-01-01           1
2021-01-01           2
2022-01-01           3
2023-01-01           4

Then the code is as follows:

import datetime
import numpy as np
import pandas as pd

class Income:
  def __init__(self, start, end, amount, yearly_raise):
    self.start = start
    self.end = end
    self.amount = amount
    self.yearly_raise = yearly_raise

# Two sample income models
incomes = [
  Income(datetime.date(2019, 1, 1), datetime.date(2025, 1, 1), 100, 0.03),
  Income(datetime.date(2020, 1, 1), datetime.date(2022, 1, 1), 200, 0.)
]

# Create dataframe with index of the next five years
dates = pd.date_range('2019-01-01', periods=5, freq='YS')
df = pd.DataFrame(np.arange(len(dates)), index=dates, columns=['YearOffset'])

def calculate_monthly_income(row):
  """Given a dataframe row, add up all incomes applicable to that row/month"""
  value = 0.
  for income in incomes:
    # Filter on overlapping date ranges first
    if pd.Timestamp(income.start) > row.name or pd.Timestamp(income.end) < row.name:
      continue

    value += row['GrossIncome'] + income.amount * (1 + income.yearly_raise) ** row['YearOffset']

  return value

# Initialize a GrossIncome column and do the math
df['GrossIncome'] = 0.
df['GrossIncome'] = df.apply(calculate_monthly_income, axis=1)

And the after, which yields the correct results:

### After Calculations: ###
            YearOffset  GrossIncome
2019-01-01           0   100.000000
2020-01-01           1   303.000000
2021-01-01           2   306.090000
2022-01-01           3   309.272700
2023-01-01           4   112.550881

Thoughts:

I'm using apply() to iterate through the rows and assigning the result back into the dataframe. This works and beats using a for loop, but seems like there's probably a better way to do this.
I'm still using a for ... in to iterate through multiple Incomes
The filtering by applicable date range also seems like I should probably be using some built-in Pandas thing like mask, but I'm unsure of where to start looking.

There's a lot here, I know, but if there's some good feedback on the current approach or recommendations for better approaches, I'd love to hear them!


texts: PHP Doctrine - shared properties between discriminator classes

texts:
I have a single table inheritance type on a class (Resource) that can be one of 3 classes:

SingleDay
MultiDay
Accommodation

SingleDay has properties:

QTY
hours_offset
minutes_offset
hours_duration
minutes_duration

MultiDay has properties:

QTY
start_day
start_time
hours_duration
minutes_duration

Accommodation has properties:

QTY
start_day
end_day
start_time
end_time

As I've highlighted above, some properties are shared between ALL classes, some properties are shared between SingleDay and MultiDay, some properties are shared between MultiDay and Accommodation and some properties are not shared

I wondered how best to deal with this?

I was thinking on the top class (Resource) to have the shared properties as protected, and then on each of the classes that use the property to have the same getter and setter?

/*
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="multi_day", type="integer")
 * @DiscriminatorMap({"M" = "MultiDay", "S" = "SingleDay", "A" = "Accommodation"})
*/
class Resource {
    /*
     * @var integer $qty
     * @Column(name="qty", type="integer", nullable=false, unique=false)
     */
    private $qty;

    /**
     * @var integer $hoursDuration
     *
     * @Column(name="hours_duration", type="integer", nullable=false, unique=false)
     */
    protected $hoursDuration;

    /**
     * @var integer $minutesDuration
     *
     * @Column(name="minutes_duration", type="integer", nullable=false, unique=false)
     */
    protected $minutesDuration;

    ...
}

class SingleDay extends Resource {
     /**
     * @var integer $hoursOffset
     *
     * @Column(name="hours_offset", type="integer", nullable=false, unique=false)
     */
    private $hoursOffset;

    /**
     * @var integer $minutesOffset
     *
     * @Column(name="minutes_offset", type="integer", nullable=false, unique=false)
     */
    private $minutesOffset;

    /**
     * @return int
     */
    public function getHoursOffset()
    {
        return $this->hoursOffset;
    }

    /**
     * @param int $hoursOffset
     */
    public function setHoursOffset($hoursOffset)
    {
        $this->hoursOffset = $hoursOffset;
    }

    /**
     * @return int
     */
    public function getMinutesOffset()
    {
        return $this->minutesOffset;
    }

    /**
     * @param int $minutesOffset
     */
    public function setMinutesOffset($minutesOffset)
    {
        $this->minutesOffset = $minutesOffset;
    }

    /**
     * @return int
     */
    public function getHoursDuration()
    {
        return $this->hoursDuration;
    }

    /**
     * @param int $hoursDuration
     */
    public function setHoursDuration($hoursDuration)
    {
        $this->hoursDuration = $hoursDuration;
    }

    /**
     * @return int
     */
    public function getMinutesDuration()
    {
        return $this->minutesDuration;
    }

    /**
     * @param int $minutesDuration
     */
    public function setMinutesDuration($minutesDuration)
    {
        $this->minutesDuration = $minutesDuration;
    }

    ...
}

Is this the best way to go about this?  Is protected properties OK in this situation?  Should I also have private properties on each class as well as the getters and setters and would Doctrine be able to deal with multiple declarations of the same column OK?


texts: 2D Platformer Collision Detection/Resolution

texts:
I am working on a 2D tile based platformer and was hoping to get someone to review my collision detection. I've only included the X collision check since the Y is essentially the same. Any suggestions/criticisms are appreciated.

    // Corrects X movement if a collision occurs.
    private void checkXCollision()
    {
        // Find the range of tiles the player intersects
        Point topLeft = new Point(((int)(xtemp + dx) - collisionWidth/2) / map.getTileSize(), ((int)ytemp - collisionHeight/2) / map.getTileSize());
        Point bottomRight = new Point(((int)(xtemp + dx) + collisionWidth/2) / map.getTileSize(), ((int)ytemp + collisionHeight/2) / map.getTileSize());

        // Left
        if(dx < 0)
        {
            boolean collision = false;
            for(int row = topLeft.y; row <= bottomRight.y; row++)
            {
                if(map.getType(row, topLeft.x) == Tile.SOLID)
                {
                    collision = true;
                    break;
                }
            }

            if(collision)
            {
                dx = 0;

                // Move player to edge of solid tile
                int col = ((int)(xtemp + dx) - collisionWidth/2) / map.getTileSize();
                xtemp = col * map.getTileSize() + collisionWidth / 2;
            }
            else
            {
                xtemp += dx;
            }
        }

        // Right
        if(dx > 0)
        {
            boolean collision = false;
            for(int row = topLeft.y; row <= bottomRight.y; row++)
            {
                if(map.getType(row, bottomRight.x) == Tile.SOLID)
                {
                    collision = true;
                    break;
                }
            }

            if(collision)
            {
                dx = 0;

                // Move player to edge of solid tile
                int col = ((int)(xtemp + dx) + collisionWidth/2) / map.getTileSize();
                xtemp = (col + 1) * map.getTileSize() - collisionWidth / 2 - 1;
            }
            else
            {
                xtemp += dx;
            }
        }
    }


texts:
My assignment is to to create two threads running functions (called vow and cons). The threads take turns printing the respective words of the phrase supplied from a text file. The main thread shouldn't post anything (only cons and vow functions should print). I can't use synchronization primitives such as mutexes for thread coordination. But I can use yield(). I think I might have my answer below but I also might be way off and I didn't use yield() at all.

Could someone please take a look and tell me if this meets the requirements I listed above.

phrase.txt:

  In computer architecture, multithreading is the ability of a central processing unit (CPU) or a single core in a multi-core processor to execute multiple processes or threads concurrently, appropriately supported by the operating system.

#include <iostream>
#include <fstream>
#include <thread>

void cons(std::string currWord){
    std::cout << "cons: " << currWord << "\n";
}

void vow(std::string currWord){
    std::cout << "vow: " << currWord << "\n";
}

bool checkVowel(std::string word) {
    char vowels[10] = {'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'};
    for(int i = 0; i < 10; i++) {
        if(word[0] == vowels[i]) {
            return true;
        }
    }
    return false;
}

int main() {
    std::string currWord;
    std::ifstream input;
    input.open("phrase.txt");

    if(input.is_open()) {

    currWord = std::string();

    while(!input.eof()) {
            input >> currWord;
        if(checkVowel(currWord)) {
            std::thread vowThread(vow, currWord);
            vowThread.join();
        }
        else {
            std::thread consThread(cons, currWord);
            consThread.join();
        }
    }

    input.close();
    }

    else {
        std::cout << "Error: File not opened";
    }

    return 0;
}

bool checkVowel(std::string);
void vow(std::string);
void cons(std::string);


texts: Updates list in haskell to remove duplication

texts:
The task in question allows a user to re-rate a film such that only the latest rating from the user should remain in the database.
Initially I solved this problem in a very basic manor?

This was my result:

type Rating = (String, Int)
type Film = (String, String, Int, [Rating])
--Example ("Blade Runner","Ridley Scott",1982, [("Amy",5),("Bill",8)])

where the functions:

--Find selected film, isolate into new List
getFilm :: String -> [Film] -> [(Film)]
getFilm search aFilm = [(title,dir,year,ratings) | (title,dir,year,ratings) <- aFilm, search == title]

--Update the new film and pull details for amendment, STORE
pullTitle :: [(Film)] -> String
pullTitle [(title,_,_,_)] = title

pullDirector :: [(Film)] -> String
pullDirector [(_,director,_,_)] = director

pullYear :: [(Film)] -> Int
pullYear [(_,_,year,_)] = year

pullRatings :: [(Film)] -> [Rating]
pullRatings [(_,_,_,rating)] = rating

newRatings :: [Rating] -> Rating -> [Rating]
newRatings oldRatings (newUser,newRate) = [(user,rate) | (user,rate) <- oldRatings, user /= newUser] ++ [(newUser,newRate)]

--Database without selected film
updateDatabase :: String -> [Film] -> [(Film)]
updateDatabase search aFilm = [(title,dir,year,ratings) | (title,dir,year,ratings) <- aFilm, search /= title]

--Adds new film to a database
updatedFilm :: String -> String -> Int -> [Rating] -> [Film] -> [Film]
updatedFilm name director yearOfRel ratings database = database ++ [(name,director,yearOfRel,ratings)]

--Add new film to updated Database
formulateFilm :: [(Film)] -> [(Film)] -> Rating -> [(Film)]
formulateFilm soloFilm updatedFilms updateRating = updatedFilm (pullTitle soloFilm) (pullDirector soloFilm) (pullYear soloFilm) (newRatings (pullRatings soloFilm) updateRating) updatedFilms

--Compiling to for finalcome
rateMovie :: String -> Rating -> [Film] -> [(Film)]
rateMovie mTitle newRating oldDatabase = formulateFilm (getFilm mTitle oldDatabase) (updateDatabase mTitle oldDatabase) newRating

I have changed the following functions to make use of filters:

getFilm :: String -> [Film]
getFilm search = filter(\(title,_,_,_) -> search == title) testDatabase

updateDatabase :: String -> [Film]
updateDatabase search = filter(\(title,_,_,_) -> search /= title) testDatabase

Could someone advise me on how I would use maps to get the selected films data from getFilm :: String -> [Film], similar to the (pull*) functions?


texts: Allowing switching between operator[] and at() based on NDEBUG

texts:
The problem:

std::vector and other containers have two functions for accessing / modifying their content: operator[] and at().

at() is meant for debugging, to catch out-of-bound bugs. However, at() is also quite a lot slower than operator[]. Both above facts would yearn for a way to switch between the use of at() and operator[] based on whether it is a debug build or a production build, especially if performance matters.

However, I can see no such easy way. Sadly, standard containers don't offer a flag or something that would allow this.

I tried to write a simple wrapper that would switch between at() and operator[] based on whether or not NDEBUG is defined, in line with how the assert macro works.

The code:

// aoo = At Or Operator[]
template<class Container>
typename Container::reference
aoo(Container &cont, typename Container::size_type index) {
  #ifndef NDEBUG
    return cont.at(index);
  #else
    return cont.operator[](index);
  #endif
}

// Needed for rvalue references to work
template<class Container>
typename Container::const_reference
aoo(Container const &cont, typename Container::size_type index) {
  #ifndef NDEBUG
    return cont.at(index);
  #else
    return cont.operator[](index);
  #endif
}

The use:

void testNormalUse()
{
    std::vector<int> vec(100);
    aoo(vec, 50) = 5;
    std::cout << aoo(vec, 50) << std::endl;
}

void testRequireConst()
{
    const std::vector<int> vec(100, 5);
    std::cout << aoo(vec, 50) << std::endl;
}

void testRvalueRef()
{
    std::vector<int>vec(100, 5);
    std::cout << aoo(std::move(vec), 50) << std::endl;
}

void test2D()
{
    std::vector<std::vector<int>> vec(100, std::vector<int>(100, 5));
    std::cout << aoo(aoo(vec, 50), 50) << std::endl;
}

int main() {
    testNormalUse();
    testRequireConst();
    testRvalueRef();
    test2D();
}

Ideone

Admittedly, using this with 2d arrays is a pain:

aoo(aoo(vec, 50), 50)

But I see a no better way, except for a macro solution, which simplifies this case at the cost of a more weird syntax.

I freely admit that I posted those two questions mostly to ask you if the whole idea makes any sense, and if it does, which of the two solutions is better.


texts:
There will be a huge object mapping (transforming) with a lot of calculations and logic for some fields.

I would like to refactor this to classes or some kind of separation so it will be easily testable (jest) for each field.  How would you abstract these to a few classes or which design pattern that is best suited for this?

For example:

 const data = {
   id: 111,
   items: [
     {
       title: "Title One",
       qty: "2",
       price: "1.00",
       vat: 20,
     },
     {
      title: "Title Two",
      qty: "3",
      price: "5.00",
      vat: 20,
    }
   ],
   address: {
    price: 5,
    name: "Tommy",
    line_1: "Line 1",
    line_2: "Line 2",
    line_3: "Line 3",
   }
 }

function mapData(data) {
  const orderItems = data.items.map(item => {
    return {
      Name: item.title,
      Qty: parseInt(item.qty),
      Price: item.price,
      Total: getOrderItemTotal(item),
      TotalIncVat: getOrderItemTotalIncVat(item),
       // and many more fields
    }
  });

  return {
     Id:  data.id,
     Total: getOrderTotal(data, orderItems),
     Items: orderItems,
     DeliveryAddress: {
       ShippingCost: data.address.price,
       Name: data.address.name,
       Address1: data.address.line_1,
       Address2: data.address.line_2,
       Address3: data.address.line_3,
     },
      // and many more fields
  }
}

function getOrderTotal(data, orderItems) {
  const totalCostItems = orderItems.reduce((acc, item) => {
    return acc + parseFloat(item.TotalIncVat);
  }, 0);

  return (totalCostItems + data.address.price).toFixed(2);
}

function getOrderItemTotal(item) {
  const totalPrice = parseFloat(item.price) * parseInt(item.qty);

  return totalPrice.toFixed(2);
}

function getOrderItemTotalIncVat(item) {
  const totalPrice = parseFloat(getOrderItemTotal(item));
  const vat = (item.vat / 100) * totalPrice;

  return (totalPrice + vat).toFixed(2);
}

console.log(mapData(data));

Edit: I would like to know what the best way to refactor this mapping to multiple files (or Classes?) and calculation logic as in clean code and follow SOLID principles.  To follow SOLID principles, I am thinking to create Order class, OrderItem class and DeliveryAddress class?

Each class would have some calculations method.

If class is not necessary, what are alternative options?


texts:
K caterpillars are eating their way through N leaves, each caterpillar
  falls from leaf to leaf in a unique sequence, all caterpillars start
  at a twig at position 0 and falls onto the leaves at position between
  1 and N. Each caterpillar j has as associated jump number Aj. A
  caterpillar with jump number j eats leaves at positions that are
  multiple of j. It will proceed in the order j, 2j, 3j…. till it
  reaches the end of the leaves and it stops and build its cocoon. Given
  a set A of K elements K<-15, N<=10^9, we need to determine the number
  of uneaten leaves.

  Input:

  N = No of uneaten leaves
  K = No. of caterpillars
  A = Array of integer jump numbers

  Output:

  The integer nu. Of uneaten leaves

  Sample Input:

10
3
2
4
5

  Output:

4

  Explanation:

  [2, 4, 5] is a j member jump numbers, all leaves which
  are multiple of 2, 4, and 5 are eaten, leaves 1,3,7,9 are left, and
  thus the no. 4

Detailed explanation Caterpillars and Leaves

public static int findUneatenLeaves(int[] array, int n) {
    ArrayList<Integer> uneatenLeaves = new ArrayList<Integer>();
    ArrayList<Integer> eatenLeaves = new ArrayList<Integer>();
    for (int i = 1; i <= n; i++) {
        uneatenLeaves.add(i);
    }
    // 1. find the multiple of the eatenLeaves
    for (int i = 0; i < array.length; i++) {
        eatenLeaves.add(array[i]);
        for (int j = 1; j < uneatenLeaves.size(); j++) {
            if (array[i] * uneatenLeaves.get(j) <= n) {
                eatenLeaves.add(array[i] * uneatenLeaves.get(j));
            }
        }
    }
    for (int i = 0; i < eatenLeaves.size(); i++) {
        for (int j = 1; j < uneatenLeaves.size(); j++) {
            if (eatenLeaves.get(i) == uneatenLeaves.get(j)) {
                uneatenLeaves.remove(uneatenLeaves.get(j));
            }
        }
    }
    System.out.println(uneatenLeaves.size());
    return uneatenLeaves.size();
}

How can this be optimized?