Wednesday, January 30, 2008

Memories ... of Lego Aircraft Carriers

Over at Gizmondo, they are showing some of the best lego sets in history.

I'm quite proud to say, that they in fact have two of my favorites.




I spent may a good day, in PJ's playing with them in my grandma spare room in jamaica. She had a kingsize bed, which i used as underground airport, and the wardrobe that was the super secret submarine base. Not to mention the drawers with where the hills surrounding the valley, which had my custom built lego aircraft carrier, which could store a helicopter, a VSTOL aircraft, and a hovercraft, all technic size i might add! It also had two escape canoes, as well as an armory, and control tower, SAM launcher and ....

Ok, i remember it a little too vividly considering it's been 6 years since i last saw it, and a few more since i last really played with it. But it was a lot of fun, and my favorite toy of my childhood. Oh, and to add it could also carry my weight on the carriers deck, thanks to a well placed supporting beam that ran across the ship and tied the hull walls together! It was 2 feet long, and foot wide, and half a foot high.

Enough carrier talk for one night don't you think!

Quote of the Day
"I Guess to you Starbucks is like Dr. Phil"

Some people seek solace at Starbucks

Sunday, January 27, 2008

The gift that just keeps on giving

After my 14 hour stint yesterday, i'm back on the trail.

Today i've cooked up a Javascript shopping cart. In true fashion it's all OO, and shiny. However very unlike me, it's JS library agnostic! Yes, thats right, i wrote by very own 'getElementById' staements!. I've only provided methods for adding, removing, and getting the price of all the objects. There is also a method for updating a ordered or unordered list, with the items stored in the object.

Javascript (No Library required!)

//Basket Object
//Library agnostic
var BasketObj = function(){
this.items = new Array();
this.bindToElementId = null

//Add an object to the basket
this.addItem = function( pObj ){
retVal = false;
if( pObj.name.length > 1 ){
this.items.push( pObj );
console.log('Object added to basket');
retVal = true;
}
else{
console.log('Not a valid object');
}

return retVal;
}
//Remove the first matching item from the basket and return it
this.removeItem = function( pItemName ){
var retVal = null;

for(i=0; i < this.items.length; i++){

if( this.items[i].name == pItemName ){

console.log('Object removed from basket')
// reference the obj
retVal = this.items[i];
//dereference it
this.items[i] = null;
//exit the loop
break;
}

}

return retVal;
}

//Calculate the total basket value
this.total = function(){
var retVal = 0.00;

for(i=0; i < this.items.length; i++){
retVal += this.items[i].price;
}

return retVal;
}

//Updates the gui display of the object
this.updateDisplay = function(){
if( this.bindToElementId != null ){
//Empty the element first
document.getElementById( this.bindToElementId ).innerHTML = '';

//Sort the array before we print
//this.items.sort();

//Now proceed to fill it
for(i=0; i < this.items.length; i++){
document.getElementById( this.bindToElementId ).innerHTML += '<li>' + this.items[i].name + '</li>';
}
}
}
}


To use it, you must first create the object,


x = new BasketObj();


Once thats done you can set it up, the only thing that you really need to set, is the id name of the object you wish to have the results shown in. This is store in a variable called bindToElementId.

x.bindToElementId = 'basketList';


Now you can add your objects to it. Your objects can be as complex as you want, however they must have the following properties,
name: This is the display name for the object, and the name that will be used for internal lookups
price: This is the value that will be added to create your total,

You use the addItem() to add items to the object, and the removeItem( nameOfObject ) to remove items.

To update your list with the current objects you call updateDisplay. And to get the total value of all the objects you can call total().

One other thing to mention, is that i use console.log statements, so be aware of those, and also i check for the name attribute before adding objects to the internal array, so don't try and add them, and prototype the method to your object later on.

Anyways, this object features in my DFTI coursework, which i've been streaming though over this past weekend, i've now implemented the Drag and drop shopping and it looks a little something like this...



I still have to do the admin page, and stock control logic, however imagine this could be done in a day or so.

When it rains it php's

Ever wanted to convert a camel case string into something more user friendly?

Introducing the super dupa know it all function, should be good for PHP 4+

PHP

/*
Make a camel case string user friendly ^_^
*/
function implodeCamelCase( $pStr, $delimiter = ' '){

$strArr = str_split($pStr);
$retArr = array();

foreach( $strArr as $val ){

if( ord($val) <= 90 ){
array_push($retArr, ' ');
}

//add to return array
array_push($retArr, $val);
}

//explictly destroy array
$strArr = null;

return mb_convert_case(implode('',$retArr),MB_CASE_TITLE);
}


It's a bit rough around the edges, anything thats not a lower case character or anything else with a decimal ascii number over 90, will have a space inserted before it, of course thats easy enough to tweak.

Saturday, January 26, 2008

Json Encoding

For a enterprising young developer like myself, i don't take advantage of json enough. So since i'm in the mix at the moment, with my DFTI course work, i thought now would be a good time.

Unfortunately the json_encode() function that i had seen in the PHP documentation, is only in the CVS distributions at the moment (v 5.1.2), so i came up with the below.

PHP

/*
This function converts an array to a Json string.
*/
function jsonEncode( $pArr ){
$arr = Array('{');

foreach( $pArr as $val ){

if( is_numeric( $val) ){
array_push($arr, $val );
}else{
array_push($arr, '"');
array_push($arr, $val);
array_push($arr, '"');
}
array_push($arr,',');
}
//Remove trailing comma
array_pop($arr);

return implode('',$arr);
}

/*
This function converts an associative array to a Json string.
*/
function jsonEncodeAssoc( $pArr ){
$arr = Array('{');

foreach( $pArr as $key => $val){
array_push($arr, '"');
array_push($arr, $key);
array_push($arr, '"');
array_push($arr, ':');

if( is_numeric( $val ) ){
array_push($arr, $val);
}
else{
array_push($arr, '"');
array_push($arr, $val);
array_push($arr, '"');
}

array_push($arr, ',');
}

//Remove trailing comma
array_pop($arr);

array_push($arr,'}');

return implode('',$arr);
}


Both functions take either a regular array, or a Associative and converts it to a json string, which looks like ...


{"id":1,"name":"Ham And Pineapple","description":"<p>Fusce magna sem, gravida in, feugiat ac, molestie eget, wisi.</p>","categoryId":1,"hasNuts":0,"vegetarians":0,"imagePath":"ham-and-pineapple.gif","price":4.95}



The above is just some data from my database. It's a pizza ordering system. I plan to go all ajaxan with a Drag and drop shopping cart, as well as some other shiny stuff.

I haven't a clue what i'm going to do concerning javascript, i'm looking at mootools, mochikit, and of course jquery and maybe even yahoo ui. Might be a last minute thing.

Sunday, January 13, 2008

My Broadband got upgraded!

Or at least so it would appear

Happy posting :), and don't write anything too stupid!

I don't know about you, but this is the fastest torrent speed i've witnessed, ever. Speedtest.net put the connection speed at 6mb!

Wednesday, January 09, 2008

Happy New year, have a server for 08

Happy 2008.

I'm in the middle of finishing up my Object Orientated Application Assignment, and i ran across this piece of code in my repository.


import java.io.*;
import java.net.*;

public class ServerInstance {

private Socket Connection;
private BufferedOutputStream Outbound;
private InputStream Inbound;
private HTTPData RawHttpData;

private int listeningPort;

//ClassFlags
private boolean connectionEstablished = false;
private boolean instanceComplete = false;

public ServerInstance(){
//This one Sets all variables to defaults
listeningPort = Preferences.DEFAULTPORT;
}

/*public ServerInstance(Preferences){

}*/

public boolean run(){
ServerSocket ListenSocket;

boolean retBool = false;
boolean endLoop = false;
int readValue = -1024; // Set to extreme value to show that it is default;
int i = 0;

/*
* How the Server Will work
*
* 1. Get the Data from the browser / Read the Stream
* 2. Send Data off to extract the headers
* 3. While Data is being Processed Send data back to the client
* 4. Flag that server action is complete, and shutdown and clean up
*
*/
try{
ListeningSocket = new ServerSocket( listeningPort );

Connection = ListeningSocket.accept();

connectionEstablished = true;

//1. Get Data from Browser
Inbound = Connection.getInputStream();

Outbound = new BufferedOutputStream ( Connection.getOutputStream() ); //Place output in a Buffered Stream

//Write to both Objects simultainously
while( !endLoop ){
readValue = Inbound.read();

if(readValue != -1){
Outbound.write( readValue ); //Send data to the client
RawHttpData.write( readValue ); //Write data to a HTTPData Object
}
else{
endLoop = true;
}
i++;
}

Outbound.flush(); //Make sure all the data has been sent back to the browser
//Just while we code
System.out.println("Server: has RX/TX " + i + " Bytes of data");

//4. Clean up
Inbound.close();
Outbound.close();
Connection.close();

instanceComplete = true;
}
catch(IOException e){
System.out.println("<-- Server Error -->");
System.err.print( e );
}
catch(IllegalBlockingModeException e){
//I doubt this will come up, but refer to java documentation on serversocket.accept() in the event it does
System.out.println("<-- Server says no! -->");
System.err.print( e );
}
finally{
return retBool;
}
}

public boolean isConnected(){
return connectionEstablished;
}

public boolean isComplete(){
return instanceComplete;
}
}


Code is released under the GPL 2.0 License, go forth and improve (and credit).


This is a working server implementation in java, a relic from my isolation project,( Isolation was meant to act as a personal proxy, similar to how google gears works, however their wouldn't need to modification to the web app, as isolation was meant to pre-fetch the data, based on monitor the users actions/http requests.).

Anyway as you can imagine this was a big project, coupled with my second major data disaster, it didn't really ever see the light of day.

Couple of things to mention, the Preferences class was a data structure to store, ... well user preferences, and the class was meant to implement the runnable interface, so that you could operate multiple server instances.

I learnt a lot researching for it, and thanks to it i have a very good idea of how the HTTP protocol works, however i think it was a little too complex for someone at my current level, i should really stick to trying to reverse engineer front row, and learning lisp.

On the note of the reversing of front row, a plugin called sapphire was released last year. From what i can determine they have worked out how to beat apples protection scheme governing the loading of foreign NSbundles (Yeah, i know about them!). So when i finally get around to it, i'll (try to) reverse it as well.

Quote of the Day
"Rave for business"

I love Capitalism, don't you