Jul 20, 2011

web based gantt charts

here’s a cool web tool for creating gantt charts. its got a hand full of features and it can export to a few various document types. there are levels of product use but the free level has a lot of the necessary features to get a decent gantt chart create (albeit with a brand watermark in the background).

http://www.viewpath.com/

Jul 11, 2011

hash tables

hash tables are a great way to sore associated lists of information and also maintain a very low retrieval time (O(1)). a hash table is basically an associative array where the keys can be anything (typically strings) that points to a value. lets say you have a list of people and their addresses. you might want to associate the people with there addresses so that when you look up “jesse mazur” you get “555-1212″. rather than having to traverse the entire array to find the value you simply query the hash table for the key “jesse mazur” and get the value “555-1212″ returned. an easy way to create this type of relationship in php is to simply use an array:

$hashTable  = array('my' => 'some data',
                         'hash' => 'some more data',
                         'table' => 'even more data');

retrieval from the hash table would be as simple as saying:

echo $hasTable['hash'];

which would display 'some more data' to the screen.

in javascript you would use a json object to do something every similar:

var hashTable = new Array();
hashTable['my'] = 'some data';
hashTable['hash'] = 'some more data';
hashTable['table'] = 'even more data';

and retrieval is as easy as:

document.write(hashTable.table);

which would display 'even more data' to the screen.

 

Jul 8, 2011

recursion

this is something that programmers deal with on a regular basis when faced with a problem were some set of tasks needs to be performed repeatedly on a set of data as well as that data’s subsets. many recursive functions can also be carried out with cunning use of loops, which is often better in the long run (as far as big-o-notation is concerned) but when the only way to do something (or the most efficient way) is to do it recursively, then writing a recursive function is the way to go. consider this: you have an array that contains either integers or other arrays, who contain integers or other arrays, and so on. you need to find the highest integer contained by the parent array, regardless of how deep the internal arrays may go. a loop would be a rather difficult way to achieve this considering you have no idea how many tiers to traverse. so recursion is a great way to do it. first write a function that just returns the highest value in the array (for the purposes of this article ill use php but this applies to almost all languages):

function highestVal ($array) {
    $curHigh = 0;
    if (is_array($array)) {
        foreach($array as $val) {
            if ($val > $curHigh) {
                $curHigh = $val;
            }
        }
    } else
        // return some error for incorrect data type
    }
    return $curHigh;
}

passing an array that contains only integers such as array(3,4,8,12,9,8,1) would return 12 in this case. but what if the array was array(3,2,8,9,4,array(12,3),1)? this function might return an error or at the very least not catch the 12 inside the internal array. so modifying the function to check if the $val is an array and recursively calling itself would then return the highest value of the inner array (and if that contained any inner arrays, they would also be assessed):

function highestVal ($array) {
    $curHigh = 0;
    if (is_array($array)) {
        foreach($array as $val) {
            if (is_array($val)) {
                $val = highestVal($val);
            }
            if ($val > $curHigh) {
                $curHigh = $val;
            }
        }
    } else {
        // return some error for incorrect data type
    }
    return $curHigh;
}

there you have it, a function that would return the highest value if an array containing any number of integers or arrays. recursion can have a high cost as far as resources are concerned but this function still maintainss a big-o value of O(n) because it only evaluates each member of each array one time.

Jul 7, 2011

javascript location based applications

mobile application development seems to be the new craze and everyone is getting in on it. with so many different platforms its difficult to decide which platform to code for. there are a few frameworks out there like Appcelerator and PhoneGap that enable you to write the application in JavaScript, HTML5 and CSS3 and then wrap the application in a ‘native’ shell to run on multiple platforms but you still need all the SDKs to do so. since all major phones have modern browsers you can create any web application using the 3 web languages instead. since geolocation seems to be the hip thing that all mobile apps have you need a way to make location based software. luckily the w3c has a new standard for doing so that is part of javascript and functions in most modern browsers:

navigator.geolocation

to make sure that the browser supports it wrapping the line in an if() statement will make sure that the application wont try to do something its incapable of doing. then once you know geolocation works, write your code:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        alert('You are at' + position.coords.latitude + ' x ' + position.coords.longitude);
    }
}

once you know the coordinates you can do all sorts of things: look up near by restaurants, get directions, find the closest gas station. now all you need to do is create a css that looks good on mobile devices and make the website itself the app. on an iphone its easy to save a website as a book mark on the home screen, so effectively you have created a location based application using only javascript, html5, and css3!

Jul 5, 2011

regular expressions

i had to work with regular expressions today and i realized i have never posed about them but i used them often. a regular expression is a way of matching patterns in a string. most programming languages have a way to work with them. in php the method i prefer to use is preg_match() and in javascript its match(). ill just show some very very basic regular expressions to describe how they work. first, a few of the basic special characters that i use rather often:

  • . – any character
  • ^ – when at the beginning of the expression it means the very first character in the expression, however when inside of a pair square brackets it denotes the NOT logical operator
  • $ – when at the end of the expression it means the end of the entire expression, otherwise it means an actual dollar sign
  • * – 0 or more of the preceding character
  • ? – 0 or 1 of the preceding character
  • {n} – n number of the preceding character
  • {n,m} – between n and m instances of the preceding character
  • | – OR logical operator
  • () – used to group things together, can also be used for back references as $n where n represents the n’th set of parenthesis (starting at 0)
  • \s – white space
  • \d – a digit
  • ‘-’ – a dash implies a range between the two characters on either site (they must match in type)
  • \ – this escapes the following character in the event that the character would otherwise be a reserved character in regular expressions

there are many more, in fact regular expressions can get so complex that some even consider it to be a pseudo-language of its own. in any result i’ll try to think of a situation where i can use at least a few of these characters and then write out the expression in plain English.

^[A-Z]([^.]\s)*hello?(\s[^.])*\.$

this would mean any grammatically correct sentence that begins with a capital letter followed by any number of characters and spaces that are not periods, followed by zero or one instance of the word ‘hello’, followed by any number of characters and spaces other than a period, and finally ending with a period

Jun 29, 2011

javascript obfuscation

with all the use of javascript and the various libraries that are now available, there are a lot of really great web applications coming out that use some pretty serious proprietary javascript code. unlike server side code, it can be rather difficult to protect your code base from other people since javascript runs in the browser. if you want to disable people from just downloading your code and running it you need to protect its source code some how. the best method i have used is to obfuscate the code so that its difficult to read. a real quick way to obfuscate is to simply minify (remove all white space), however, there are also unminifiers out there and many IDEs have code formatters built in that will beautify the code. i prefer to use a great tool that gives a number of options that will allow for further obfuscation:

JavaScript Packer by Dean Edwards

generally speaking it can remove all white space to minify the code (which is already a great idea anyway to keep the file size down) but there are also a couple of checkboxes that allow you to select two other options:

Base62 encode
Base62 encoding is just a conversion that will change the code from how it appears to a different representation of the same text in a 62 character scale. it is a two way conversion so it can be decoded, but its virtually impossible to read normally. checking this box will Base62 encode the javascript text so that the typical user cannot read it by just viewing the source. there’s also the added level of obscurity considering the reader will not to wither to Base62 or Base64 decode the string.

Shrink variables
this options converts all variable names to a single letter so that even if the user was able to decode the string, the still one have obvious variable names to read. think of how much more difficult it would be to figure out what var a = b + '  ' + c; means instead of var helloWord = hello + '  ' + world; for example.

so the reader would have to get the source code, then determine if its Base 62 or Base64, decode it, and unminify it and decipher what each variable represents before have any means of reverse engineering or stealing it. definitely a good place to start if you want to protect your javascript.

Jun 28, 2011

multithreading in php

ok… you got me… there is no such thing as actual multithreading in php. however, i have come up with a method that worked for me on a project where i had to write a web crawler and it the spider hasn’t failed yet. the basic idea is this: while php cannot multithread, your server certainly can so rather than try to jumo through a bunch of hoops to make php do what you want, just rely on the server to do the work.

the parent file
in order to multithread you must have a parent file that creates the threads (or children as i will refer to them for the remainder of this article). you will most likely have to account for the available resources and have the parent file check those resources to make sure that there is enough “room” for another child to be created, otherwise wait until there is “room.” another thing to pay attention to is the default max_execution_time in php. my method to handle both of these issues is to first set php’s max_execution_time to 0 (effectively turning it off) and then to store a running list of children in a database table to keep track of the count.

ini_set('max_execution_time', 0);
$maxThreadsAllowed = 50;
$activeThreads = 0;
$cyclesToRun = 250;
$count = 0;
$keepRunning = TRUE;
while ($keepRunning) {
    if ($activeThreads <= $maxThreadsAllowed) {
        exec('php -f childThread.php >> threadlog.txt &');
        $count++;
    }
    $sql = "'SELECT count(*) FROM threads WHERE completed = 0';
    $result = mysql_query($sql);
    $activeThreads = mysql_result($result, 0);
    if ($activeThreads == 0 && $count &;t= $cyclesToRun) {
        $break;
    }
}

initially there are no threads so i set $activeThreads to 0. for the purposes of this article i am assuming that the system will remain stable as long as there are no more than 50 threads running. the first time through the loop will always run since $keepRunning is initially TRUE. as long as there aren’t too many active children, a new child will be created each pass, otherwise it will be skipped and the count will be checked again. once the $activeCount hits 0 and the $count matches the $cyclesToRun the loop will break. you might ask yourself how the $activeCount will ever be more than 0 based on this code, the answer is in the child file.

the child file
the child file is where all the actual actions that are to be performed take place. in this example it will simply say 'Hello World.' the key here is to insert a new row into the threads table right away so that when the parent checks the $activeCount, there will be something there. then do the work. finally, update the row and set completed to 1 so that the thread is not included in the $activeCount.

$pid = getmypid();
$sql = 'INSERT INTO threads (pid, completed) VALUES (' . $pid . ', 0)';
$result = mysql_query($sql);
echo 'Hello World';
$sql = 'UPDATE threads SET completed = 1 WHERE pid = ' . $pid;
$result = mysql_query($sql);

thats it, albeit in a very basic way. the threads table tracks all the currently running children and the parent checks the table to ensure that there aren’t too many threads running. once all the threads are completed and the total number of cycles has been fulfilled the loop will break and the parent will stop.

assumptions
i am assuming that you already have a connection to a database and that whichever user php is running as has the proper permissions necessary to run exec() commands, user ini_set() and write to a threadlog.txt file

Jun 27, 2011

ascii star wars

just found this while trolling around. its a new hope completely done in ascii art. geek gold!

watch it on the web here

or open up a terminal/command line window and type telnet towel.blinkenlights.nl

Jun 27, 2011

object oriented javascript

intro
i recently had to write a firefox extension, and since extensions are written in javascript, and i am an object oriented programmer, i decided to write the extensions using object oriented javascript. there are a number of ways to achieve this and i will be discussing two of those options: using prototypes and using json. both have their pros and cons, personally i prefer json so i’ll discuss that one first.

json
writing a class in json is rather easy and looks similar to how it would be written in any other languages. first the class must be declared, then its attributes are listed, followed by its methods. here is an example:

var MyClass = {
    str: null,

    setStr: function() {
        this.str = arguments[0];
    },

    writeStr: function() {
         document.write(this.str);
    }

}

to use this class you would instanciate an object of the type MyClass and then act on that object by using the methods available withint he object:

var Obj = new MyClass;
Obj.setStr("Hello World");
Obj.writeStr();

based on the code above that would set the attribute str to "Hello World" and then write it to the document. the one setback to using json is that there is no clearly defined constructor or destructor the way most object oriented languages have. the only way to have  either us to write them and then specifically call them them. if MyClass had a method called __construtor, for example, i would want to call Obj.__constructor immediately upon creating it, since that method would not auto execute. this leads me to the second way to write object oriented javascript, using prototypes.

prototypes
when using prototypes, the syntax is a little different and the final document does not look like a class the way it would in other object oriented languages. instead, the initial variable is set up as a method and then all other methods are set up as prototypes to that original variable. this results in the initial method acting as a sort of constructor for the class since it executes when instanciated. here is an example:

function MyClass() {
    this.str = null;

    if (document.location == "http://www.jessemazur.com") {
        this.str = "Welcome to Jesse Mazur's Website";
    }
};

MyClass.prototype.setStr = function() {
     this.str = arguments[0];
};

MyClass.prototype.writeStr = function() {
    document.write(this.str);
};

the class would be instanciated the same way as the json class, and used the same way. the difference is that the if statement inside the first method would execute as soon as the object was created. so it MyClass.setStr was never called, and you happend to be on my website (which you are!) the str attribute would be set to "Welcome to Jesse Mazur's Website".

i happen to thing the first example is nicer looking and easier to read, but lacks the constructor method that you might be used to. either way, neither of them have desctuctors. one other subtle difference to make note of is the syntax for separating the pieces. all attributes and methods in json are separated by commas, whereas prototypes end with a semicolon.

Jun 2, 2010

variable variables in php and javascript

intro
ok, so the title of this one is a little weird but it is a very common thing that i run into, and i find myself looking this up each time and realized i should just add it to the blog. first off, what is a variable variable. basically its a variable whose name is assigned via a variable. so lets say you have a variable ($txt, or var txt) that you assign a value of “myVar” to. echo/alerting the txt variable will display myVar to the screen. well what if you want to use that word as the name of a variable and assign it a value of “test”. you could simply use $myVar = "test"; or var myVar = "test"; right? simple! but, if youve received a variable (say from some other method/function) containing a word, and you want to use that word as a new variable name. you need a way to declare the variable with the name stored inside the received variable. luckily both php and javascriptp have a way to do this.

php
in php you just use two dollar signs ($). so if you have a variable $a and inside of $a is a string “myVar,” then $$a = "hello"; would be the same thing as using $myVar = "hello";. to reference it later, echo $a; would print “myVar” to the screen and echo ${$a}; or echo $myVar; would print “hello” to the screen.

javascript
in javascript its a little more difficult but certainly possible. lets use the exact same scenario but switch to javascript syntax. to assign the string inside var a to a var myVar you would use window[a] = "hello"; referencing it later, alert(a); would yield an alert box containing “myVar” and alert(myVar); or alert(window[a]); would yield an alert box with “hello” inside.

conclusion
you may not have ever been faced with a situation where youve needed to do this, but for those of you who have and couldnt find the results, youre welcome! im faced with this right now, and knowing i can do this is certainly making my life much easier

Pages:1234»