jQuery dropdown menu I wrote this jQuery code as I could for a dropdown menu.

But I'm sure there is a way to make this code shorter.

$(document).ready(function() {
    $('#show-menu-1').on('click touch', openSubMenu);
    $('#close-menu-1').on('click touch', closeSubMenu);

    $(document).on('click touch', function(event) {
        if (!$(event.target).closest('#menu-1').length) {
            $('#menu-1 > .main-menu__submenu').removeClass('main-menu__submenu--active');
            $('#menu-1').removeClass('main-menu__item--active');
        }
    });

    function openSubMenu() {
        $('#menu-1 > .main-menu__submenu').addClass('main-menu__submenu--active');
        $('#menu-1').addClass('main-menu__item--active');
    };

    function closeSubMenu() {
        $('#menu-1 > .main-menu__submenu').removeClass('main-menu__submenu--active');
        $('#menu-1').removeClass('main-menu__item--active');
    };
});

$(document).ready(function() {
    $('#show-menu-2').on('click touch', openSubMenu);
    $('#close-menu-2').on('click touch', closeSubMenu);

    $(document).on('click touch', function(event) {
        if (!$(event.target).closest('#menu-2').length) {
            $('#menu-2 > .main-menu__submenu').removeClass('main-menu__submenu--active');
            $('#menu-2').removeClass('main-menu__item--active');
        }
    });

    function openSubMenu() {
        $('#menu-2 > .main-menu__submenu').addClass('main-menu__submenu--active');
        $('#menu-2').addClass('main-menu__item--active');
    };

    function closeSubMenu() {
        $('#menu-2 > .main-menu__submenu').removeClass('main-menu__submenu--active');
        $('#menu-2').removeClass('main-menu__item--active');
    };
});

You can make this shorter by modifying your html to have the id in a data attribute and using classes, but this is what I have based on the info you've given.

$(function() {

    function initializeMenu(id) {
       $('#show-menu-' + id).on('click touch', function() { toggleMenu(id, true); });
       $('#close-menu-' + id).on('click touch', function() { toggleMenu(id, false); });

       $(document).on('click touch', function(event) {
            if (!$(event.target).closest('#menu-' + id).length) {
                toggleMenu(id, false);
            }
       });
    }

    function toggleMenu(id, open) {
        $('#menu-' + id + ' > .main-menu__submenu').toggleClass('main-menu__submenu--active', open);
        $('#menu-' + id).toggleClass('main-menu__item--active', open);
    }

    for(var i = 1; i <= 2; i++) {
        initializeMenu(i);
    }
});


Converting Decimals to Fractions with JavaScript - Simplify & Improve I wrote a simple script that converts a decimal to a mixed number, proper, or improper fraction depending on the inputed decimal.

It works but I think it could be improved as it hangs when large decimals are used. Please review and let me know how I could improve and simplify it. Thanks.

My script on JS Bin: http://jsbin.com/axulob/1/edit

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

highestCommonFactor should take 2 integers as parameter instead of relying on the variable numerator and `denominator'. Also, you could find it using Euclid'a algorithm.
I am wrong is saying that this piece of code :

var rightDecimalPart = decimalArray[1];
// Save decimal part only for later use
var decimalOnly = "0." + rightDecimalPart;
// Find the decimal multiplier
var multiplier = "1";
for (var i = 0; i < rightDecimalPart.length; i++) {
    multiplier += "0";
}
// Create numerator by multiplying the multiplier and decimal part together
var numerator = Number(multiplier) * Number(decimalOnly);

is here to transform a number such as 78924 in 0.78924 and then check that have to multiply it by 100000 to get an integer which is ... 78924.

Edit
After a first cleanup, I get :

function highestCommonFactor(a,b) {
    if (b==0) return a;
    return highestCommonFactor(b,a%b);
}

var decimal = "1.75";
var decimalArray = decimal.split(".");
var leftDecimalPart = decimalArray[0];
var rightDecimalPart = decimalArray[1];

var denominator = "1";

for (var i = 0; i < rightDecimalPart.length; i++) {
    denominator += "0";
}
document.getElementById("debug").innerText = denominator;
var factor = highestCommonFactor(rightDecimalPart, denominator);

// Simplify the fraction by dividing the numerator and denominator by the factor
var denominator = Number(denominator) / Number(factor);
var numerator = (Number(rightDecimalPart) / Number(factor)) + (leftDecimalPart * denominator);

// Display solution as a proper fraction or improper fraction (depending on input)
document.getElementById("divSolution").innerText = numerator + "/" + denominator;

I'll try to go a step further.

Edit 2
After a rewriting of the calculation, here's what I got :

function highestCommonFactor(a,b) {
    if (b==0) return a;
    return highestCommonFactor(b,a%b);
}

var decimal = "1.75";
var decimalArray = decimal.split(".");
var leftDecimalPart = decimalArray[0]; // 1
var rightDecimalPart = decimalArray[1]; // 75

var numerator = leftDecimalPart + rightDecimalPart // 175
var denominator = Math.pow(10,rightDecimalPart.length); // 100
var factor = highestCommonFactor(numerator, denominator); // 25
denominator /= factor;
numerator /= factor;

document.getElementById("divSolution").innerText = numerator + "/" + denominator;


Two similar factory classes to instantiate services I'm working on building a library to help you bootstrap the development of a Java API. The premise is, you can have your controllers implement interfaces like IGetController<SomeEntity> or IListController<SomeEntity>.  These interfaces have default methods to implement their endpoint, and use a service factory to get the appropriate service to do the bulk of the work.  These services are also interfaces, and have default methods which get a repository (by calling getRepository on the IBaseService they extend).  There's a lot of "magic" going on here to inspect the genericInterfaces on the class, and then getting the type arguments to determine what entity we're working with.

The problem I'm having is consolidating my factories.  Take a look at these two factory classes:

GetServiceFactory:

package apibuilder.service.factory;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import apibuilder.entity.BaseEntity;
import apibuilder.service.IGetService;

public class GetServiceFactory {
    private static final Map<Type, IGetService<? extends BaseEntity>>
            registrationMap = new HashMap<>();

    public static <T extends BaseEntity> IGetService<T> getService(final Type entityType) {
        if (registrationMap.containsKey(entityType)) {
            //noinspection unchecked
            return (IGetService<T>) registrationMap.get(entityType);
        }
        return null;
    }

    public static <T extends BaseEntity> void registerServices(final IGetService<T>[] services) {
        for (IGetService<T> service : services) {
            Type entityType = ((ParameterizedType) service.getClass().getGenericInterfaces()[0])
                    .getActualTypeArguments()[0];
            registrationMap.put(entityType, service);
        }
    }
}

ListServiceFactory:

package apibuilder.service.factory;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import apibuilder.entity.BaseEntity;
import apibuilder.service.IListService;

public class ListServiceFactory {
    private static final Map<Type, IListService<? extends BaseEntity>>
            registrationMap = new HashMap<>();

    public static <T extends BaseEntity> IListService<T> getService(final Type entityType) {
        if (registrationMap.containsKey(entityType)) {
            //noinspection unchecked
            return (IListService<T>) registrationMap.get(entityType);
        }
        return null;
    }

    public static <T extends BaseEntity> void registerServices(final IListService<T>[] services) {
        for (IListService<T> service : services) {
            Type entityType = ((ParameterizedType) service.getClass().getGenericInterfaces()[0])
                    .getActualTypeArguments()[0];
            registrationMap.put(entityType, service);
        }
    }
}

As you can see, they're nearly identical.  They create a map to get the proper service per entity, and then have methods to build the map, and get a service from the map.  I feel like these can be consolidated into some sort of BaseServiceFactory, but I'm having a hard time actually pulling it off.

Problem is that you prefer static methods. This way you effectively throw away benefits of polymorphism.

Also, when ever you find duplicated code you should carefully think if it might belong into a class of its own.

If you could open your mint to an OO approach you could move common behavior into a (non static) utility class and inject that common behavior into the concrete Factories. Or you go the usual OO way to create an abstract factory having the common code and have the concrete factories inheriting from it.

  but why do static methods throw away polymorphism benefits?  – Thufir

Static method imply early binding. All accessors to a method are known at compile time of the method implementation. Also all implementors of a static method are known at compile time of the accessors. You cannot provide a new behavior of a method unless you compile the accessors needing this new behavior.

class A {
  static void method(){
     System.out.println("static method in A");
  }
}

class B extends A {
  static void method(){
     System.out.println("static method B");
  }
}

class  C {
  static void main(String[] args){
     A.method(); // outputs "static method in A"
     B.method(); // outputs "static method in B"
     A[] a = {new A(), new B()};
     a[0].method();  // outputs "static method in A"
     a[1].method();  // outputs "static method in A" although instance is f type `B`
  }
}

  And, is polymorphism really so beneficial? – Thufir

Polymorphism is no value as such.

But if you doubt the value of polymorphism in general you might rather use a programing language that does not bother you with such  gratuitous  concepts...


PDO / HASH Registration form I just made my first registration form with password confirmation, hashing with BCRYPT and PDO. As a beginner, looking around on StackExchange, I seem to miss a lot.

To keep it simple for myself, I coded PHP and HTML on the same page. Hence I'm just into PHP for 3 days now.

if (isset($_POST['register'])) {

    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $cPassword = $_POST['cPassword'];

    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];

    $host = 'localhost';
    $db = 'loginform';
    $user = 'root';
    $pass = '';
    $charset = 'utf8mb4';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";

    try {
        $pdo = new PDO($dsn, $user, $pass, $options);
    } catch (\PDOException $e) {
        throw new \PDOException($e->getMessage(), (int)$e->getCode());
    }

    if ($password != $cPassword)
        $msg = "Wachtwoord komt niet overeen!";

    else {

        $hash = password_hash($password, PASSWORD_BCRYPT);

        $sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $email, $hash]);

        $msg = "U bent geregistreerd!";
        header( "Refresh:3; url=/Login2/inloggen.php", true, 303);

    }
}

That's a very good code. Speaking of the things that are written in it, there is very little I would change. Only a few things are coming to my mind,

I would move the database connection code into a separate file and then just include in other scripts that needed a database connection.
Using the Refresh header is old fashioned, inconvenient and buggy. I would rather redirect a user to the newly created account page. So they would know that an account has been created at once.
I wouldn't hardcode a particular hashing algorithm, and rather use PASSWORD_DEFAULT instead.

That's all. But of course some things could be added to this code as well. You can add some verifications, like as to see

if the username is not empty or already exists
whether the password is not strong enough
whether email follows the proper format or already exists
all other verifications you can think of

And for this purpose it is useful to make $msg not a string but an array of strings, to collect all possible errors in one variable. You can check this approach in my recent answer


Hex String to Bytes (NSData) I'm trying to convert this Objective-C code (originally found in this Stack Overflow question) which turns an NSString into NSData to Swift:

- (NSData *)dataFromHexString {
    const char *chars = [self UTF8String];
    int i = 0, len = self.length;

    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;

    while (i < len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }

    return data;
}

My first pass looked like this:

func hexStringToBytes(hexString: String) -> NSData? {
    guard let chars = hexString.cStringUsingEncoding(NSUTF8StringEncoding) else { return nil}
    var i = 0
    let length = hexString.characters.count

    let data = NSMutableData(capacity: length/2)
    var byteChars: [CChar] = [0, 0, 0]

    var wholeByte = CUnsignedLong()

    while i < length {
        byteChars[0] = chars[i++]
        byteChars[1] = chars[i++]
        i+=1
        wholeByte = strtoul(byteChars, nil, 16)
        data?.appendBytes(&wholeByte, length: 1)
    }

    return data
}

I realized I could optimize this further, since ++ is deprecated and will be removed in Swift 3:

func hexStringToBytes(hexString: String) -> NSData? {
    guard let chars = hexString.cStringUsingEncoding(NSUTF8StringEncoding) else { return nil}
    var i = 0
    let length = hexString.characters.count

    let data = NSMutableData(capacity: length/2)
    var byteChars: [CChar] = [0, 0, 0]

    var wholeByte: CUnsignedLong = 0

    while i < length {
        byteChars[0] = chars[i]
        i+=1
        byteChars[1] = chars[i]
        i+=1
        wholeByte = strtoul(byteChars, nil, 16)
        data?.appendBytes(&wholeByte, length: 1)
    }

    return data
}

And then as an extension on String:

extension String {

    func dataFromHexString() -> NSData? {
        guard let chars = cStringUsingEncoding(NSUTF8StringEncoding) else { return nil}
        var i = 0
        let length = characters.count

        let data = NSMutableData(capacity: length/2)
        var byteChars: [CChar] = [0, 0, 0]

        var wholeByte: CUnsignedLong = 0

        while i < length {
            byteChars[0] = chars[i]
            i+=1
            byteChars[1] = chars[i]
            i+=1
            wholeByte = strtoul(byteChars, nil, 16)
            data?.appendBytes(&wholeByte, length: 1)
        }

        return data
    }
}

A few questions:

How can I optimize the ugly i+=1 lines?
Is cStringUsingEncoding(NSUTF8StringEncoding) the correct way to get the [CChar] from the string?
Since this is almost a direct translation from Objective-C, is there any way to make this more "Swifty," say by using map or stride, without sacrificing speed?

First note that your code does not detect invalid input data.
For example, the string "XX" is just converted to a zero byte.
Detecting invalid input with strtoul() is a bit tricky, there is an
alternative suggestion below.

let data = NSMutableData(capacity: length/2)

creates an optional NSData. If that fails then the optional chaining

data?.appendBytes(&wholeByte, length: 1)

simply does nothing, i.e. the error is ignored. Better check the
success immediately:

guard let data = NSMutableData(capacity: length/2) else { return nil }

  How can I optimize the ugly i+=1 lines?

By using stride:

func dataFromHexString() -> NSData? {
    guard let chars = cStringUsingEncoding(NSUTF8StringEncoding) else { return nil}
    let length = characters.count

    guard let data = NSMutableData(capacity: length/2) else { return nil }
    var byteChars: [CChar] = [0, 0, 0]
    var wholeByte: CUnsignedLong = 0

    for i in 0.stride(to: length, by: 2) {
        byteChars[0] = chars[i]
        byteChars[1] = chars[i + 1]
        wholeByte = strtoul(byteChars, nil, 16)
        data.appendBytes(&wholeByte, length: 1)
    }

    return data
}

This does not change the performance. The time to convert a 512,000
character string is 0.0140 sec on my computer (test code at the end).

  Is cStringUsingEncoding(NSUTF8StringEncoding) the correct way to get the [CChar] from the string?

That is fine as far as I can see. There is also

self.withCString {
    // $0 is a pointer to the NUL-terminated UTF-8 string
}

which I personally prefer, but I could not detect a difference in
the performance.

  Since this is almost a direct translation from Objective-C, is there any way to make this more "Swifty," say by using map or stride, without sacrificing speed?

stride() is already used for the iteration. I do not see an use-case
for map() here.

But the performance can be improved considerably.
As observed here
and here, accessing the UTF-16 view
of a Swift string is very fast. This leads to the following implementation:

func dataFromHexString() -> NSData? {

    let utf16 = self.utf16
    guard let data = NSMutableData(capacity: utf16.count/2) else { return nil }

    var byteChars: [CChar] = [0, 0, 0]
    var wholeByte: CUnsignedLong = 0
    var i = utf16.startIndex
    while i != utf16.endIndex {
        byteChars[0] = CChar(truncatingBitPattern: utf16[i])
        byteChars[1] = CChar(truncatingBitPattern: utf16[i.advancedBy(1, limit: utf16.endIndex)])
        wholeByte = strtoul(byteChars, nil, 16)
        data.appendBytes(&wholeByte, length: 1)
        i = i.advancedBy(2, limit: utf16.endIndex)
    }
    return data
}

which converts the 512,000 character string in 0.00185 sec.
Note that invalid input is still not detected.

We can still make it faster by converting the UTF-16 code points
"manually" instead of using strtoul(). This is more code,
but again faster, and also detects all kinds of invalid input:

func dataFromHexString() -> NSData? {

    // Convert 0 ... 9, a ... f, A ...F to their decimal value,
    // return nil for all other input characters
    func decodeNibble(u: UInt16) -> UInt8? {
        switch(u) {
        case 0x30 ... 0x39:
            return UInt8(u - 0x30)
        case 0x41 ... 0x46:
            return UInt8(u - 0x41 + 10)
        case 0x61 ... 0x66:
            return UInt8(u - 0x61 + 10)
        default:
            return nil
        }
    }

    let utf16 = self.utf16
    guard let data = NSMutableData(capacity: utf16.count/2) else {
        return nil
    }

    var i = utf16.startIndex
    while i != utf16.endIndex {
        guard let
            hi = decodeNibble(utf16[i]),
            lo = decodeNibble(utf16[i.advancedBy(1, limit: utf16.endIndex)])
        else {
                return nil
        }
        var value = hi << 4 + lo
        data.appendBytes(&value, length: 1)
        i = i.advancedBy(2, limit: utf16.endIndex)
    }
    return data
}

The time to convert the 512,000 character string is now
0.0008 seconds. This is more than 17 times faster than the original code.

Test code:

let s1 = (0 ... 255).map { String(format:"%02x", $0) }.joinWithSeparator("")
let str = Repeat(count: 100, repeatedValue: s1).joinWithSeparator("")
print(str.characters.count) // 51200

let start = NSDate()
if let data = str.dataFromHexString() {
    let duration = NSDate().timeIntervalSinceDate(start)
    print(duration)
} else {
    print("failed")
}

The tests were done on a MacBook, with the program compiled in
Release mode.


RFC PS Rasterizer Library API We've got the basic functionality of using my postscript interpreter, xpost, as a library. I'd like to solicit some feedback from the community on the API setup. This example program, called xpost_client.c illustrates the API to rasterize a small EPS into a 792x612 BGR buffer, which it then dumps to a file as an ASCII PPM file (so you can check it with a text editor).

/*
   This is a simple example of a client calling xpost as a library
   with a postscript program, desiring the raster data of the
   generated image.

TODO:
    define buffer interchange type
 */

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

#include "xpost.h"
#include "xpost_memory.h"
#include "xpost_object.h"
#include "xpost_context.h"
#include "xpost_interpreter.h"

char *prog =
    "%%BoundingBox: 200 300 400 500\n"
    "300 400 100 0 360 arc\n"
    "fill\n"
    "showpage\n";

int main() {
    void *buffer_type_object;
    xpost_init();
    xpost_create("bgr",
            XPOST_OUTPUT_BUFFEROUT,
            &buffer_type_object,
            XPOST_SHOWPAGE_RETURN,
            1);
    xpost_run(XPOST_INPUT_STRING, prog);
    {
        unsigned char *buffer = buffer_type_object;
        int i,j;
        FILE *fp = fopen("xpost_client_out.ppm", "w");
        fprintf(fp, "P3\n612 792\n255\n");
        for (i=0; i<792; i++) {
            for (j=0; j<612; j++) {
                unsigned int red, green, blue;
                red = *buffer++;
                green = *buffer++;
                blue = *buffer++;
                ++buffer;
                fprintf(fp, "%d ", red);
                fprintf(fp, "%d ", green);
                fprintf(fp, "%d ", blue);
                if ((j%20)==0)
                    fprintf(fp, "\n");
            }
            fprintf(fp, "\n");
        }
        fclose(fp);
    }
    xpost_destroy();
    free(buffer_type_object);
    xpost_quit();
    return 0;
}

Currently only the bgr device offers the OUTPUT_BUFFEROUT option. The C code assumes that the PS program contains a showpage to trigger the copying of the buffer. No showpage :: your buffer's a trash-pointer, dude.

I do plan to sweep-up the auxiliary headers into a single "xpost.h" header file. But that's the full list you currently need from the top-level.

One obvious flaw is that there's currently no way to set the geometry or resolution. It's 1-pt per pixel, and that's that. It's also currently hardcoded at letter dimensions, (sorry, rest of the world). Does anybody have ideas about the best way to interface
for that at the top level?

Any other options that a library user might want? Does the buffer-type struct need anything more than height, width and stride? Should stride count words or bytes?

In unixes, Cygwin and mingw, you can

hg clone https://luser.droog@code.google.com/p/xpost/

then read the INSTALL stuff, but the quick version is

./configure
make
sudo make install

then you can run

xpost_client

to produce a (buggy) rendering of a filled circle in xpost_client_out.ppm which loads ok for me in Gimp.

The program can also be browsed online at:

http://code.google.com/p/xpost/source/browse/src/bin/xpost_client.c
http://code.google.com/p/xpost/source/browse/src/lib/xpost.h
http://code.google.com/p/xpost/source/browse/src/lib/xpost_memory.h
http://code.google.com/p/xpost/source/browse/src/lib/xpost_object.h
http://code.google.com/p/xpost/source/browse/src/lib/xpost_context.h
http://code.google.com/p/xpost/source/browse/src/lib/xpost_interpreter.h

Note: I have also posted this code to comp.lang.postscript for a more discussion-type discussion.

Also note: The interpreter produces temporary files in the current directory named gmemXXXXXX lmemXXXXXX xdumpXXXXXX (where XXXXXX is a system-generated unique filename sequence) which may needlessly accumulate diskspace. They periodically must be manually removed. And be careful with code that may do an infinite series of pushes to the stack, lmemXXXXXX may grow very large to hold a huge stack.

Based on these two lines…

xpost_create("bgr",
        XPOST_OUTPUT_BUFFEROUT,
        &buffer_type_object,
        XPOST_SHOWPAGE_RETURN,
        1);
xpost_run(XPOST_INPUT_STRING, prog);

I am puzzled by the interaction between xpost_create() and xpost_run().  Is it possible to create and use multiple xpost contexts at once?  If so, shouldn't xpost_create() return some kind of handle that would be passed as a parameter to xpost_run()?  Or, if not, then why should I need to call xpost_create() and xpost_destroy() at all?

I would expect the library to behave more like a printer, in that it would produce an image for every showpage command.  One way to make that work would be to register a callback, which would be called whenever showpage is encountered.  Perhaps it could pass some information about the bounding box as parameters to the callback, since it's unreasonable to have to guess or hard-code that information.

It's odd that the color model is called "bgr", but the pixel values are arranged in the opposite order (red, green, blue) in the output buffer.  I would also consider treating the buffer as an array of

typedef {
    int red;
    int green;
    int blue;
} struct pixel;

… instead of separate red, green, and blue integers.

Your example client doesn't seem to demonstrate any error-handling capability.  What happens, for example, if the PostScript interpreter has a stack underflow?


PDO multiple queries with 2 different tables I joined this 2 tables and dropped the user_id afterwards. I am defining the user_id elsewhere in my code based on my session/cookies and I do not want to return this value as a global. Is there a more compact or elegant way to write this:

public function test($user_id)
{
    $stmt = $this->conn->prepare("CREATE TEMPORARY TABLE `temp_tb`
                                  SELECT a.*, b.token
                                  FROM $this->tableName a
                                  LEFT JOIN `requests` b
                                  ON a.$this->user_id = b.uid
                                  WHERE $this->user_id=:user_id ");
    $stmt->execute(array(":user_id"=>$user_id));
    $stmt = $this->conn->prepare("ALTER TABLE `temp_tb` DROP $this->user_id ");
    $stmt->execute();
    $stmt = $this->conn->prepare("SELECT * FROM `temp_tb` ");
    $stmt->execute();
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

Thank you!

Well, I hardly understand the whole affair but from what I can get about it

$sql = "SELECT a.*, b.token FROM $this->tableName a
        LEFT JOIN `requests` b ON a.$this->user_id = b.uid
        WHERE $this->user_id=:user_id";
$this->conn->prepare($sql);
$stmt->execute(array(":user_id"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
unset($row[$this->user_id]);
return $row;


Calling individual classes for navigation items I have navigation items that are created dynamically with PHP. I wrote this because I need to add individual classes and fire them individually. My code works, but I want a way of refining it no matter how many items are added to the navigation via the backend. Is there a way of doing this so I don't have to add 20 .slideToggle lines of code?

//Adds a CSS Selector to items we need to target individually
jQuery('#sidr ul li').has('ul').each(function(i){
    jQuery(this).addClass('has-sub-'+(i+1));
});
jQuery('#sidr ul li ul').has('li').each(function(i){
    jQuery(this).addClass('sub-'+(i+1));
});

//Toggles a 'clicked' CSS Selector and reveals the Sub-Menus
jQuery('li.has-sub-1').click(function(){
    jQuery('#sidr ul li ul.sub-1').slideToggle(200);
});
jQuery('li.has-sub-2').click(function(){
    jQuery('#sidr ul li ul.sub-2').slideToggle(200);
});
jQuery('li.has-sub-3').click(function(){
    jQuery('#sidr ul li ul.sub-3').slideToggle(200);
});

jQuery('li.has-sub-1, li.has-sub-2, li.has-sub-3, li.has-sub-4, li.has-sub-5, li.has-sub-6').click(function(){
    jQuery(this).toggleClass('clicked');
});

I think that all you are looking for is:

//assumes sidr is top level container for menu
//you should consider adding a generic class to menu items when page is assembled
jQuery('#sidr > ul > li').click(function() {
     $this = jQuery(this);
     $this.find('ul').slideToggle(200);
});

If you cannot rely on a selector (like I used above) to find the elements that you are interested in, or if you cannot add classes to the elements when the page is assembled then you could add the class in code:

jQuery('#sidr ul li').has('ul').addClass('hasSubMenu');

Now you can use:

jQuery('.hasSubMenu').click(function() {
     $this = jQuery(this);
     $this.find('ul').slideToggle(200);
     $this.toggleClass('clicked');
});

This also saves re-evaluating the various selectors, which is much more efficient.


Python Inheritance and Class (Hackerank problem) I just deep dived to Python and I came with this Hackerrank problem:

Create two class, Person with firstName, lastName, idNumber as its attributes with method printPerson() simply print last name and first name and id, and the derived class Student.

The Student class has additional attributes, its score and an array with two value, and I need to calculate the average of all scores in this array. Then finally I will decide which letter I should assign to this average score and print it.

Sample Input:

Heraldo Memelli 8135627
2
100 80

Sample Output:

Name: Memelli, Heraldo
ID: 8135627
Grade: O

My code in Python 3:

class Person:
    def __init__(self, firstName, lastName, idNumber):
        self.firstName = firstName
        self.lastName = lastName
        self.idNumber = idNumber
    def printPerson(self):
        print("Name:", self.lastName + ",", self.firstName)
        print("ID:", self.idNumber)

def avg(a):
    return sum(a)/len(a)

def m(a):
    return [int(r) for r in list(a.values())[0].split('-')]

class Student(Person):
    def __init__(self, f, l, i, s):
        Person.__init__(self, f, l, i)
        self.s = s
    def calculate(self):
        avgScore = avg(self.s)
        scoreList = [
          {'O': '90-100'},
          {'E': '80-89'},
          {'A': '70-79'},
          {'P': '55-69'},
          {'D': '40-54'},
          {'T': '0-39'},
        ]
        scoreLetter = list([x for x in scoreList if m(x)[0] <= avgScore == avgScore <=m(x)[1]][0].keys())[0]
        return '{}'.format(scoreLetter)

line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print("Grade:", s.calculate())

It passes all test cases. Could you please help me to review it and give me some advice?

Read PEP8 the Python style guide

Functions and variables should be lower_snake_case
Naming

Single letter variable names are a bad habit. Code should be self explanatory and function names like m() don't tell what they are supposed to do
Instead of the printPerson() function, override the magic function __str__

Doing this you can do print(student) to print the class
You should make the avg function a part of the Student class
Your grade function can be simplified

 scoreList = [
   {'O': '90-100'},
   {'E': '80-89'},
   {'A': '70-79'},
   {'P': '55-69'},
   {'D': '40-54'},
   {'T': '0-39'},
]

When you swap the key and values around, and loop over them in order

self.score_dictionary = {
    90 : 'O',
    80 : 'E',
    70 : 'A',
    55 : 'P',
    40 : 'D',
    0  : 'T'
}

It becomes clear that if the average is higher than the value that should be the grade to give, else go to the next value

This will happen automatically with Python3.7+, or else you can make use of an OrderedDict

from collections import OrderedDict
self.score_dictionary = OrderedDict([
    (90, 'O'),
    (80, 'E'),
    (70, 'A'),
    (55, 'P'),
    (40, 'D'),
    (0, 'T')
])

Thnx @Graipher, for correcting my mistake regarding the OrderedDict

Another way (which might be clearer) is to loop over the dictionary keys in sorted order
You can unpack multiple arguments in one go

line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]

Could be

f, l, i = input().split()

It is Python idion to use _ for variables you don't use

Code

class Person:
    def __init__(self, first_name, last_name, id):
        self.first_name = first_name
        self.last_name = last_name
        self.id = id

    def __str__(self):
        return f"Name: {self.last_name}, {self.first_name}\nID: {self.id}"

class Student(Person):
    def __init__(self,  first_name, last_name, id, scores):
        super().__init__(first_name, last_name, id)
        self.scores = scores
        self.avg = sum(self.scores) / len(scores)
        self.score_dictionary = {
            90 : 'O',
            80 : 'E',
            70 : 'A',
            55 : 'P',
            40 : 'D',
            0  : 'T'
        }

    def grade(self):
        for score in sorted(self.score_dictionary.keys(), reverse=True):
            if self.avg >= score:
                return self.score_dictionary[score]

if __name__ == '__main__':
    f, l, i = input().split()
    _ = input()
    scores = list(map(int, input().split()))
    student = Student(f, l, i, scores)
    print(student)
    print(f"Grade: {student.grade()}")


Keyboard handler for moving in four directions I'm having trouble deciding if I should leave the default: break; in the switch statement or not. It does kinda show intent, i.e. that most keys are not handled, but it's also effectively useless code. I feel like it's clear enough anyway, but maybe being explicit is better?

function handleKeyDownEvent(event) {
    switch (event.keyCode) {
        case 87: // w
            player.dy = -50
            break
        case 65: // a
            player.dx = -50
            break
        case 83: // s
            player.dy = 50
            break
        case 68: // d
            player.dx = 50
            break
        default:
            break
    }
}

Maps seem to be the preferred way of doing this, instead of a switch statement. How does the movement map work with the corresponding handleKeyUpEvent which works the same way, except that it zeroes the dx or dy values?

Should I keep the default: break; or not?

Your code is rather short, but can still be greatly improved.

  Should I keep the default: break; or not?

Do not keep it. Since you aren't doing anything for the default case, there is no point in having it. You can remove that entire thing.

Map

In order to improve the readability of your code (and overall efficiency), I recommend creating a map that maps the key code values to the changes needed to be made to dx and dy. Here is what I mean:

var keyToChangeMap = {
    87: [0, -50], // [change in x, change in y]
    65: [-50, 0]
    ...
};

Now, you have an \$O(1)\$ method for finding out how to change the dx and dy values. This is also flexible: you can easily change the values that x and y change by, and you can easily add more keys to listen to.

Then, in your function, simply use the key code to get a value from the map:

function handleKeyDownEvent(event) {
    var keyCode = event.keyCode;
    if(keyToChangeMap.hasOwnProperty(keyCode)) {
        var change = keyToChangeMap[keyCode];
        player.dx += change[0];
        player.dy += change[1];
    }
}

Magic numbers

You have some magic numbers in your code. It's pretty difficult to understand these numbers, so you should create constants to represent these values.

For example,

var W_KEY = 87;
var A_KEY = 65;

You don't even have to be that specific. You can do something like this:

var UP_KEY = 87;
var LEFT_KEY = 65;

which is even more readable.


Class Module to wrap up classic ADO call to SQL-server I do a lot of copying excel vba code related to classic ADO from workbook to workbook, so I've decided to add the code to a Class Module in a single utility workbook and then in all other books just reference the utility book and use instances of the ADO wrapper class.

The class module is called clDataAccess

I would like to know any obvious flaws in the coding:

Option Explicit

'::::::::::::::::::::
'::
'::  Class Variable Declarations
'::
'::::::::::::::::::::

Private mcnConnectString As String
Private mcnConnect As ADODB.Connection

'::::::::::::::::::::
'::
'::  on initialization open an ADO connection through to the server
'::
'::::::::::::::::::::
Private Sub Class_Initialize()

    mcnConnectString = _
        "PROVIDER=SQLOLEDB.1;" & _
        "P******D=*********;" & _
        "PERSIST SE**RITY INFO=****;" & _
        "USER ID=**********;" & _
        "INITIAL CATALOG=*******;" & _
        "DATA SOURCE=*****;" & _
        "USE PROCEDURE FOR PREPARE=*;" & _
        "AUTO TRANSLATE=****;" & _
        "CONNECT TIMEOUT=*;" & _
        "COMMAND TIMEMOUT=*" & _
        "PACKET SIZE=****;" & _
        "TAG WITH COLUMN COLLATION WHEN POSSIBLE=****"

    Call ensureClosedConn(mcnConnectString)

End Sub

'::::::::::::::::::::
'::
'::  connection string property
'::  user could need to change the connection
'::
'::::::::::::::::::::
Property Let connectionString(ByVal stConn As String)
    mcnConnectString = connectionString
End Property

':::::::::::::::::
'::
':: This procedure attempts to create a connection to
':: the database using the specified connection string.
'::
'::::::::::::::::::::
Private Function ensureClosedConn(ByVal sConnection As String) As Boolean

On Error GoTo ErrorHandler

    If (mcnConnect Is Nothing) Then
        Set mcnConnect = New ADODB.Connection
        With mcnConnect
            .connectionString = sConnection
            .CommandTimeout = 0
            .Open
            .Close
        End With
    Else
        If (mcnConnect.State And 1) = 1 Then mcnConnect.Close
    End If

Exit Function
ErrorHandler:
    Err.Raise 99999, , "Error occured inside routine ensureClosedConn of clDataAccess"
End Function

':::::::::::::::::
'::
':: Client may wish to receive the recordset
'::
'::::::::::::::::::::
Public Function cGetRecordset(ByVal sqlString As String) As ADODB.Recordset

    Call ensureClosed_PubConn
    mcnConnect.Open
    Set fRecordset = New ADODB.Recordset

    With fRecordset
        .Open _
            Source:=sqlString, _
            ActiveConnection:=mcnConnect, _
            CursorType:=adOpenForwardOnly, _
            LockType:=adLockReadOnly, _
            Options:=adCmdText
    End With

    Set cGetRecordset = fRecordset
End Function

':::::::::::::::::
'::
':: This procedure attempts to move some data
'::
'::::::::::::::::::::
Public Sub updateWorkSheet( _
    ByVal sqlString As String, _
    ByRef rngDest As Excel.Range _
    )

On Error GoTo ErrorHandler

    Call ensureClosed_PubConn
    mcnConnect.Open
    Dim r As ADODB.Recordset
    Set r = New ADODB.Recordset

    With r
        ':: Extract and copy the required records.
        .Open _
            Source:=sqlString, _
            ActiveConnection:=mcnConnect, _
            CursorType:=adOpenForwardOnly, _
            LockType:=adLockReadOnly, _
            Options:=adCmdText
        rngDest.CopyFromRecordset r
        .Close
    End With

    ':: drop the recordset and its connection
    If Not (r Is Nothing) Then
        If (r.State And 1) = 1 Then r.Close
        Set r.ActiveConnection = Nothing
        Set r = Nothing
    End If

ErrorHandler:
    Err.Raise 99999, , "Error occured inside routine updateWorkSheet of clDataAccess"
End Sub    'updateWorkSheet

Suggestions:

Don't assume the cursor type of the recordset, the user might want a different type.
Consider making a ConnectionString class that lets the user use properties to get and let the individual parameters, but allows assigning or returning a complete string
Don't force the connection to close, as the user might intend to make subsequent calls.


Eliminating nested each I have an unusual data structure that I need to search - the structure is the result of parsing a JSON file returned from an HTTP request.

The top-level object is an Array, but from top to bottom I have Array->Hash->Array->Hash.

I'm writing code to check the value of a given key in the innermost hash, across the entire data structure.

As it stands, my code is like this:

json = JSON.parse(File.read(file))
json.each do |hash1|
  hash1.keys.each do |key|
    hash1[key].each do |inner_hash|
      # search in the inner hash
    end
  end
end

I know this is ugly. I know there are better ways to iterate over collections and to combine selections together. I'm just not sure what I should do in this instance given the repeated sliding from array to hash.

What I'm Searching

In the above code, I have the search snipped out. My goal with this iteration structure is to skim through entries (the hashes at the entry_id level) for various conditions and either immediately act on or return the Hash object when the conditions are met. For example, if the condition is that field1 contains something, I might want to return

[
  {
    "entry_id": 544,
    "field1": "something",
    "field2": "something else",
    "field3": 456
  },
  {
    "entry_id": 546,
    "field1": "something!",
    "field2": "something else!",
    "field3": 012
  }
]

Example of Data Structure

[
{
  "12345": [
    {
      "entry_id": 543,
      "field1": "value",
      "field2": "other value",
      "field3": 123
    },
    {
      "entry_id": 544,
      "field1": "something",
      "field2": "something else",
      "field3": 456
    }
  ],
  "23456": [
    {
      "entry_id": 545,
      "field1": "new value",
      "field2": "other new value",
      "field3": 789
    },
    {
      "entry_id": 546,
      "field1": "something!",
      "field2": "something else!",
      "field3": 012
    }
  ]
}
]

You can iterate over the hashes/arrays using a custom enumerator (modified from a StackOverflow answer here):

def dfs(obj, &blk)
  return enum_for(:dfs, obj) unless blk
  yield obj if obj.is_a? Hash
  if obj.is_a?(Hash) || obj.is_a?(Array)
    obj.each do |*a|
      dfs(a.last, &blk)
    end
  end
end

You can then use this enumerator builder method in any number of other helper methods for whatever you need. For example, to perform your example search, you could define:

def find_node_with_value(obj, key, value)
  dfs(obj).select do |node|
    node[key].respond_to?(:include?) && node[key].include?(value)
  end
end

And then use it like:

find_node_with_value(json_data, "field1", "something")
# [{"entry_id"=>544, "field1"=>"something" ...}, {"entry_id"=>546, "field1"=>"something!" ...}]


How to efficiently find if numbers in a given range contains either 1 or 3, but not both? I am having a trouble speeding up my implementation. The question is, given a range of numbers from long a to long b, find how many lucky numbers are between a and b inclusive. A number is a lucky number if it contains either 1 or 3. If it contains both 1 and 3, it is not a lucky number.

Currently, I am iterating over from a to b, inclusive, using for loop, and have a while loop in each iteration where a while loop continues until current number is > 0. In the while loop, I use modulo 10 to get the last digit, check if it's 1 or 3, then set the current number to the number/10.

Is there a way to make this more efficient for range from 10000000000 to 20000000000? With my implementation, it takes around 160 seconds.

Here is my code:

public class Main {

    public static void main(String[] args) {

        long start = 10000000000L;
        long end = 20000000000L;

        int total = 0;

        double startTime = System.nanoTime();

        for (long i = start;i <= end; i++) {
            int numOf1 = 0;
            int numOf3 = 0;
            long number = i;
            while (number > 0) {
                long lastDigit = number % 10;
                if (lastDigit == 1) {
                    numOf1++;
                } else if (lastDigit == 3) {
                    numOf3++;
                }

                if (numOf1 > 0 && numOf3 > 0) {
                    break;
                }
                number /= 10;
            }

            if (numOf1 > 0 || numOf3 > 0) {
                total++;
            }
        }

        System.out.println(total);
        double endTime = System.nanoTime();

        System.out.println((endTime - startTime) / 1000000000);

    }

}

A Bug

if (numOf1 > 0 || numOf3 > 0) {
    total++;
}

That overcounts. The definition of "lucky number" included "if it contains both 1 and 3, it is not a lucky number", but numbers that contain both a 1 and a 3 are counted. The break in the while-loop exits that loop when that condition is detected, but then the code above still runs. You could use:

if ((numOf1 > 0) != (numOf3 > 0)) {
    total++;
}

The != between two booleans is a slightly tricky way to say "one of them but not both". Of course that can be written out more explicitly.

An other bug

int total = 0;

Do you know how big the result is? By my count it's just over 3.48 billion. That's a problem, int only goes just over 2.14 billion. The count doesn't go over 4.29 billion, so you could still use int, and then interpret it as an unsigned integer later (eg printing total & 0xFFFFFFFFL). But that's strange, a bit advanced, not for beginners. Using long total = 0; is a simpler and more sensible solution.

  Is there a way to make this more efficient for range from 10000000000 to 20000000000?

There are some specific properties of that range that you could use.

First, let's ignore 20000000000 itself, it contains neither a 1 nor a 3.

Then, every number in the range for sure has at least one 1 in it, so you don't need to test it, this is something you already know. That would let you simplify the test to "check if there is any 3 in the number".

Counting without brute force

Forgetting the leading 1, the numbers in our range have 10 "variable" digits.
How many 10-digit strings of digits 0..9 don't have a 3 in them? Every place has 9 possible digits left instead of 10, so rather than pow(10, 10) it will be pow(9, 10).

pow(9, 10) is something that you can calculate easily, even with just Math.pow(9, 10). It's normally not really proper to use doubles for integer calculations, but this one works.

  With my implementation, it takes around 160 seconds.

Does it actually? That's an order of magnitude faster than it runs on my PC.


Simple script to find the largest number palindrome I have made a simple C# script that will find the largest palindrome made by the product of two numbers. These numbers will be between a minimum and maximum value, inputted by int.Parse(Console.ReadLine()). Is there a way to make this better?

It is brute force, however I tried to make it use fewer numbers if one combination gives a smaller palindrome. The numbers are generated in a for loop.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace ProjectEuler
{
    class Solution
    {
        static void Main( /*I am not sure what the point is for String args. If anybody can explain?*/ )
        {
            Console.Clear();
            Console.WriteLine("What would the maiximum value be for these numbers?");
            int max = int.Parse(Console.ReadLine());

            Console.WriteLine("\nWhat would the minimum value be for these numbers?");
            int min = int.Parse(Console.ReadLine());

            int largestNumb1 = 0;
            int largestNumb2 = 0;
            int generatedPalindrome = 0;

            for (int number1 = max; number1 >= min; number1--)
            {
                for (int number2 = max; number2 >= min; number2--)
                {
                    string generatedNumber = (number1 * number2).ToString();
                    if (IsPalindrome(generatedNumber))
                    {
                        if (int.Parse(generatedNumber) > generatedPalindrome)
                        {
                            generatedPalindrome = number1 * number2;
                            largestNumb1 = number1;
                            largestNumb2 = number2;
                            //This is mainly done to increase 'subtle' performance, by skipping numbers
                            //that will never give a larger number than the previous palindrome
                            number1--;
                            number2 = max;
                        }
                        else if (int.Parse(generatedNumber) < generatedPalindrome)
                        {
                            //This is mainly done to increase 'subtle' performance, by skipping numbers
                            //that will never give a larger number than the previous palindrome
                            number1--;
                            number2 = max;
                        }
                    }
                }
            }
            PrintAnswer(generatedPalindrome, largestNumb1, largestNumb2);
        }

        static bool IsPalindrome(string generatedNumber)
        {
            char[] answerChar = generatedNumber.ToCharArray();
            Array.Reverse(answerChar);
            string reversedString = new string(answerChar);

            if (generatedNumber == reversedString)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        static void PrintAnswer(int generatedPalindrome, int largestNumb1, int largestNumb2)
        {
            Console.Clear();
            if (generatedPalindrome != 0)
            {
                Console.WriteLine("Largest possible palindrome given limit: {0}\nNumbers used: {1} & {2}", generatedPalindrome, largestNumb1, largestNumb2);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Sorry, but no valid palindrome was generated given your values.\nWould you like to try again? (y)");
                if (Console.ReadLine() == "y")
                {
                    Main();
                }
                else
                {
                    return;
                }
            }
        }
    }
}

For getting integers (or any other data that needs to be validated) from the user, sometimes it's best to create a separate function that you can call. For example:

static int GetIntFromUser(string prompt)
{
    int input;

    while (true)
    {
        if (prompt != null) Console.Write(prompt);
        if (int.TryParse(Console.ReadLine(), out input)) break;
        Console.WriteLine("Sorry, {0} is not a valid integer. Please try again.", input);
    }

    return input;
}

Then you can use it like:

int max = GetIntFromUser("Enter the maximum value for these numbers: ");
int min = GetIntFromUser("Enter the minimum value for these numbers: ");


Color fading function I found this old color fading function in my snippets folder and would like to implement it to one of my projects. It can be used to fade one color to another. It's a very long one-liner:

D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor)
{
    return (factor<0.0f)?from:((factor>1.0f)?to:(((((from>>24)>(to>>24))?((from>>24)-
    (D3DCOLOR)(factor*(float)((from>>24)-(to>>24)))):((from>>24)+(D3DCOLOR)(factor*(float)
    ((to>>24)-(from>>24)))))<<24)|(((((from<<8)>>24)>((to<<8)>>24))?(((from<<8)>>24)-
    (D3DCOLOR)(factor*(float)(((from<<8)>>24)-((to<<8)>>24)))):(((from<<8)>>24)+(D3DCOLOR)
    (factor*(float)(((to<<8)>>24)-((from<<8)>>24)))))<<16)|(((((from<<16)>>24)>
    ((to<<16)>>24))?(((from<<16)>>24)-(D3DCOLOR)(factor*(float)(((from<<16)>>24)-
    ((to<<16)>>24)))):(((from<<16)>>24)+(D3DCOLOR)(factor*(float)(((to<<16)>>24)-
    ((from<<16)>>24)))))<<8)|(((((from<<24)>>24)>((to<<24)>>24))?(((from<<24)>>24)-(D3DCOLOR)
    (factor*(float)(((from<<24)>>24)-((to<<24)>>24)))):(((from<<24)>>24)+(D3DCOLOR)(factor*
    (float)(((to<<24)>>24)-((from<<24)>>24))))))));

}

D3DCOLOR is just a DWORD (unsigned long). A color can for example be 0xAARRGGBB (A-alpha, R-red, G-green, B-blue), but works with other compositions aswell.

Obviously it's a total mess.

I actually don't know how it works and don't remember where I have it from, so I would ask for a review to improve the code and make it readable and understandable.

This is the reason why some people want ternary operators removed from the language. It's not quite the worst abuse I've seen, but it's pretty close. This took quite a while to disentangle. I'm going to go through it in steps:

First step: make it slightly more readable. Break up everything:

return (factor<0.0f)
?
from
:
((factor>1.0f)
?
to
:
(((((from >> 24) > (to >> 24))
?
((from>>24)-(D3DCOLOR)(factor*(float)((from>>24)-(to>>24))))
:
((from>>24)+(D3DCOLOR)(factor*(float)((to>>24)-(from>>24)))))<<24)
|
(((((from<<8)>>24)>((to<<8)>>24))
?
(((from<<8)>>24)-(D3DCOLOR)(factor*(float)(((from<<8)>>24)-((to<<8)>>24))))
:
(((from<<8)>>24)+(D3DCOLOR)(factor*(float)(((to<<8)>>24)-((from<<8)>>24)))))<<16)
|
(((((from<<16)>>24)>((to<<16)>>24))
?
(((from<<16)>>24)-(D3DCOLOR)(factor*(float)(((from<<16)>>24)-((to<<16)>>24))))
:
(((from<<16)>>24)+(D3DCOLOR)(factor*(float)(((to<<16)>>24)-((from<<16)>>24)))))<<8)
|
(((((from<<24)>>24)>((to<<24)>>24))
?
(((from<<24)>>24)-(D3DCOLOR)(factor*(float)(((from<<24)>>24)-((to<<24)>>24))))
:
(((from<<24)>>24)+(D3DCOLOR)(factor*(float)(((to<<24)>>24)-((from<<24)>>24))))))));

Not a hell of a lot of improvement, but we can at least start to see some of the shifting operations here and (sort) of what they're being applied to.

Second step: make some utility functions -

typedef unsigned long D3DCOLOR;

D3DCOLOR Alpha(D3DCOLOR color)
{
    return (color >> 24);
}

D3DCOLOR Red(D3DCOLOR color)
{
    return (color << 8) >> 24;
}

D3DCOLOR Green(D3DCOLOR color)
{
    return (color << 16) >> 24;
};

D3DCOLOR Blue(D3DCOLOR color)
{
    return (color << 24) >> 24;
}

Effectively, what's being done here is masking out each part (A, R, G, B) one at a time. I'm assuming it's in this format: it doesn't really matter if it isn't, because it's doing the same thing to each byte in the long. The only thing that will change is the order, but we'll stick with these function names for now. Let's add this into the mix:

return (factor<0.0f)
?
from
:
((factor>1.0f)
?
to
:
(Alpha(from) > Alpha(to))
?
(Alpha(from) - (D3DCOLOR)(factor * (float)(Alpha(from) - Alpha(to)))
:
((Alpha(from) + (D3DCOLOR)(factor * (float)((Alpha(to)- Alpha(from))))))) << 24
|
(Red(from) > Red(to))
?
((Red(from) - (D3DCOLOR)(factor * (float)(Red(from) - Red(to))))
:
(Red(from) + (D3DCOLOR)(factor * (float)((Red(to) - Red(from)))))) << 16
|
(Green(from) > Green(to))
?
((Green(from) - (D3DCOLOR)(factor*(float)(Green(from) - Green(to)))
:
(Green(from) + (D3DCOLOR)(factor * (float)((Green(to) - Green(from)))))) << 8
|
(Blue(from) > Blue(to))
?
((Blue(from) - (D3DCOLOR)(factor * (float)(Blue(from) - Blue(to)))
:
(Blue(from) + (D3DCOLOR)(factor * (float)((Blue(to) - (Blue(from)))))) >> 24;

Ok, getting there. It's almost readable now. Note the parens here are something of a pain, and we must be careful to get them correct.

We can now do the (laborious) task of replacing ternary operators with if/else:

D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor)
{
    D3DCOLOR col = 0;

    if (factor < 0.0f) {
        col = from;
    }
    else if (factor > 1.0f) {
        col = to;
    }
    else {
        if(Alpha(from) > Alpha(to)) {
            col = (Alpha(from) - (D3DCOLOR)(factor * (float)((Alpha(from) - Alpha(to))))) << 24;
        }
        else {
            col = (Alpha(from) + (D3DCOLOR)(factor * (float)((Alpha(to)- Alpha(from))))) << 24;
        }

        if(Red(from) > Red(to)) {
            col |= (Red(from) - (D3DCOLOR)(factor * (float)((Red(from) - Red(to))))) << 16;
        }
        else {
            col |= (Red(from) + (D3DCOLOR)(factor * (float)((Red(to) - Red(from))))) << 16;
        }

        if(Green(from) > Green(to)) {
            col |= (Green(from) - (D3DCOLOR)(factor * (float)((Green(from) - Green(to))))) << 8;
        }
        else {
            col |= (Green(from) + (D3DCOLOR)(factor * (float)((Green(to) - Green(from))))) << 8;
        }

        if(Blue(from) > Blue(to)) {
            col |= (Blue(from) - (D3DCOLOR)(factor * (float)((Blue(from) - Blue(to)))));
        }
        else {
            col |= (Blue(from) + (D3DCOLOR)(factor * (float)((Blue(to) - (Blue(from))))));
        }
    }

    return col;
}

Ok, so now it's readable. This can likely be simplified further - there's quite a bit of duplication here. All that really changes are some shift values. Hopefully this is enough that you can do that simplification yourself, however.


Regular Expression replace specific characters Does anyone know of a better / cleaner way to write the following:

GetSafeTagName(txtUserInput.text);

public static string GetSafeTagName(string tag)
{
    tag = tag.ToUpper()
    .Replace("'","`")
    .Replace('"','`')
    .Replace("&", "and")
    .Replace(",",":")
    .Replace(@"\","/"); //Do not allow escaped characters from user
    tag = Regex.Replace(tag, @"\s+", " "); //multiple spaces with single spaces
    return tag;
}

Thanks!

You could use a regular expression and Dictionary<string, string> to do the search replace:

// This regex matches either one of the special characters, or a sequence of
// more than one whitespace characters.
Regex regex = new Regex("['\"&,\\\\]|\\s{2,}");

var map = new Dictionary<string, string> {
    { "'", "`"},
    { "\"", "`"},
    { "&", "and" },
    { ",", ":" },
    { "\\", "/" }
};

// If the length of the match is greater that 1, then it's a sequence
// of spaces, and we can replace it by a single space. Otherwise, we
// use the dictionary to map the character.
string output = regex.Replace(input.ToUpper(),
    m => m.Value.Length > 1 ? " " : map[m.Value]);


Managing many exceptions in Erlang cowboy without deeply nested trees In my cowboy (Erlang) application, I have a handler called projects_from_json. This takes a JSON POST request as input and should create a database entry from this. Then, it should respond with a success message or the correct error message to the user.

I started with two exceptions that could occur (simplified):

projects_from_json(Req=#{method := <<"POST">>}, State) ->
    {ok, ReqBody, Req2} = cowboy_req:read_body(Req),
    try
        Name = parse_json(ReqBody),
        % Continuation of happy path
        db:create_project(Name)
    catch
        error:{badkey, Key} ->
            % return error message about invalid JSON
            % [<<"Key \"">>, Key, <<"\" does not exist in passed data">>]
        throw:duplicate ->
            % return error message about duplicate name
            % [<<"A project with name \"">>, Name, <<"\" already exists">>]
    end

Already in this case, this did not work, because Name is not safe in the second catch clause (since it comes from the try clause and could potentially be unset). I also could not move the call of db:create_project(Name) outside of the try, because then again Name would not be safe to be used.

Since there were some more exceptions and errors to be handled, I ended up with a very deeply nested situation (follows below).

My first idea would be to move stuff into own functions, but most of the code is error handling and as far as I know I can only handle the error by returning a tuple from the projects_from_json handler.

So here follows my nested mess. In total, I currently want to handle three error situations:

InvalidValue: The project name sent by the user contains invalid characters
DuplicateValue:  A project with the same name already exists
MissingKey: User did not supply all required keys

Code:

projects_from_json(Req=#{method := <<"POST">>}, State) ->
    {ok, ReqBody, Req2} = cowboy_req:read_body(Req),
    try
        Name = project_name(ReqBody),

        case validate_project_name(Name) of
            invalid ->
                molehill_respond:respond_error(<<"InvalidValue">>,
                    <<"The project name can only consist of ASCII characters and numbers, and dash in the middle of the word.">>,
                    400, Req2, State);
            ok ->
                {ok, Conn} = moledb:connect_from_config(),

                try
                    moledb:create_project(Conn, Name),
                    Data = prepare_project_json(Name),
                    molehill_respond:respond_status(Data, 201, Req2, State)
                catch
                    throw:duplicate_element ->
                        molehill_respond:respond_error(<<"DuplicateValue">>,
                            erlang:iolist_to_binary(
                                [<<"A project with name \"">>, Name, <<"\" already exists">>]),
                            409, Req2, State)
                end
        end
    catch
        error:{badkey, Key} ->
            molehill_respond:respond_error(
                <<"MissingKey">>,
                erlang:iolist_to_binary(
                    [<<"Key \"">>, Key, <<"\" does not exist in passed data">>]),
                400, Req2, State)
    end.

Is it possible to restructure this to a clean form where all possible errors are on a similar indentation level at the end of the function?

molehill_respond is a helper module I wrote to simplify the creation of my JSON return messages, moledb is a helper module that executes all the SQL queries.

My first attempt (without changing any of your functions nor the semantics of your handler) would be:

projects_from_json(Req=#{method := <<"POST">>}, State) ->
    try
        {ok, ReqBody, Req2} = cowboy_req:read_body(Req),
        Name = get_project_name(ReqBody),
        {ok, Conn} = moledb:connect_from_config(),
        Data = get_project_json(Conn, Name),
        molehill_respond:respond_status(Data, 201, Req2, State)
    catch
        error:{badkey, Key} ->
            molehill_respond:respond_error(
                <<"MissingKey">>,
                erlang:iolist_to_binary(
                    [<<"Key \"">>, Key, <<"\" does not exist in passed data">>]),
                400, Req2, State);
        error:{error, Label, Message, Status} ->
            molehill_respond:respond_error(Label, Message, Status, Req2, State)
    end.

get_project_name(ReqBody) ->
    Name = project_name(ReqBody),
    case validate_project_name(Name) of
        invalid ->
            erlang:error({
                error,
                <<"InvalidValue">>,
                <<"The project name can only consist of ASCII characters and numbers, "
                    "and dash in the middle of the word.">>,
                400
            });
        ok ->
            Name
    end.

get_project_json(Conn, Name) ->
    try
        moledb:create_project(Conn, Name),
        prepare_project_json(Name)
    catch
        error:duplicate_element ->
            erlang:error({
                error,
                <<"DuplicateValue">>,
                erlang:iolist_to_binary(
                    [<<"A project with name \"">>, Name, <<"\" already exists">>]),
                409
            })
    end.

I basically moved pieces of your code from projects_to_json/2 into its own functions so you can keep your main one tidier.

But you might have noticed that my new functions still have a lot of code for encapsulating the errors. If you can get validate_project_name/1 and prepare_project_json/1 to raise the errors in the proper format themselves instead of returning invalid | ok, this gets reduced to…

projects_from_json(Req=#{method := <<"POST">>}, State) ->
    try
        {ok, ReqBody, Req2} = cowboy_req:read_body(Req),
        Name = project_name(ReqBody),
        validate_project_name(Name),
        {ok, Conn} = moledb:connect_from_config(),
        moledb:create_project(Conn, Name),
        Data = prepare_project_json(Name)
        molehill_respond:respond_status(Data, 201, Req2, State)
    catch
        error:{badkey, Key} ->
            molehill_respond:respond_error(
                <<"MissingKey">>,
                erlang:iolist_to_binary(
                    [<<"Key \"">>, Key, <<"\" does not exist in passed data">>]),
                400, Req2, State);
        error:{error, Label, Message, Status} ->
            molehill_respond:respond_error(Label, Message, Status, Req2, State)
    end.

%% @doc this function may raise an error like {error, binary(), binary(), 400..499}
validate_project_name(Name) ->
    …

%% @doc this function may raise an error like {error, binary(), binary(), 400..499}
prepare_project_json(Name) ->
    …

Basically, the idea is to include as much information as you need on the error itself, so… instead of failing with duplicate_element, you fail with {error, …, …} so that the outer loop can catch that. If you can’t decide on how your functions will fail, just wrap them up in other functions that will translate the errors/results into the expected form.


Nested Loop For Cell Compare I'm trying to loop through two separate sheets going row by row starting at row 2 comparing multiple columns (Product Number, Date, Quantity) in Excel using VBA.

My nested loops are taking way too long. Is there another way to loop through, while cutting down on time, but being able to compare multiple columns at the same time?

For i = 2 To lastRow22
    If ws2.Cells(i, 80) = 1 Or ws2.Cells(i, 80) = 2 Then
            x = ws2.Cells(i, 79)
        ElseIf ws2.Cells(i, 80) = 0 Then
            x = ws2.Cells(i, 1)
        End If
    x2 = Trim(ws2.Cells(i, 81))
    xDate = Trim(ws2.Cells(i, 19))
    xQD = Trim(ws2.Cells(i, 20))
    For j = 2 To lastRow33
        y = Trim(ws3.Cells(j, 28))
        y2 = Trim(ws3.Cells(j, 10))
        yDate = Trim(ws3.Cells(j, 13))
        yQD = Trim(ws3.Cells(j, 17))
        If x = y And xDate = yDate And xQD = yQD And ws2.Cells(i, 82) = 0 And ws3.Cells(j, 27) = 0 Then
            ws3.Cells(j, 1).Interior.Color = vbGreen
            ws2.Cells(i, 1).Interior.Color = vbGreen
            ws2.Cells(i, 82) = 1
            ws3.Cells(j, 27) = 1
        ElseIf x2 = y2 And xDate = yDate And xQD = yQD And ws2.Cells(i, 82) = 0 And ws3.Cells(j, 27) = 0 Then
            ws3.Cells(j, 1).Interior.Color = vbGreen
            ws2.Cells(i, 1).Interior.Color = vbGreen
            ws2.Cells(i, 82) = 1
            ws3.Cells(j, 27) = 1
        End If
    Next j
Next i

1. Too Many Spreadsheet Reads and Writes

Would you be comfortable turning ws2.Range(ws2.Cells(2,1),ws2.Cells(lastRow22,80)) into an array? You can do that like this:

Dim arrEntireWs2() as Variant
With ws2
    arrEntireWs2 = .Range(.Cells(2,1),.Cells(lastRow22,80)).Value
End With

By cutting out all of those spreadsheet reads and writes, you'll be able to make all your checks and value changes much less expensively. Loop through the array like this (assuming from your code you want to loop through rows):

Dim lngArrEntireWs2Index as Long
For lngArrEntireWs2Index = LBound(arrEntireWs2,1) to Ubound(arrEntireWs2,1)
    <stuff you want to do here>
Next lngArrEntireWs2Index

And write it all to the spreadsheet one time like this:

With ws2
    .Cells(2,1).Resize(Ubound(arrEntireWs2,1), Ubound(arrEntireWs2,2)).Value = arrEntireWs2
End With

Using arrays will save you the most time, but one other habit I have is to do this:

2. VBA doesn't support short-circuit evaluation, so add it manually

Others will have different preferences since doing this makes your code uglier and thus less maintainable, but at the moment I currently prefer to implement manual short-circuit evaluation by breaking multiple-condition If And lines into several pieces. Thus:

If x = y And xDate = yDate And xQD = yQD And ws2.Cells(i, 82) = 0 And ws3.Cells(j, 27) = 0 Then

becomes:

If x = y Then
    If xDate = yDate Then
        If xQD = yQD Then
            If ws2.Cells(i, 82) = 0 Then
                If ws3.Cells(j, 27) = 0 Then
                    <do stuff>
                End If
            End If
        End If
    End If
End If

There's could be a more sensible way to deal with your logic that doesn't involve Arrow Code, but without more of your code available, it's hard for me to help further.


Winning Loop Connect 4 I am writing a fully functional single player Connect 4 game. I am working on the second player and the while loop that tells the player who won.

GUI

package lab7;

import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GUIClass implements Runnable {

    @Override
    public void run() {

        JFrame f = new JFrame("CSE 115 Connect 4");
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridLayout myGrid = new GridLayout(7, 6);
        JPanel panel;
        panel = new JPanel();
        panel.setLayout(myGrid);
        f.setLayout(myGrid);

        f.pack();

        ArrayList<JButton> col_button = new ArrayList<JButton>();
        for (Integer i = 1; i <= 7; i++)
        {
            JButton b = new JButton("Col " + i.toString());
            col_button.add(b);
            f.add(b);
        }

        ArrayList<ArrayList<JLabel>> col_list = new ArrayList<ArrayList<JLabel>>();
        for (int i = 0; i < 7; i++)
        {
            col_list.add(new ArrayList<JLabel>());
        }

        for (int i = 0; i < 42; i++)
        {

            JLabel label = new JLabel(new ImageIcon("images/blank.png"));
            //System.out.println(label.getIcon().toString())
            col_list.get(i % 7).add(label);
            f.add(label);
        }
        GameClass gc = new GameClass(col_list);

        for (int i = 0; i < 7; i++)
        {
            col_button.get(i).addActionListener(new ColButton(col_list.get(i)));
        }

        f.pack();

    }

    ImageIcon whiteCircle = new ImageIcon("blank.png");
}

that contains all of the graphical interface behind my code, as you might have guessed I used Java and Eclipse.

This is my game class where my second player is going to be, and I also assume my winning loop will be here.

import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JLabel;

public class GameClass{

    public GameClass(ArrayList<ArrayList<JLabel>> col_list)
    {

    }
}

finally this is my column class which contains the 1st player and all the buttons.

package lab7;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class ColButton implements ActionListener {

    private ArrayList<JLabel> _column;
    private GameClass _game;

    public ColButton(ArrayList<JLabel> c)
    {
        _column = c;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        for (int i = _column.size() - 1; i >= 0; i--)
        {
            JLabel l = _column.get(i);
            if(l.getIcon().toString().equals("images/blank.png"))
            {
                l.setIcon(new ImageIcon("images/red.png"));
                break;
            }
        }
    }

}

What do you think?  Any suggestions on how to get get going for the second part? I am working on the 2nd player but I have run into some setbacks.

Typically, a Swing application would be written using a Model-View-Controller pattern to split the responsibilities:

The Model would be a data structure to represent the game state.  It could, for example, consist of an ConnectFourBoard class that holds a two-dimensional array of chips in the board.
The View would be the Swing UI code
The Controller acts as the glue between the Model and View.  It handles actions triggered by the View, and notifies the View when the Model has changed.

Here, I see View and Controller code, commingled.  However, I don't see any Model code.  In fact, in ColButton.actionPerformed(), it appears that the lack of a Model is causing you some difficulty: you're resorting to determining the model state by parsing the icon name out of the view.

Without a Model, you are no doubt going to have a difficult time examining the model state to determine the winner.


Check if a file exists in a directory or parent I want to check if a file exists in a given directory or in the parent one, so I wrote this code:

if (File.Exists(fileName) ||
    File.Exists(Directory.GetParent(Path.GetDirectoryName(fileName)).FullName +
        Path.DirectorySeperatorChar +
        Path.GetFileName(fileName)))

However, this seems quite odd to me and I wonder if there is a smarter approach to making this check. I'm not necessarily looking for a shorter approach, but a more understandable one.

It's safer to use the Path.Combine method for joining the directory name and file name:

var fileName = @"c:\temp\foo.txt";

var fileExists =
    File.Exists(fileName) ||
    File.Exists(
        Path.Combine(
            Directory.GetParent(Path.GetDirectoryName(fileName)).FullName,
            Path.GetFileName(fileName)
        )
    );

What else you could to is to take it out of the if and use a helper variable and add some identation.

Another approach could be to encapsulate the search paths and the file exists check:

static IEnumerable<string> GetFileSearchPaths(string fileName)
{
    yield return fileName;
    yield return Path.Combine(
        Directory.GetParent(Path.GetDirectoryName(fileName)).FullName,
        Path.GetFileName(fileName)
    );
}

// or as an extension
static bool FileExists(string fileName)
{
    return GetFileSearchPaths(fileName).Any(File.Exists);
}

Usage:

if(FileExists(fileName)) ...

or you can get the actual file name from the search:

static string FindFile(this string fileName)
{
    return GetFileSearchPaths(fileName).FirstOrDefault(x => File.Exists(x));
}

var actualFileName = FindFile(fileName);

if (!string.IsNullOrEmpty(actualFileName)) ...


Calculate total cost of items, based on bulk discount I've written a short program for one of my first exercise in C++.... I would like to get better suggestions to solve it, so hope you can help me :) And I hope this is the right session to ask...:)

  Exercise:

  Input: Pieces and price per piece. If pieces > 10, its 5% discount. If pieces>50, 10% discount

  Output: total price

Thank you a lot in advance

#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int stk, ep, gesamt;
cout << "Pieces?" << endl;
cin >> stk;
cout << "Price per Piece?" << endl;
cin >>ep;
if (stk>=10)
{
    if (stk>=50)
    //10% discount
    {
    gesamt=stk*ep;
    gesamt=gesamt - (gesamt*10)/100;
    goto stop;
    }
     else   //5% discount
    gesamt=stk*ep;
    gesamt=gesamt - (gesamt*5)/100;
    goto stop;
}

else gesamt=stk*ep;

stop:
    cout << gesamt << endl;

return 0;
}

Avoid using namespace std

This can cause name collisions because it adds every name in the std namespace to the global namespace. For a small program like this one it's unlikely that you'll run into any problems (then again, maybe not) but it's best to get into the habit of using the std:: prefix on names in the std namespace.

Alternatively, you can introduce using declarations like using std::cout; to add specific names to the global namespace.

Avoid duplicated code like gesamt=stk*ep;

That statement appears three times in your code. If that logic ever changes you'll need to make sure you change it everywhere, and you might miss one or more instances. Put that duplicated code in a function if necessary, or just write it once if possible.

Indent for readability

None of the code in main() is indented, for example. It's easier to read your program if it's indented like this:

int main() {
  int stk, ep, gesamt;
  //...
}

Use more whitespace for readability

E.g. use gesamt = stk * ep; instead of gesamt=stk*ep;

Use descriptive variable names

The variable names seem to be in a different language (German?) but stk and ep in particular look like they are abbreviations or acronyms. I would prefer pieces for stk and unit_price for ep.

Avoid std::endl in favor of \n

std::endl flushes the stream, which can cause a loss in performance. In some cases you can also reduce calls to operator<< (e.g. cout << "Pieces?" << endl; becomes cout << "Pieces?\n";).

Check the problem statement logic

The problem statement says to apply a 5% discount if pieces > 10 but you use >=. Your code applies a discount if pieces = 10 but the problem statement implies that the discount should not be applied in that case (only starting with pieces = 11).

Use the appropriate type for variables

In this case, you probably need to use float or double for ep and gesamt. The price isn't necessarily an integer and neither is the total price if the discount is applied.

Check your inputs for error conditions

For example, neither the number of pieces nor the unit price should be negative. Check for these error conditions and handle them appropriately (output an error message, throw an exception, ask for a new input, etc.).

Avoid unnecessary goto statements

goto is generally not needed, and that is the case in your program. Your program will reach the stop statement after entering the various if/else clauses.

Result

Here's the end result of your program with the above suggestions (I've also made the code more concise in some cases, e.g. by the use of the *= operator to multiply a number by itself):

#include <iostream>

int main() {
    int pieces;
    double unit_price;
    double gesamt;

    std::cout << "Pieces?\n";
    std::cin >> pieces;

    if (pieces < 0)
    {
        std::cout << "Cannot have negative pieces!\n";
        return -1;
    }

    std::cout << "Price per Piece?\n";
    std::cin >> unit_price;

    if (unit_price < 0)
    {
        std::cout << "Cannot have negative unit price!\n";
        return -1;
    }

    // Calculate total price
    gesamt = pieces * unit_price;

    // Apply discount, if applicable
    if (pieces > 10)
    {
        if (pieces > 50)
        //10% discount
        {
        gesamt *= 0.9;
        }
        else   //5% discount
        {
        gesamt *= 0.95;
        }
    }

    std::cout << gesamt << '\n';

    return 0;
}


Leetcode: Roman digit to integer I tried to solve the question at https://leetcode.com/problems/roman-to-integer/ i.e Converting an Roman Digit to a Integer  using C#. It passes all the test cases but any suggestions to reduce  run time and memory usage would be appreciated.

    public static int RomanToInt(string s)
    {
        if (s.Length>=2)
        {
            int currentIndex = s.Length - 1,HighestValue=CharacterValue(s[currentIndex]),number=HighestValue;
            currentIndex--;
            while (currentIndex>=0)
            {
                int currentValue = CharacterValue(s[currentIndex]);
                if(currentValue >= HighestValue)
                {
                    number = number + currentValue;
                    HighestValue = currentValue;
                }

                else
                {
                    number = number - currentValue;
                }

                currentIndex--;
            }

            return number;

        }
        else
        {
            return CharacterValue(s[0]);
        }
    }

    public static int CharacterValue(char c)
    {
        switch (c)
        {
            case 'I': return 1;
            break;
            case 'V':
                return 5;
                break;
            case 'X':
                return 10;
                break;
            case 'L':
                return 50;
                break;
            case 'C':
                return 100;
                break;
            case 'D':
                return 500;
                break;
            case 'M':
                return 1000;
                break;
             default:
                 return 0;
             break;
        }

    }

}

Run time is linear, and memory usage is constant (and small), so I don't think you're going to see much improvement in either.

You might be able to make some slight improvements by using pointers in unsafe mode (see https://stackoverflow.com/questions/13179554/is-it-faster-to-access-char-in-string-via-operator-or-faster-to-access-char-i), but unless you're processing a very large number of strings this is probably not necessary.  As always, profile before and after making any optimizations!

Stylistically, there are a few improvements that could be made:

Declare your variables in separate statements.
HighestValue should be highestValue.
In CharacterValue, you don't need to break when you're returning anyway.
It would be clearer to remove the blank line between the inner if and else.
You don't need the outer if/else for the length of the string; the code inside the main case would handle a length-1 string fine.
The way the logic works, the first item doesn't have to be handled as a special case, so this could be rewritten as a for loop, which would make it (for many people) easier to read.

And one functional one - your code doesn't currently handle the string being null or empty; it should either return 0 or throw an appropriate exception in that case, depending on whether you consider that to be valid input.

So for example:

    public static int RomanToInt(string s)
    {
        if (string.IsNullOrEmpty(s))
        {
            return 0;
        }

        int highestValue = 0;
        int number = 0;

        for(int currentIndex = s.Length - 1; currentIndex >= 0; currentIndex--)
        {
            int currentValue = CharacterValue(s[currentIndex]);

            if (currentValue >= highestValue)
            {
                number += currentValue;
                highestValue = currentValue;
            }
            else
            {
                number -= currentValue;
            }
        }

        return number;
    }

    private static int CharacterValue(char c)
    {
        switch (c)
        {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default:  return 0;
        }
    }


Count byte length of string I am looking for some guidance and optimization pointers for my custom JavaScript function which counts the bytes in a string rather than just chars. The website uses UTF-8 and I am looking to maintain IE8 compatibility.

/**
 * Count bytes in string
 *
 * Count and return the number of bytes in a given string
 *
 * @access  public
 * @param   string
 * @return  int
 */
function getByteLen(normal_val)
{
    // Force string type
    normal_val = String(normal_val);

    // Split original string into array
    var normal_pieces = normal_val.split('');
    // Get length of original array
    var normal_length = normal_pieces.length;

    // Declare array for encoded normal array
    var encoded_pieces = new Array();

    // Declare array for individual byte pieces
    var byte_pieces = new Array();

    // Loop through normal pieces and convert to URL friendly format
    for(var i = 0; i <= normal_length; i++)
    {
        if(normal_pieces[i] && normal_pieces[i] != '')
        {
            encoded_pieces[i] = encodeURI(normal_pieces[i]);
        }
    }

    // Get length of encoded array
    var encoded_length = encoded_pieces.length;

    // Loop through encoded array
    // Scan individual items for a %
    // Split on % and add to byte array
    // If no % exists then add to byte array
    for(var i = 0; i <= encoded_length; i++)
    {
        if(encoded_pieces[i] && encoded_pieces[i] != '')
        {
            // % exists
            if(encoded_pieces[i].indexOf('%') != -1)
            {
                // Split on %
                var split_code = encoded_pieces[i].split('%');
                // Get length
                var split_length = split_code.length;

                // Loop through pieces
                for(var j = 0; j <= split_length; j++)
                {
                    if(split_code[j] && split_code[j] != '')
                    {
                        // Push to byte array
                        byte_pieces.push(split_code[j]);
                    }
                }
            }
            else
            {
                // No percent
                // Push to byte array
                byte_pieces.push(encoded_pieces[i]);
            }
        }
    }

    // Array length is the number of bytes in string
    var byte_length = byte_pieces.length;

    return byte_length;
}

It would be a lot simpler to work out the length yourself rather than to interpret the results of encodeURI().
/**
 * Count bytes in a string's UTF-8 representation.
 *
 * @param   string
 * @return  int
 */
function getByteLen(normal_val) {
    // Force string type
    normal_val = String(normal_val);

    var byteLen = 0;
    for (var i = 0; i < normal_val.length; i++) {
        var c = normal_val.charCodeAt(i);
        byteLen += (c & 0xf800) == 0xd800 ? 2 :  // Code point is half of a surrogate pair
                   c < (1 <<  7) ? 1 :
                   c < (1 << 11) ? 2 : 3;
    }
    return byteLen;
}

JavaScript implementations may use either UCS-2 or UTF-16 to represent strings.
UCS-2 only supports Unicode code points up to U+FFFF, and such Unicode characters occupy 1, 2, or 3 bytes in their UTF-8 representation.  This is not too tricky to handle.
However, as @Mac points out, UTF-16 surrogate pairs are a tricky special case.  UTF-16 extends UCS-2 by adding support for code points U+10000 to U+10FFFF, which UTF-16 encodes using a pair of code points.  The first code point of such a pair (called the "high surrogate") is in the range D800 to DBFF; it should always be followed by another code point (called the "low surrogate") is in the range DC00 to DFFF.  Observe that the UTF-8 representation of any character in the range U+10000 to U+10FFFF would take 4 bytes.  Therefore, any surrogate pair in UTF-16 would translate to a 4-byte UTF-8 representation.  Or, we could say that whenever we encounter half of a surrogate pair (i.e., a code point is in the range from D800 to DFFF), just add two bytes to the UTF-8 length.


Compute the outputs of a generator in parallel I am processing an unknown "length" of  generator object.
I have to keep things "lazy" because of memory management.
The processing is compute heavy, so writing it multiproc style is the solution (or at least it seems for me).
I have solved this problem of multiproc on generator object with a combination of monkey patch and a bounded Queue.
What really itches me is the monkey patch...
Do you think this is fine to apply imap() on a generator object? How would you do this?
I would like to underline that the focus is to compute the outputs of a generator in parallel.
From the perspective of this "minimal example" :
process_line, process_line_init, process_first_n_line

are the functions I am most interested about your opinion.
import multiprocessing as mp
import psutil
import queue
from typing import Any, Dict, Iterable, Set

def yield_n_line(n: int)-> Iterable[Dict[str, str]]:
    for i in range(n):
        yield {'body': "Never try to 'put' without a timeout sec declared"}

def get_unique_words(x: Dict[str, str])-> Set[str]:
    return set(x['body'].split())

def process_line(x:Dict[str, str])-> Set[str]:
    try:
        process_line.q.put(x, block=True, timeout=2)
    except queue.Full:
        pass
    return get_unique_words(x)

def process_line_init(q: mp.Queue)-> None:
    process_line.q = q

def process_first_n_line(number_of_lines: int)-> Any:
    n_line = yield_n_line(number_of_lines)

    if psutil.cpu_count(logical=False) > 4:
        cpu_count = psutil.cpu_count(logical=False)-2
    else:
        cpu_count = psutil.cpu_count(logical=False)
    q = mp.Queue(maxsize=8000)
    p = mp.Pool(cpu_count, process_line_init, [q])
    results = p.imap(process_line, n_line)
    for _ in range(number_of_lines):
        try:
            q.get(timeout=2)
        except queue.Empty:
            q.close()
            q.join_thread()
        yield results.next()
    p.close()
    p.terminate()
    p.join()
    pass

def yield_uniqueword_chunks(
    n_line: int = 10_000_000,
    chunksize: int = 1_787_000)-> Iterable[Set[str]]:
    chunk = set()
    for result in process_first_n_line(n_line):
        chunk.update(result)
        if len(chunk) > chunksize:
            yield chunk
            chunk = set()
    yield chunk

def main()-> None:
    for chunk in yield_uniqueword_chunks(
        n_line=1000, #Number of total comments to process
        chunksize=200 #number of unique words in a chunk (around 32MB)
        ):
        print(chunk)
        #export(chunk)

if __name__ == "__main__":
    main()

Here's a condensed illustration of how to achieve your stated purpose, namely
to compute the outputs of a generator in parallel. I offer it because
I could not understand the purpose of most of the complexity in your current
code. I suspect there are issues that you have not explained to us or that I
failed to infer (if so, this answer might be off the mark). In any case,
sometimes it helps to look at a problem in a simplified form to see
whether your actual use case might work just fine within those parameters.
import multiprocessing as mp

def main():
    for chunk in process_data(1000, 50):
        print()
        print(len(chunk), chunk)

def process_data(n, chunksize):
    # Set up the Pool using a context manager.
    # This relieves you of the hassle of join/close.
    with mp.Pool() as p:
        s = set()
        # Just iterate over the results as they come in.
        # No need to check for empty queues, etc.
        for res in p.imap(worker, source_gen(n)):
            s.update(res)
            if len(s) >= chunksize:
                yield s
                s = set()

def source_gen(n):
    # A data source that will yield N values.
    # To get the data in this example:
    # curl 'https://www.gutenberg.org/files/2600/2600-0.txt' -o war-peace.txt
    with open('war-peace.txt') as fh:
        for i, line in enumerate(fh):
            yield line
            if i >= n:
                break

def worker(line):
    # A single-argument worker function.
    # If you need multiple args, bundle them in tuple/dict/etc.
    return [word.lower() for word in line.split()]

if __name__ == "__main__":
    main()

This example illustrates a garden-variety type of parallelization:

The data source is running in a single process (the parent).

Downstream computation is
running in multiple child processes.

And final aggregation/reporting
is running in a single process (also the parent).

Behind the scenes, Pool.imap() is
using pickling and queues to shuttle data between processes. If your real
use case requires parallelizing data generation and/or reporting,
a different approach is needed.


Optimizing a query with many joins I have a query which selects a show from anime_series, then selects corresponding information from other tables (such as studio, which is stored as a SMALLINT reference to another table). The below query works as intended, but I really don't believe my code is as efficient as it can or should be.

The real complexity is that shows can and often do have multiple genres and studios. I'm current using GROUP_CONCAT on the multiple genres, studio names, and studio links, though I'm not sure this is the best method. I'm using a sub query for the next episode because I only need the first episode that hasn't aired, again, my method is probably over-complicating it.

SELECT
    anime.*,
    episode.number AS episode,
    episode.air_date AS ep_airdate,
    station.name AS station_name,
    station.link AS station_link,
    GROUP_CONCAT(DISTINCT genre.name ORDER BY LOWER(genre.name)) AS genres,
    GROUP_CONCAT(DISTINCT studio.name) AS studio_names,
    GROUP_CONCAT(DISTINCT studio.link) AS studio_links
FROM
    `anime_series` AS anime
LEFT JOIN (
    SELECT
        `air_date`,
        `series`,
        `number`
    FROM
        `anime_episodes`
    WHERE
        `air_date` > NOW()
    GROUP BY `series`) episode
    ON anime.id = episode.series
LEFT JOIN `anime_stations` station
    ON anime.station = station.id
LEFT JOIN `anime_genre_connections`
    ON anime_genre_connections.series_id = anime.id
    JOIN `anime_genres` AS genre
        ON anime_genre_connections.genre_id = genre.id
LEFT JOIN `anime_studio_connections`
    ON anime_studio_connections.series = anime.id
    JOIN `anime_studios` AS studio
        ON anime_studio_connections.studio = studio.id
WHERE anime.id = 1
GROUP BY anime.id;

Here's some table examples (anime_series missing irrelevant columns):

anime_series
id | station
 1 |    1

anime_stations
id |     name     |        link
 1 | Something TV | http://example.com

anime_episodes
id | series |       air_date      | number
 1 |   1    | 2013-07-09 01:00:00 |   1
 2 |   1    | 2013-07-16 01:00:00 |   2

anime_genre_connections
id | series_id | genre_id
 1 |     1     |    1
 2 |     1     |    2

anime_genres
id |   name
 1 |  Comedy
 2 |  Action

anime_studio_connections
id | series | studio
 1 |    1   |    1
 2 |    1   |    2

anime_studios
id |      name    |       link
 1 |  Example     | http://example.com
 2 |  Some Studio | http://example.com

EDIT: I should also add that I'm splitting the returned columns genres, studio_names, and studio_links into arrays after the query has executed.

I would say the DISTINCT keywords in the following quote are superfluous. I would recommend to explicitely use INNER JOIN but even as it is, your JOIN clauses should implicitly compute that already. The only time I would use DISTINCT would be if I suspected that one anime had duplicate records of multiple of the same studio/genre.

GROUP_CONCAT(DISTINCT genre.name ORDER BY LOWER(genre.name)) AS genres,
GROUP_CONCAT(DISTINCT studio.name) AS studio_names,
GROUP_CONCAT(DISTINCT studio.link) AS studio_links

Your use of GROUP_CONCAT() should not cause much if any performance difference, as it computes that on the result set to display it differently. I'm curious about the reason you are using LEFT JOIN and joining a subquery, can you clarify?