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).
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.
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.
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!
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
$nwherenrepresents 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
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.
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.
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
appending and prepending elements
intro
with AJAX user interfaces becoming more and more popular, users are getting used to things happening in real time on websites. take, for example, leaving a comment on a blog post. clicking “post comment” can submit a form that your server language (php) can handle and then reload the page with the comment posted. however this makes the entire page reload, which can take up more time than necessary, not to mention server resources to rebuild the entire page’s content. enter, [intlink id="109" type="post"]XMLHttpRequest[/intlink] and a little AJAX fun….
scenario
let’s assume you already have your [intlink id="109" type="post"]XMLHttpRequest[/intlink] function written and that it sends information to a postComment() function that will add the comment to the blog post. once you gave gotten your responseXML from the request you want to add the comment to the list of existing comments in real time.
solution
create the div that contains the comments and make sure to give it a unique id:
<div id="comment_container">
<p>comment 1</p>
<p>comment 2</p>
</div>
then simply get the dom element of the container div so you can add the element from the responseXML:
var new_comment = request.responseXML;
var comments = document.getElementById("comment_container");
now you have to decide if you want to add the element to the top or the bottom of the list. if you are sorting the comments with the newest at the bottom, you want to append the new comment:
comments.appendChild(new_comment);
this will add the dom element to the end of the list, attaching it to the beginning is a little trickier. there is no prependChild() method in javascript. instead you will have to use the insertBefore() method:
comments.insertBefore(new_comment, comments.firstChild);
combine this with some cool graphic effects (like fading in the new comment) and you can start to create a really appealing interface for your users.
javascript
introduction
javascript is a scripting language widely used for client-side web development. it was the originating dialect of the ecmascript standard. it is a dynamic, weakly typed, prototype-based language with first-class functions. javascript was influenced by many languages and was designed to look like java, but be easier for non-programmers to work with.
although best known for its use in websites (as client-side javascript), javascript is also used to enable scripting access to objects embedded in other applications (see below).
javascript, despite the name, is essentially unrelated to the java programming language, although both have the common c syntax, and javascript copies many java names and naming conventions. the language’s name is the result of a co-marketing deal between netscape and sun, in exchange for netscape bundling sun’s java runtime with their then-dominant browser. the key design principles within javascript are inherited from the self and scheme programming languages.
“javascript” is a trademark of sun microsystems. it was used under license for technology invented and implemented by netscape communications and current entities such as the mozilla foundation.
history and naming
javascript was originally developed by brendan eich of netscape under the name mocha, which was later renamed to livescript, and finally to javascript. the change of name from livescript to javascript roughly coincided with netscape adding support for java technology in its netscape navigator web browser. javascript was first introduced and deployed in the netscape browser version 2.0b3 in december 1995. the naming has caused confusion, giving the impression that the language is a spin-off of java, and it has been characterized by many as a marketing ploy by netscape to give javascript the cachet of what was then the hot new web-programming language.
microsoft named its dialect of the language jscript to avoid trademark issues. jscript was first supported in internet explorer version 3.0, released in august 1996, and it included y2k-compliant date functions, unlike those based on java.util.date in javascript at the time. the dialects are perceived to be so similar that the terms “javascript” and “jscript” are often used interchangeably (including in this article). microsoft, however, notes dozens of ways in which jscript is not ecma compliant.
netscape submitted javascript to ecma international for standardization resulting in the standardized version named ecmascript.
main uses
the primary use of javascript is to write functions that are embedded in or included from html pages and interact with the document object model (dom) of the page. some simple examples of this usage are:
- opening or popping up a new window with programmatic control over the size, position, and attributes of the new window (i.e. whether the menus, toolbars, etc. are visible).
- validation of web form input values to make sure that they will be accepted before they are submitted to the server.
- changing images as the mouse cursor moves over them: this effect is often used to draw the user’s attention to important links displayed as graphical elements.
because javascript code can run locally in a user’s browser (rather than on a remote server) it can respond to user actions quickly, making an application feel more responsive. furthermore, javascript code can detect user actions which html alone cannot, such as individual keystrokes. applications such as gmail take advantage of this: much of the user-interface logic is written in javascript, and javascript dispatches requests for information (such as the content of an e-mail message) to the server. the wider trend of ajax programming similarly exploits this strength.
a javascript engine (also known as javascript interpreter or javascript implementation) is an interpreter that interprets javascript source code and executes the script accordingly. the first ever javascript engine was created by brendan eich at netscape communications corporation, for the netscape navigator web browser. the engine, code-named spidermonkey, is implemented in c. it has since been updated (in javascript 1.5) to conform to ecma-262 edition 3. the rhino engine, created primarily by norris boyd (also at netscape) is a javascript implementation in java. rhino, like spidermonkey, is ecma-262 edition 3 compliant.
the most common host environment for javascript is by far a web browser. web browsers typically use the public api to create “host objects” responsible for reflecting the dom into javascript. the web server is another common application of the engine. a javascript webserver would expose host objects representing an http request and response objects, which a javascript program could then manipulate to dynamically generate web pages.
things to consider
the dom interfaces for manipulating web pages are not part of the ecmascript standard, or of javascript itself. officially, they are defined by a separate standardization effort by the w3c; in practice, browser implementations differ from the standards and from each other, and not all browsers execute javascript.
to deal with these differences, javascript authors can attempt to write standards-compliant code which will also be executed correctly by most browsers; failing that, they can write code that checks for the presence of certain browser features and behaves differently if they are not available. in some cases, two browsers may both implement a feature but with different behavior, and authors may find it practical to detect what browser is running and change their script’s behavior to match. programmers may also use libraries or toolkits which take browser differences into account.
security
javascript and the dom provide the potential for malicious authors to deliver scripts to run on a client computer via the web. browser authors contain this risk using two restrictions. first, scripts run in a sandbox in which they can only perform web-related actions, not general-purpose programming tasks like creating files. second, scripts are constrained by the same origin policy: scripts from one web site do not have access to information such as usernames, passwords, or cookies sent to another site. most javascript-related security bugs are breaches of either the same origin policy or the sandbox.
one common javascript-related security problem is cross-site scripting, or xss, a violation of the same-origin policy. xss vulnerabilities occur when an attacker is able to cause a trusted web site, such as an online banking website, to include a malicious script in the webpage presented to a victim. the script in this example can then access the banking application with the privileges of the victim, potentially disclosing secret information or transferring money without the victim’s authorization.
xss vulnerabilities can also occur because of implementation mistakes by browser authors.
xss is related to cross-site request forgery or xsrf. in xsrf one website causes a victim’s browser to generate fraudulent requests to another site with the victim’s legitimate http cookies attached to the request.




