## Programming

### JavaScript: Why does parseInt("09") show the value of 0?

That's because "09" is an invalid number, in octal.

The parseInt() funciton acutally has 2 arguments that most people are not aware of, first is the string to parse and then a radix (which is optional). The radix value allows you to convert a binary (base 2), hexadecimal (base 16) or other base string to a decimal integer.

Example: parseInt("FF", 16); returns 255

The problem is that if you leave the radix argument off the function doesn't necessarily assume you want a decimal (base 10) conversion. Instead it checks the input string (the first argument) and if it starts with "0x" it assumes it's a hexadecimal value. If it starts with "0" - not followed by an "x" - it takes it as an octal value. This follows the JavaScript convention for numeric constants.

If you code

var x = 0x18;

it will display 24 which is the decimal equivalent of the hex number "18". Likewise,

var x = 014;

displays 12 which is the decimal value of the octal number "14".

Resource: FAQTs

Hexadecimal uses the numbers 0 to 9 and the letters A to F, 16 in all. You would normally see hexadecimal values used for colors (Orange: #FF9C00, White: #FFFFFF, or Red: #FF0000). Octal is base 8, so only the numbers 0-7 are valid. Hence, "09" is not a valid octal number and the function returns 0. Just as it would for "abc" in decimal ... it's not a valid number.

To avoid this, get into the habit of always adding the second argument, in this case ...

parseInt("09", 10);

returns 9 (decimal), as desired.

Resources
* FAQTs

### Need to test your site in IE6?

If you're a web developer (like me) and need to test a website in good old Internet Explorer 6 but you have Windows Vista or you've upgraded your Internet Explorer to version 7. Then luck is on your side and Microsoft has been so kind to supply Virtual PC for free and an image of Windows XP with IE 6 for free.

All you need to do is download Virtual PC 2004, which is also free, and then download Internet Explorer 6 Testing VPC Image.

Most developers (like myself) will be ignoring Internet Explorer 6 once Internet Explorer 8 has been announced, so we won't have to go through the tedious issues of fixing Internet Explorer 6 JavaScript bugs for much longer (unless specifically requested by a client).

### Very Simple Regular Expressions (Starting with Numbers)

If you want to validate strings, text, or whatever it may be, validating with Regular Expression is an easy way to determine that the data is valid. Whether it's an application or a web-site, you can validate users' input to ensure it has met all requirements before continuing, or validate your own data.

` ^123\$ `

This small example checks whether the data is simply '123', anything else will fail. We use the '^' symbol to show where the beginning of the data is, and the '\$' symbol to show where the end of the data is.

` ^[0-9]\$ `

The example above will test the data to ensure it is a single number between 0 to 9. '0', '1', '2', '3', and '9' are examples of data that will pass the above regular expression. 'a', '10', and ' 1' are all examples of data that will fail.

So what if we wanted 2 numbers?

` ^([0-9]|[0-9][0-9])\$ `

The example above will match 0 to 9 or 00 to 99. The '|' symbol simply specifies 'or' so in affect we have [0-9] for 0 to 9 | [0-9][0-9] for 00 to 99. Because we are using the '|' symbol, we need to wrap brackets around our statement to show where the 'or' statement begins and where it ends.

Now lets work with time.

` ^(1[0-2]|(0?[1-9])):[0-5][0-9]\$ `

12 hour format is pretty damn simple now that you know the basics. The first part '1[0-2]' means 1 followed by 0 to 2 (for example 10, 11, 12), 'or' '(0*[1-9])' for 1 to 9 or 01 to 09. The '*' means whatever character before it is optional, so the '0' is optional but can only occur once if it was there.

So this will cover 1 to 9, 01 to 09, and 10, 11, 12. The ':' symbol is exactly that, and the last two parts '[0-5][0-9]' means 00 to 59. '1:15', '9:59', and '12:39' will all pass, but '00:38', '13:32', and '3:83' will all fail.

I'm on a quest to make the ultimate regular expression for date and time, but there's no use giving you the whole thing without first telling you how to get there. Keep an eye on my blog for more posts to come.

### Selecting an option with JavaScript

Normally you would select an option with a server-side script like PHP which is a lot faster and doesn't require the client's browser to do the work. But on the rare occasion where you need to set an option with JavaScript, here's a small script on how to do it.

` document.getElementById('select_box_id_here').value  = 'the value of the one you want selected'; `

This will work if you have constructed the page the proper way. On the odd chance you've used JavaScript to pull in a whole string of HTML then use the method below.

` var selectBox = document.getElementById('select_box_id_here');for(i=0; i<selectBox.options.length; i++) {	if(selectBox.options[i].value == a_value) {		selectBox.options[i].selected = true;		i = selectBox.options.length;	}} `

The above script simply loops through your select box and determines if the current option (in the loop) matches the value (a_value), if so then set the option to selected. The line "i = selectBox.options.length;" simply stops the 'for loop' from checking any further options.

The reason why you have to manually go through the select box yourself is because the DOM doesn't actually know the select box is on the page when you've just dumped a whole lot of HTML into the page with JavaScript. If it's possible to refresh the DOM then let me know, otherwise the above option is the solution to this problem.

### Preventing SPAM Bots Sending Mail Through Your Website (Non-Intrusive Way)

You can find a lot of ways to prevent spam from your site these days but I've really tested this method and it has been 100% effective (so far). It will stop automatic bots but a human will be able to work out how to get around it pretty easily (but when do humans have time to do that).

To begin with: this script is written in PHP but you can easily translate it.

`    session_start();   \$_SESSION["spam_prevention"] = '1'; `

First off, on the page with the form to email to you, declare a unique session variable on this page with any value you want. Why? So when the user submits this form to the script that sends the email, you know the user definitely came from the page with the form, and it's not a bot attacking your email script. So before your email script, test to see if \$_SESSION["spam_prevention"] exists.

`    <input type="text" name="spam_prevention"     style="display:none; visibility:hidden;" /> `

Another method is to put a text field on your form and hid it with CSS. 99.9% of the SPAM bots out there will disregard any CSS styles, and at the same time the SPAM bots will fill out every field within your form. So if this field is filled out, it's a good guess that it wasn't a human that filled it out.

This isn't bullet proof, but it works quite well and it doesn't require the user to fill out any spam prevention captcha fields etc.

Let me know how you go with this script if you try it.

### Simple Folder Creator with PHP

This script will detect if a folder exists as well as create the directories if the folder doesn't exist.

` 	mk_dir_recursive('the/directory/you/want/to/create');	function mk_dir_recursive(\$folder_name) {		if(file_exists(\$folder_name)) {			return;		}		\$folder_name = rtrim(\$folder_name, "/\\");		\$parent = dirname(\$folder_name);		if(!file_exists(\$parent)) {			mk_dir_recursive(\$parent);		}		mkdir(\$folder_name);	} `

### PHP Script: Create a Photo Gallery with Thumbnails and Resized Images

If you want to create an easy photo gallery, this script will allow you to resize images on the fly. It has a few pros and cons that you should be aware of before you start using it.

Pros
* Simple and easy to use - even I can use it.
* It resizes on the fly, so you can modify the code and it will affect all images you pass through it immediately. Great if you're short on storage on your web server, and doesn't require you to re-render all the images if you decide to change the size of the thumbnails.
* You can call this script for any image on your site, the image doesn't have to sit in an actual photo gallery.

Cons
* If you have a high traffic website, this isn't the best solution. You're best off resizing all your images when they're uploaded, not when they're are viewed. If you choose to use this script on a high traffic website, then at least cache the results so your web server isn't creating the same image 1000's of times over.
* This script only works with JPEGs, I'll create a new version (one day) to handle others.
* If you think of more cons, let me know.

* Rename the file to galleryviewer.php.

Usage
Create Thumbnail: galleryViewer.php?version=thumb&image=the/url/to/the/image.jpg
Create Resized Image: galleryViewer.php?version=full&image=the/url/to/the/image.jpg

```<img src="galleryViewer.php?version=thumb
&image=the/url/to/the/image.jpg" alt="Thumbnail" />```

Full Usage

The query string 'image' needs to be relative to the script.

### A note about modifying arrays during a loop.

Just a small tip for some people who might be modifying arrays during a loop, where the array is used in the condition of the loop. Just be a little bit careful on what you do with the array when looping through.

` var testArray = Array('1','2','3','4','5');for(var j=0; j<testArray.length; j++) {    alert(testArray[j]);    if(testArray[j] == '3') {        testArray.splice(j,1);    }} `

The above array loop is written in JavaScript, whether you're using JavaScript or not this is still something small to keep in mind. It will produce an alert of '1', then '2', then '3', and then '5'.

The length of the above array is 5, you start at position 0 and testArray[0] doesn't equal '3' so move on, same thing with position 1 (testArray[1] doesn't equal '3'). You then move onto position 2 where testArray[2] does equal '3', so we splice the array at position 2 which removes testArray[2] from the array, making the rest of the array drop down a position.

j still equals 2, so when it loops through again, j will equal 3. When it looks at what position 3 equals (testArray[3]) it will now be '5' as the array's position dropped down by one from the splice.

So we missed out on alerting '4' after going through that loop and you might be doing something important with the loop rather then simply alerting the values, there is 2 ways to get around this. One, put the 'something important' function after the loop in its own separate array. Or two, even easier, if the 'if condition' is true and you modified the array, simply affect the value of j so that the next loop through will be correct (like below).

` var testArray = Array('1','2','3','4','5');for(var j=0; j<testArray.length; j++) {    alert(testArray[j]);    if(testArray[j] == '3') {        testArray.splice(j,1);        j--;    }} `

### Using TinyMCE with AJAX

What is TinyMCE?
TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under LGPL by Moxiecode Systems AB. It has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances. TinyMCE is very easy to integrate into other Content Management Systems. Please visit their website for more details.

``` tinyMCE.init({ //settings go here });
```

Starting TinyMCE

``` tinyMCE.triggerSave(false,true);
tiny_mce_editor = tinyMCE.get('your_textarea_name');
var newData = tiny_mce_editor.getContent();
tinyMCE.execCommand( 'mceRemoveControl', false, 'your_textarea_name' );
```

Getting the Textarea Text and Closing TinyMCE
The new data that the user would enter into TinyMCE is now stored in the variable newData.

You need to specify a trigger save like this for 2 reasons:-
* You can't simply get content from your textarea once TinyMCE has taken over it, as the text in the textarea isn't actually stored in that field name you know.
* You need to remove the control properly so that TinyMCE doesn't make another instance of the same textarea, or otherwise you will run into issues.

### Common Programming Mistake: Working with dates and times.

This is an issue I see every so often, particularly with calendar scripts or anything that works with dates and times. When you store your timestamp or date-time in a database and do a search between 2 values, most scripts leave out something very crucial.

Lets us the following data as an example.

```Row | Start of Event         | End of Event
---------------------------------------------------------
1   | 15/05/2008 12:00:00    | 15/05/2008 17:30:00
2   | 24/05/2008 09:00:00    | 24/05/2008 17:30:00
```

If we perform the following search, we will only get the first row (15/05/2008) and not the second row (24/05/2008).

```WHERE `Start of Event` >= '15/05/2008'
AND `End of Event` < = '24/05/2008`
```

The reason is simple and most people won't realise this issue at first but will eventually find the issue once they have debugged their application to bits. When you perform a search between timestamps or date-time values using dates only, you are in fact doing a search between the dates and midnight as the default time value.

For example the above will in fact be searching for:

```WHERE `Start of Event` >= '15/05/2008 00:00:00'
AND `End of Event` < = '24/05/2008 00:00:00`
```

Because the second event "24/05/2008 09:00:00" starts after the "24/05/2008 00:00:00" it won't be included in the results. It's a simple mistake and very easy one to make.

There are many ways to get around it, the most simple way is to get the last date eg; "24/05/2008" add one day, and minus one second. So you end up with "24/05/2008 23:59:59".

Credit for this conversation: monk-ee

### Free Microsoft Silverlight Video Tutorials

In a collaboration between Microsoft and Lynda.com, whether you're a developer or a designer you can get a head start on how to create Microsoft Silverlight applications.

Check out the Silverlight Video Tutorials and don't forget to show me what you've made.

The Google AJAX Libraries API has been created to make AJAX applications that use popular frameworks such as Prototype, Script.aculo.us, jQuery, Dojo, and MooTools faster and easier for developers and the end users.

Whenever a user goes to a AJAX site, they would normally have to download one of the libraries listed above again, and again, and again for each AJAX site they go to. The same file, over, and over, and over again. What a waste of time and speed.

So Google have developed a service for developers to reference these popular AJAX libraries from the Google servers. They have each version of the libraries (incase you want to stick to an older version), and many other benefits such as:-
* Caching can be done correctly, and once, by us... and developers have to do nothing
* Gzip works
* We can serve minified versions
* The files are hosted by Google which has a distributed CDN at various points around the world, so the files are "close" to the user
* The servers are fast
* By using the same URLs, if a critical mass of applications use the Google infrastructure, when someone comes to your application the file may already be loaded!
* A subtle performance (and security) issue revolves around the headers that you send up and down. Since you are using a special domain (NOTE: not google.com!), no cookies or other verbose headers will be sent up, saving precious bytes.

So a message to everyone who has created AJAX applications, to help yourself and the end users, change your references to Google's AJAX Libraries API. For more information check out ajaxian and the Google AJAX Libraries API???????? ????? ???????? and documentation.

### PHP MySQL Handler

User Level: Beginner to Intermediate

` < ?php  class MySQLHandler {     var \$mysql_host;     var \$mysql_username;     var \$mysql_password;     var \$mysql_marking_database;     var \$link;     var \$select_db;      function MySQLHandler(\$database_name) {        \$this->mysql_host = "INSERT_HOST_HERE";        \$this->mysql_username = "INSERT_USERNAME_HERE";        \$this->mysql_password = "INSERT_PASSWORD_HERE";        \$this->mysql_marking_database = \$database_name;     }      function open_mysql_link() {        \$this->link = mysql_connect(\$this->mysql_host,            \$this->mysql_username, \$this->mysql_password);        \$this->select_db = mysql_select_db(           \$this->mysql_marking_database, \$this->link);        return \$this->link;     }      function close_mysql_link() {        mysql_close(\$this->link);     }  }?> `

The above PHP script (mysql_handler.php) can be used to connect to your MySQL database with PHP.

` < ?php   include('classes/mysql_handler.php');   \$mysql = new MySQLHandler("database_name");?> `

The include line will allow you to make references to the class, the 2nd line will allow you to initiate the class with a database name.

`    \$mysql_link = \$mysql->open_mysql_link(); `

Then when you need a link for your MySQL functions, all you need to do is specify the above script and you're connected.

You may want to further secure this file by placing your host, username, and password details elsewhere.

### A common security mistake

This is one of the most common mistakes developers (of any language) make so I thought I should let you know why you shouldn't use this method.

The Scenario:
You have a page on your site and you don't want people to simply link to this page unless they have clicked on a link from your own site. Lets say your page is called 'page2.php' and it's located at 'www.your-site.com/page2.php.'

When the user enters the 'page2.php' page you can easily determine which page they came from, in PHP you can use the \$_SERVER['HTTP_REFERER'] function to determine the referring page. With this function you would check that it contains www.your-site.com in the value.

For what ever reason why you might want to check the referring address to your page, checking the referral address against your own domain name isn't bullet-proof.

Why? The referral address is set by the user's agent (their Internet browser), some browsers have the option for you to edit this value and some browsers don't even set this at all.

There are many solutions to this scenario, but I would recommend using sessions where you can set the a session variable on 'page1.php' which contains the link to 'page2.php.' When the user enters the 'page2.php' page, you can then check to see if that variable has been set, if it hasn't then the user must have come from a different location.

It's a little bit more of a setup, but it's secure.

### What’s Your CSS Skill Level

Want to know how you rate with your CSS Skills, follow the skill level checklist below to see how you rate.

* Iâ€™ve heard of CSS, it is used in web design.
* I have poked around in CSS files making small changes like changing colors and removing underlines from links.

* I understand that the purpose of CSS is keeping design and content separate, to the highest extent that is possible.
* I have made extensive modifications to a CSS template.
* I have used a WYSIWYG editor to create CSS web page.
* I have a basic understanding of CSS layout techniques.

* I have designed a reasonably complex website from scratch using only CSS for layout.
* I have a solid understanding of the structure of CSS, the CSS box model, and CSS positioning.
* I understand how to use float and deal with itâ€™s quirks.
* I have a basic understanding that different browsers render some CSS differently and that needs to be accounted for and tested.
* I have a growing collection of CSS resources to draw from.
* I do not use tables for layout whatsoever anymore. I understand that tables are for tabular data, not page layout.

* I have designed and coded a large number of CSS web sites. I can convert a design from any format into a CSS layout: Photoshop, Illustrator, napkin drawings, etc.
* I am completely comfortable writing and editing CSS by hand.
* I have a strong understanding of the cascading part of CSS. Particularly how some some CSS properties do, some donâ€™t, and some depend on how the value is declared.
* I have a solid understanding of cross-browser CSS. I know how to use browser specific CSS statements and delclare browser specific stylesheets.
* I know and have tried some CSS hacks and understand the advantages and disadvantages of using them.
* I have a strong understanding of the different sizing values available in CSS (e.g. em, px, %, pt, â€œsmallâ€, etc.) and in what situations each make the most sense.
* I can quickly troubleshoot and solve CSS problems.
* I have a great collection of tools and resources at my disposal for inspiration, debugging, or reference.

* I feel like I could tackle any design idea with CSS.
* I can do pixel-perfect cross-browser conversions of designs into CSS websites.
* I can visualize markup structure easily, just by looking at a design.
* I have utilized additional web technologies to expand the possibilities and break through the limitations of CSS.
* I have my own CSS framework I use, complete with my own customized CSS reset.
* I have a strong understanding of advanced CSS like pseudo classes, pseudo elements, and attribute selectors.
* I keep up to date on browser support and development progress.

* I am involved with the future of CSS specifications or support.
* I am a CSS Celebrity.
* Iâ€™ve written books, given seminars, taught classes, knew CSS since she was a little girl, etc.
* I donâ€™t need to do testing, I just know.

Skill level ratings taken from CSS Tricks.