Category Archives: howto

JQuery dataTable plugin quick notes

Server-side processing

To return the names of the columns you want, you need to use aoColumndefs and provided individual objects with the property sName.

Below is most of the implementation for a jeditable Ajax driven dataTables, this is the Alpha version and still needs a lot of love in places, but the gist of it is here

var semesterTable = $("#semesterViewTable").dataTable({
                "bProcessing"   : true
            ,   "bServerSide"   : true
            ,   "sAjaxSource"   : ""
            ,   "fnRowCallback" : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                                    //console.log(nRow, aData, iDisplayIndex, iDisplayIndexFull);
                                    var recordId = aData[0];
                                    $("td", nRow).data("recordId", recordId);
                                    return nRow;
                                }
            , "fnDrawCallback"  : function(){
                                    $("td.editableMajor")
                                        .editable("",
                                                    {                                                        
                                                          loadurl: ""
                                                        , type: "select"
                                                        , submit: "OK"
                                                        , method: "post"
                                                        , submitdata: function(){
                                                            console.log(this, arguments);
                                                            var $this = $(this);
                                                            return {
                                                                    recordId: $this.data("recordId")
                                                                    , classes: $this.attr("class")
                                                                }
                                                        }
                                                    });
                                   
                                }
            /* Seriously a meta-generator for this would be nice */
            ,"aoColumnDefs": [
                ,{ sName:"record_id",          aTargets:[00], bSearchable:false, bVisible:false }
                ,{ sName:"roster_date",         aTargets:[01], sClass:"roster_date"}
                ,{ sName:"roster_name_both",    aTargets:[02], sClass:"roster_name_both"}
                ,{ sName:"roster_student_id",   aTargets:[03], sClass:"roster_student_id"}
                ,{ sName:"roster_major1",       aTargets:[04], sClass:"roster_major1 editableMajor"}
                ,{ sName:"roster_major2",       aTargets:[05], sClass:"roster_major2 editableMajor"}
                ,{ sName:"roster_major3",       aTargets:[06], sClass:"roster_major3 editableMajor"}
                ,{ sName:"roster_major4",       aTargets:[07], sClass:"roster_major4 editableMajor"}
                ,{ sName:"roster_minor1",       aTargets:[08], sClass:"roster_minor1 editableMajor"}
                ,{ sName:"roster_minor2",       aTargets:[09], sClass:"roster_minor2 editableMajor"}
            ]
    });

For the tbody, just put something like

        <tbody><tr><td>Chill the fuck out, it's loading</td></tr></tbody>

Server side data contract

dataTables expects a JSON’ified construct like this

$responseBody = array(
		"sEcho" => intval($input['sEcho']),
		"iTotalRecords" => (int) $count,
		"iTotalDisplayRecords" => count($data),
		"aaData" => $data
            );

  • sEcho is a security variable used by dataTables, basically just send it back and don’t worry about it
  • iTotalRecords – is the MAXIMUM # of records in the data set without any filtering
  • iTotalDisplayRecords – is the MAXIMUM # of records in the data set WITH filtering
  • An array of numerically indexed arrays, dataTables doesn’t like associative arrays

Total and Display total records

If the blink tag still worked reliably, I’d put a neon sign here. Basically you need to do 3 queries per Ajax call… call 1 is to get a

 
   SELECT count(1) FROM sourceTABLE

call 2 is

 SELECT count(1) FROM sourceTable WHERE someCriteria 

and finally call 3 is

 SELECT yourColumnList FROM sourceTable WHERE someCriteria

With memcache or such, I’d advise caching the total count but no matter what you unfortunately need to make these three SQL calls :(.

Advanced collision detection

Unfortunately I haven’t gotten the chance to completely read this ( http://www.wildbunny.co.uk/blog/2011/03/25/speculative-contacts-an-continuous-collision-engine-approach-part-1/ ) but what I’ve read has been very educational and potentially useful for future game development.

A quick synopsis is that the linked article provides a very well documented approach for dealing with collisions in time. Say you have an object that should have collided with another, but it’s velocity or translation across the drawing surface is so high that in the time between frames it completely skips over another entity without colliding. In physical reality there would be a collision, but in computer terms there isn’t easy logic to detect and resolve these false-negative near misses.

Python helping PHP development

Just a quick little utility script I wrote to make watching PHP error logs a tad easier:

Usage is

#tail -F /var/log/php/php_error.log | ~/bin/parsePHPErrors.py

Thanks to this Stackoverflow question, it even colorizes!

#!/usr/bin/python
import sys
import os
import re

input = os.fdopen(sys.stdin.fileno(),'r',100)
regex = re.compile("(.*?PHP (Warning|Error|Notice|):.*)")
line = input.readline()

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'    
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'


myColor = bcolors.OKGREEN

while line:
    
    if regex.match(line) or line.find("TODO") > -1:
        
        isCorrect = True
        
        if line.find("Fatal error") > -1:
            myColor = bcolors.FAIL
            pass
        elif line.find("Error")  > -1:
            myColor = bcolors.FAIL
            #todo get console color code
            pass
        elif line.find("Warning")  > -1:
            myColor = bcolors.WARNING
            pass
        elif line.find("Notice")  > -1:
            myColor = bcolors.OKBLUE
            pass
        elif line.find("TODO") > -1:
            myColor = bcolors.OKBLUE
            pass
        
        if isCorrect:            
            print "#"*25, "@"*25, "#"*25
            print
    else:
        pass
        #myColor = bcolors.OKGREEN
        
        
    print myColor, line.strip(), bcolors.ENDC
    line = input.readline()

Output looks like:

######################### @@@@@@@@@@@@@@@@@@@@@@@@@ #########################

[28-Mar-2011 11:14:10] PHP Notice:  Undefined variable: sql in

basically breaking up individual error messages into visually easy to spot blocks

Canvas pixel collision detection

So… a fair number of people arrive here looking for how to detect when a pixel/object/thing has collided with something else.

I’ll add more information in the future but in the interim, the quick and dirty advice I can provide:

Given p = x, y where this is the point your trying to determine if it intersects another… the best place is to start with bounding box logic.  Regardless of what shape your object is, if wrap it in an invisible box boundry, it’s relatively trivial to do:

box upper left origin is bX, bY off size sizeX, sizeY.   If p.x greater then bX and p.x less then bX + sizeX AND p.y greater then bY and p.y less then bY + sizeY   you’re inside the bounding box and it’s highly likely your point has or will soon be colliding with an object.

That’s pretty much it and is perfect if you don’t mine lagging the crap out of whatever is running this logic.    To make these collision checks performant, you need to make the computer do less work.   For two dimensional space, my personnel research has led me to the Quad tree structure ( wikipedia article ).  I’ve got a brute force / naive implementation prototyped  @ here & here but as of 2011 March 9th it is not finished and needs some more work.

Basically Quad tree’s provides a super quick way for you to determine if there is any other objects in relative space to an entity.  Doing a quick lookup, if there’s nothing nearby then you can skip the bounding box checks and then the stupidly expensive perimeter intersection checks.

Full library is here and like most of my pet projects is heavily undocumented and completely absent of unit-testing.

Stellar simulator thingy

Inspired by this
IF YOU CAN SEE THIS, YOUR BROWSER SUCKS!





Source code @ Github here

So… this basically covers elliptical paths ( which I want to play with more ), a rendering chain I’m happy with, and a few others things. What isn’t exactly right: speed, planetary/stellar surface animation is missing, and I’d like to have a fly by mechanism that shifts the Y ratio progressively over time.

Deferreds for JQuery 1.5

Anyone familiar with async programming like Node.JS or Python’s twistd library will be familiar with deferreds. Its usually a simple nuisance to re-implement when needed, so it’s nice to hear that’s not an issue anymore with JQuery’s $.when & $.then methods

Really useful guide here

What does this mean?

Say you’ve got a compound action you want to complete. For example a user clicks on a leaf in a tree like directory
menu. Now you want to update both the menu to add any possible sub nodes of that leaf PLUS update a content panel and once its finished, maybe update the hash tag to the current page’s url.

   
  $.when( updateMenu(), updateContent() )
     .success( function(){
           console.log("Both menu & content panel have been updated!");
      })
     .fail( function(){
           console.log("Oh noes, we didn't finish... try again?");
      });

 

That’s pretty much the gist of deferreds in a nutshell. Furthermore it appears that the author of this fantastic addition to jQuery really grokked the concept of deferreds because you can chain one deferred result to multiple child deferred’s allowing for cascading events to fire in response to one event.

Python pydoc module

Python documentation here

Example

$python -m pydoc pydoc

Talk about eating your own dogfood! This is exactly like using the help() function in the python command line interpreter… except accessible from your shell prompt…. but wait!

It’ gets better! Not only does it make julian fries ( may not for any implementation ) but it’s got a few versatile little secrets

$ python -m pydoc
pydoc - the Python documentation tool

pydoc.py  ...
    Show text documentation on something.   may be the name of a
    Python keyword, topic, function, module, or package, or a dotted
    reference to a class or function within a module or module in a
    package.  If  contains a '/', it is used as the path to a
    Python source file to document. If name is 'keywords', 'topics',
    or 'modules', a listing of these things is displayed.

pydoc.py -k 
    Search for a keyword in the synopsis lines of all available modules.

pydoc.py -p 
    Start an HTTP server on the given port on the local machine.

pydoc.py -g
    Pop up a graphical interface for finding and serving documentation.

pydoc.py -w  ...
    Write out the HTML documentation for a module to a file in the current
    directory.  If  contains a '/', it is treated as a filename; if
    it names a directory, documentation is written for all the contents.

Now the graphical interface isn’t anything to write home about, but the -p option provides a no thrills web interface to
almost everything accessible to your python interpreter. This can make it slightly easier to troll through foreign modules
looking for undocumented sub modules and classes… or having an accessible reference doc for properly managed modules

Python urllib

Python documentation here

Unfortunately there is little or no documentation on the command line properties of urllib but it does recognize everything that urllib can handle. So
python -m urllib http://website.com will grab the specified url and print to std out

Note FTP works as well but you need to follow the pattern ftp://user:password@website.com if authentication is required

Python module dis

Python documentation here

Example

python -m dis myFile.py provides an interesting look into a python file’s guts
I could easily imagine this being part of some sort of static time inspect system where dis sits at the front and a parse
walks down the output lines, turning the data into a dependency and symbol graph. Unfortunately it doesn’t seem to provide anything more and is really just a test function most likely intended for unit-testing the python stdlib.

Python SimpleHTTPServer

When working on pure javascript applications ( canvas widgets & such ), I’ve found using the SimpleHTTPServer disgustingly useful as it serves the current working directly without much thrills.

Python documentation here

Usage

$ python -m SimpleHTTPServer 8081 0.0.0.0
Serving HTTP on 0.0.0.0 port 8081 ...

Note that it’s not necessary to set the 2nd argument to 0.0.0.0 if you want the service to listen on all routes. It normally will by default listen on everything… just habit for me to always append that.

Another useful part of this server is that it servers an apache directory style listing of all file’s present unless there is a valid index file like index.htm present.