Welcome!

    I'm a software developer for Cox Media Group living in Santa Maria, CA. This is my site where I post my work in software, game-making, and writing. My contact information is to the left if you'd like to know more about me. Thanks for stopping by.

batchrc Update - minify.bat

posted Apr 24, 2013, 11:01 PM by Dan Cobb   [ updated Apr 25, 2013, 11:29 PM ]

    Just a quick post about a really sweet script I just wrote to minify all JavaScript and CSS files for an entire project. Uses jsmin and csstidy and will recurse throughout all subdirectories. This tool is meant to be ran in an umbrella resource directory that contains all JS and CSS for a site. The tool will run minify in those subdirectories, ex) myproject/resources/css/mystyle.css

Eta - Minimalistic Templating

posted Apr 19, 2013, 8:59 PM by Dan Cobb   [ updated Apr 19, 2013, 9:02 PM ]

    A few months ago I made a post about a bare-bones templating approach. Well, since then I have used that engine on several small projects and kept finding myself with the need for a (very slightly) expanded feature set. So, after hammering out some of the finer points and testing it out on a few projects, I have released Eta - a lightweight PHP templating engine designed for rapid prototypes and small-scale web applications. The name comes from the Greek alphabet and shares its capital symbol with modern English's letter H. The symbol for the letter eta (granted, lowercase) is often used in math as the symbol for efficiency.

    Eta was designed for prototypes and small-scale web applications that need to be developed and deployed quickly with minimal setup. Meaning, with one require statement, you can be ready to use the engine. Since Eta does not use custom template tags, projects can be easily turned over to a more robust framework, like Cake or Yii, in the future - which I feel really reflects that this engine was created with development speed in mind.

    Here is a simple Hello World example to illustrate how dirt simple Eta is to start using.
// index.php
require_once "eta.php";
$who = "World";
echo H::render(null, [
    "name" => $who
]);
// base.view
Hello <?= $name ?>!
    > Link to Eta's GitHub: https://github.com/cobbdb/eta

HTTP Cookies and You: a PHP tutorial

posted Feb 23, 2013, 11:26 PM by Dan Cobb   [ updated Mar 7, 2013, 9:52 PM ]

    I've been building a MediaWiki bot as a new feature for version 1.4 of the Apprount tool I made a few months ago. This will enable the tool to make very large queries to the API thereby reducing the total average number of requests made per Apprount query. The tricky part is that the MediaWiki API requires several pieces of session data to be passed as cookies, which means I had to build this into the system. Using Apprount as a scenario, here are the basics of working with HTTP cookies.

Server Response
    When the server wants you to set cookie data, the header will contain the following:
Set-Cookie: <name>=<value>; <potentially other information such as expiration or path data>;
Set-Cookie: <name2>=<value2>
    This header information is essentially a command from the server, telling your system to remember certain bits of information. How I recommend doing this will follow shortly.

Client Request
    Now that you know what the server wants you to remember, your next request should contain that cookie information in this format:
Cookie: <name>=<value>; <name2>=<value2>; 
    Notice that this is not two separate lines, this is all cookie data together on the same line separated by semi-colons. The last pair of data can have a semi-colon and a space optionally, but leaving it on will clean up the loop that assembles this string (see below).

My Cookie Engine
    Now for the implementation. Below is sample code of an engine I put together for Apprount that does a great job of automating cookie data without needing to add yet another framework to the mix.
    Please note that this code was built for the scenario of a MediaWiki bot and will need to be customized to fit your specific project.
class YourAPI {
    /**
     * Cookie information to be added to request headers.
     */
    private static $cookieJar = Array();
    
    /**
     * Parse an http response header for cookie information.
     * @see http://stackoverflow.com/questions/10958491/get-cookie-with-file-get-contents-in-php/10958820
     * @param {Array} responseHeader Magic value set by calling file_get_contents()
     * @returns {Array}
     */
    public static function getResponseCookies($responseHeader) {
        $cookies = Array();
        foreach ($responseHeader as $hdr) {
            if (preg_match('/^Set-Cookie:\s*([^;]+)/', $hdr, $matches)) {
                parse_str($matches[1], $tmp);
                $cookies += $tmp;
            }
        }
        return $cookies;
    }
    
    /**
     * Query MediaWiki API for information.
     * @param {Array} data Request parameters.
     * @param {Array} [header] Additional header information. Defaults to cookie jar.
     * @param {String} [url] API url. Defaults to Appropedia's API.
     * @returns {Array} API response.
     */
    public static function query($data, $header = null, $url = false) {
        // Assemble header from cookie jar if no header supplied.
        if ($header === null) {
            $header = Array();
            $header[] = self::buildCookieSheet(self::$cookieJar);
        }
        
        // Send request for data.
        $url = ($url) ? $url : "YourAPIsURI";
        $context = self::createPostContext($data, $header);
        $res = file_get_contents($url, false, $context);
        $res = unserialize($res);
        
        // Add any cookies from the response to the cookie jar.
        $cookies = self::getResponseCookies($http_response_header);
        self::$cookieJar = array_merge(self::$cookieJar, $cookies);
        
        return $res;
    }

    /**
     * @param {Array} data Request parameters.
     * @param {Array} [header] Additional header information.
     * @returns {StreamContext}
     */
    private static function createPostContext($data, $header = Array()) {
        $header[] = "Content-type: application/x-www-form-urlencoded";
        $header[] = "User-Agent: YourToolName/Version (SiteURI; YourEMail)";
        $opts = Array(
            "http" => Array(
                "method" => "POST",
                "header" => $header,
                "content" => http_build_query($data)
            )
        );
        return stream_context_create($opts);
    }
    
    /**
     * Convert a set of key/value cookie data pairs to a single string.
     * @param {Array} cookies In ["<name>"] = "<value>" form.
     * @returns {String} In "Cookie: <name>=<value>; " form.
     */
    private static function buildCookieSheet($cookies) {
        $sheet = "Cookie: ";
        foreach ($cookies as $key => $value) {
            $sheet .= "$key=$value; ";
        }
        return $sheet;
    }
}

Parsing URI Queries in JavaScript

posted Oct 15, 2012, 3:08 PM by Dan Cobb

    For a recent project, I was tasked with parsing a URI query in JavaScript. Normally, this behavior is handled by the application (PHP, Ruby, Python, Node, etc.) so I wasn't terribly surprised to find that there are almost no examples out there.
/**
 * @param {String} query Typically the result of window.location.search.
 */
function parseQuery(query) {
    // Decode the uri and remove the leading '?'.
    query = decodeURIComponent(query);
    query = query.substr(1);
    
    var result = {};
    var params = query.split("&");
    for (var i in params) {
        var pair = params[i].split("=");
        result[pair.shift()] = pair.join("=");
    }
    return result;
}
    The only real trickery here is in cases where an attribute's value contains an equal sign. Ex.) "&a=b=c&". In this case, only the left-most equal sign should be treated as a delimiter, so I use the shift/0 method to grab the attribute's name and then join what's left over and treat that as the attribute's value. Pretty straightforward, but it seemed to get the job done for me.

Bare-bones PHP Template Engine

posted Sep 19, 2012, 8:32 PM by Dan Cobb   [ updated Sep 24, 2012, 10:14 AM ]

    Lately I've been doing some work for a professor back at HSU sprucing up one of his sites and cleaning up a lot of my old code base (for past projects such as Apprount). While I was refactoring I came to a point where I could go no further without breaking up some of the giant (1000+ lines) script and markup files. So, I decided to code up an absolute minimum template engine to bring a touch of MVC to the mix - minus the C in this case. Here's the code:
/**
 * @usage
 * VIEW:
 *   <?php echo $body ?>
 * PHP:
 *   echo Template::render(null, Array(
 *       "body" => $myHTML
 *   ));
 */

class MissingTemplateException extends Exception {
}

final class Template {
    /**
     * Render a template without auto-responding.
     * @param view Filename of the template to render.
     * @param model Data to inject into the template.
     * @returns String of HTML.
     */
    public static function render($view, $model = Array()) {
        if (!isset($view)) {
            $view = $_SERVER["DOCUMENT_ROOT"] . "/util/pepage.view";
        }
        
        if (file_exists($view)) {
            ob_start();
            extract($model);
            @require $view;
            return ob_get_clean();
        } else {
            throw new MissingTemplateException("Template: $view could not be found!");
        }
    }
}
    This engine is adapted from a great blog post here: http://proccli.com/2010/03/dead-simple-php-template-rendering/. I just wrapped it in a class so that its usage would be more transparent. The only problem I had with the vanilla code was with the echo shorthand tag - they are deprecated now (as of 5.3.0) and the PHP server I use has the option off by default. Other than that, this is an absolutely fantastic chunk of code!

Dirt Simple Node Express Example

posted Aug 23, 2012, 9:03 PM by Dan Cobb   [ updated Mar 1, 2013, 10:42 AM ]

    I've been working a lot with Node lately, and I decided it was time to dive into the packages available. To put it kindly, the documentation on even the best of these packages is extremely lacking. So, after many hours of reading and searching here is a small simple example for anyone learning to use Express.
// Grab Express resources.
var express = require("express");
var app = express();

// Configure Express MVC. You MUST pick a template
//   engine to use and Jade is fantastic. If you
//   don't want to convert existing HTML, then
//   webfiller is your best bet.
app.set("views", __dirname + "/archive/PPP");
app.set("view engine", "jade");

// Here is where static files (ex JS & CSS) are
//   routed. If you aren't using MVC, then this
//   is all you need to serve your static pages.
//   For this example, I have Express routing any request
//   for ./PPP/res to ./archive/PPP.
//   Change these paths to your values.
app.use(
    "/PPP/res",
    express.static(
        __dirname + "/archive/PPP"
    )
);

// Here is where you route views. I chose to
//   route all requests to PPP to the index page.
//   The second argument to res.render() is the
//   model which your template can use.
app.get("/PPP", function (req, res) {
    res.render("index", {
        greeting: "Welcome Back!",
        version: "v1.2"
    });
});

// Start up the server.
app.listen(8000);
console.log("Server listening on port 8000.");

UpgradeJS

posted Aug 18, 2012, 2:04 AM by Dan Cobb   [ updated Apr 22, 2013, 12:08 PM ]

    There are a lot of options for handling websockets in NodeJS, but all seem to be far too over-designed for any of my projects (special client-side sockets??). So, I put together a very lightweight library to handle http upgrade requests and decrypt incoming data.

To install (from command prompt)
npm install upgrade
Example of use (server side)
var http = require("http");
var upgrade = require("upgrade");

var server = http.createServer();

// Notice this is all with native NodeJS
server.on("upgrade", function (req, socket) {
    // Write header for upgrade request
    upgrade.writeHead(req, socket);

    socket.on("data", function (buff) {
       // Buffer data is masked, so decrypt it
       var data = upgrade.getData(buff);
       console.log(">" + data);
    });
});
server.listen(8000);
Example of use (client side)
// Remember to update the address with your own!
var socket = new WebSocket("ws://localhost:8000");
[..]
// No special socket needed here unlike other
//   libraries ex) socket.io
socket.send("cool message");
    There really isn't much to say about it, basically it can respond with the appropriate header to complete the upgrade handshake and has a function to unmask incoming data. This library is just meant to be a quick and simple solution to work with most projects, so hopefully it will help someone else out there!

AssertJS

posted Aug 12, 2012, 1:08 PM by Dan Cobb   [ updated Aug 14, 2012, 10:46 AM ]

    A very lightweight unit-test library, I wrote AssertJS to aid in my goal of test-driven development. There are essentially three areas of interest when using AssertJS:
  • $A.is*: These are three convenience functions to handle what I consider the three most common tests - isEqual, isGreater, isLess.
user.setName("John Doe");
var name = user.getName();
$A.isEqual(name, "John Doe", "getName/0 Test");
  • $A.test: A test is an atom of assertions that will run to completion before throwing an error if an assertion fails.
$A.test(function () {
    var volume = getVolume();
    $A.isGreater(volume, 0);
    $A.isLess(volume, 100);
}, "Volume Test");
  • $A.assert: Here is where more complex structures can be tested, as well as testing outside of the three convenience functions. ex) greater-than-or-equal-to.
var shape = createShape();
$A.assert(function () {
    return (shape.color !== Color.GREEN);
}, "Green shape was created!", shape.color);
    While I fully believe this library should be written by extending Object.prototype, intricacies of the language (and incompatibilities with jQuery) mean I have to take a more Java approach.
    The library is being developed on GitHub here: https://github.com/PetitGibier/AssertJS/blob/master/assert.js
    Hosting on Google Code:
<script type="text/javascript" src="http://assertjs.googlecode.com/files/assert.js"></script>

Interview Questions, pt. 3

posted Aug 7, 2012, 10:22 PM by Dan Cobb   [ updated Feb 28, 2013, 10:52 AM by Dan Cobb ]

    Here's an interesting problem that was asked with a time limit attached - I wasn't able to solve it within the specified amount of time, but I finally got there after giving it some time to marinade in my subconscious.

Given a string of digits and a target value, place '+' or '*' between each pair of digits so they compute exactly to the target value.

Test Cases:
  • "123456",33 becomes "1+2*3+4*5+6"
  • "456789",80 becomes "4+5+6+7*8+9"
  • "456789",84 becomes "no solution"
Solution:
    My first idea was to break the digits up into a tree, evaluate each node, and then compare nodes - typical divide and conquer. However, without knowing which node is addition and which is multiplication, the tree approach is not viable (think order of operations). So, I decided to stop trying to be clever and just get a solution down (translation: brute force). Let me just state that I don't like this solution - O(2n-1) yuck! - but at least it works. I chose to solve the problem in JavaScript.
/**
 * Inserts + and * to match counter value.
 * '+' is a 0
 * '*' is a 1
 */
String.prototype.toExpression = function (counter) {
    var digit, binValue, operator;
    var expression = this.charAt(0);
    
    // build expression from digits and operators
    for (var i = 1; i < this.length; i += 1) {
        digit = this.charAt(i);
        binValue = Math.pow(2, this.length - i - 1);
        
        // Check if binary value of digit is in range
        //   of desired value.
        // ex) 100b > 2, 010b = 2, 001b < 2
        if (binValue > counter) {
            operator = "+";
        } else {
            counter -= binValue;
            operator = "*";
        }
        
        expression += operator + digit;
    }
    return expression;
};

String.prototype.insertOperators = function (total) {
    var maxCount = Math.pow(2, this.length - 1);
    var expression, evaluation;
    
    // iterate through every possible permutation
    // O(2n-1) complexity :[
    for (var i = 0; i < maxCount; i += 1) {
        expression = this.toExpression(i);
        evaluation = eval(expression);
        
        if (evaluation === total) {
            return expression;
        }
    }
    return "no solution";
};

// Part of my personal unit test library. I will probably post
//   more on this later.
String.prototype.assertEquals = function (pass, message) {
    message = message || "";
    
    if (this.valueOf() !== pass) {
        console.log(
            "Failed! [" + message + "]\n\t" +
            this + " != " + pass
        );
    }
};

// tdd ftw!
"1234".toExpression(3).assertEquals("1+2*3*4", "toExpression(3)");
"1234".toExpression(4).assertEquals("1*2+3+4", "tE(4)");
"123456".insertOperators(33).assertEquals("1+2*3+4*5+6", "insertOperators(33)");
"456789".insertOperators(80).assertEquals("4+5+6+7*8+9", "iO(80)");
"456789".insertOperators(84).assertEquals("no solution", "iO(84)");
    My main approach is to count from 0 to 2n-1 treating the operators as base 2 digits. Starting with 0 (all +, ex. 1+2+3) and stopping before 2n-1 (all *, ex. 1*2*3) where n is the number of digits. This solution also does not account for malformed strings (ex. those with letters), but that was not listed as a test case, so I think it's okay here.

Basic JavaScript Object Patterns

posted Jul 13, 2012, 3:56 PM by Dan Cobb   [ updated Aug 19, 2013, 2:20 PM by Dan Cobb ]

    I've been spending a lot of time recently on JavaScript and I thought it would be helpful to someone out there if I posted sample code for the four most basic object-oriented patterns: enumeration, constructor definition, parasitic inheritance, and the singleton. If you notice, I will refrain from using the word 'class' in my descriptions since JS is a classless language (weird, I know). 

General style rules to keep you and your code happy and healthy:
  • Avoid these at all costs!
    • Operators: this, new, ++ (yes avoid N++! use N += 1 instead!)
    • No singletons! They will make your life a nightmare when you write tests.
    • No immediate functions! Use a module loader (like RequireJS) instead!
  • Use these often!
    • Constructors return literal objects.
    • Leave no lint! I recommend forcing yourself to code like Crockford - use jslint.com.
Now for some code examples.

Enumeration:
// Probably the most straightforward pattern,
//   but one of the easiest to overlook in my opinion.
// USAGE: var myColor = Color.RED;
var Color = {
    RED: {
        name: 'Red',
        code: '#FF0000'
    },
    GREEN: {
        name: 'Green',
        code: '#00FF00'
    }
};
Constructor Definition:
// Contract for a Shape
// Notice the 'guts' of Shape are not strung out
//   with prototype modifications.
function Shape() {
    var privateField = 'Secret Value.';
    var privateMethod = function () {
    };
    
    return {
        publicField: 'No secrets here.',
        publicMethod: function () {
        },
        // Method used in next example.
        draw: function () {
        }
    };
}
Shape.staticMember = 'Only one of me.';
Parasitic Inheritance:
function Circle(color) {
    // Inherit from Shape
    var circle = Shape();
    
    // Set some public fields
    circle.x = 10;
    circle.y = 10;
    circle.radius = 15;
    circle.color = color;
    
    // Override draw method from Shape
    circle.draw = function () {
        // System is defined in example below.
        // draws a circle to the System singleton's canvas
        System.gfx.beginPath();
        System.gfx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2, true);
        System.gfx.closePath();
        
        System.gfx.fillStyle = circle.color.code; // Notice use of Color
        System.gfx.fill();
    };
    
    return circle;
}
Singleton:

Please NOTE: Singletons that contain state are always a bad idea. For example, the Math singleton is fine because it only contains leaf methods. However, the example below would be a nightmare to unit test as it hides its dependencies and creates a form of global state. I am only including this pattern for the sake of explanation. Don't believe me? I'll defer to Misko Hevery to change your mind.

// By evaluating this anonymous function,
//   we can ensure that this is the only time this
//   pseudo constructor can be called.
//   ex) var sys = new System(); is not legal.
var System = (function () {
    var privateField = 'More Secrets.';
    var privateMethod = function () {
    };
    // Context set as public field below.
    var canvas = Canvas();
    
    return {
        publicField: 'Public Data.',
        publicMethod: function () {
        },
        // Field used in inheritance example above.
        gfx: canvas.getContext('2d')
    };
})();
    If you are down for a more advanced look into JavaScript, here is a link to David Crockford's site: http://www.crockford.com/javascript/.

1-10 of 50