Its My Space

Cooooooooooool

Archive for January, 2009

Three Things In Life

Posted by Ramkumar on January 30, 2009

Three things in life that,once gone, never come back:
Time, Words & Opportunity

Three things in life that may never be lost:
Peace, Hope & Honesty.

Three things in life that are most valuable:
Love, Self-confidence & Friends

Three things in life that are never certain:
Dreams, Success & Fortune

Three things that make a man:
Hard work, Sincerity & Commitment

Three things in life that can destroy a man:
Wine, Pride & Anger

Posted in Cute Wordings | Tagged: | Leave a Comment »

Using Cookies

Posted by Ramkumar on January 30, 2009

Using Cookies with JavaScript
The document.cookie property is a string that contains all the names and values of Navigator cookies. You can use this property to work with cookies in JavaScript. Here are some basic things you can do with cookies:
• Set a cookie value, optionally specifying an expiration date.
• Get a cookie value, given the cookie name.
It is convenient to define functions to perform these tasks. Here, for example, is a function that sets cookie values and expiration:
// Sets cookie values. Expiration date is optional
//

function setCookie(name, value, expire) {
document.cookie = name + “=” + escape(value)
+ ((expire == null) ? “” : (“; expires=” + expire.toGMTString()))
}
Notice the use of escape to encode special characters (semicolons, commas, spaces) in the value string. This function assumes that cookie names do not have any special characters. The following function returns a cookie value, given the name of the cookie:
function getCookie(Name) {
var search = Name + “=”
if (document.cookie.length > 0) { // if there are any cookies
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(“;”, offset)
// set index of end of cookie value
if (end == -1)
end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
Notice the use of unescape to decode special characters in the cookie value.

Using Cookies: an Example
Using the cookie functions defined in the previous section, you can create a simple page users can fill in to “register” when they visit your page. If they return to your page within a year, they will see a personal greeting. You need to define one additional function in the HEAD of the document. This function, register, creates a cookie with the name TheCoolJavaScriptPage and the value passed to it as an argument.
function register(name) {
var today = new Date()
var expires = new Date()
expires.setTime(today.getTime() + 1000*60*60*24*365)
setCookie(“TheCoolJavaScriptPage”, name, expires)
}
The BODY of the document uses getCookie (defined in the previous section) to check whether the cookie for TheCoolJavaScriptPage exists and displays a greeting if it does. Then there is a form that calls register to add a cookie. The onClick event handler also calls history.go(0) to redraw the page.
<BODY>
<H1>Register Your Name with the Cookie-Meister</H1>
<P>
<SCRIPT>
var yourname = getCookie(“TheCoolJavaScriptPage”)
if (yourname != null)
document.write(“<P>Welcome Back, “, yourname)
else
document.write(“<P>You haven’t been here in the last year…”)
</SCRIPT>
<P> Enter your name. When you return to this page within a year, you will be greeted with a personalized greeting.
<BR>
<FORM onSubmit=”return false”>
Enter your name: <INPUT TYPE=”text” NAME=”username” SIZE= 10><BR>
<INPUT TYPE=”button” value=”Register”
onClick=”register(this.form.username.value); history.go(0)”>
</FORM>

Posted in Javascript | Tagged: | Leave a Comment »

Using the Status Bar

Posted by Ramkumar on January 30, 2009

You can use two window properties, status and defaultStatus, to display messages in the Navigator status bar at the bottom of the window. Navigator normally uses the status bar to display such messages as “Contacting Host…” and “Document: Done.” The defaultStatus message appears when nothing else is in the status bar. The status property displays a transient message in the status bar, such as when the user moves the mouse pointer over a link. You can set these properties to display custom messages. For example, to display a custom message after the document has finished loading, simply set defaultStatus. For example,
defaultStatus = “Some rise, some fall, some climb…to get to Terrapin”
Creating Hints with onMouseOver and onMouseOut
By default, when you move the mouse pointer over a hyperlink, the status bar displays the destination URL of the link. You can set status in the onMouseOut and onMouseOver event handlers of a hyperlink or image area to display hints in the status bar instead. The event handler must return true to set status. For example,
<A HREF=”contents.html”
onMouseOver=”window.status=’Click to display contents’;return true”>
Contents
</A>

Posted in Javascript | Tagged: | Leave a Comment »

Embedding JavaScript in HTML

Posted by Ramkumar on January 30, 2009

You can embed JavaScript in an HTML document as statements and functions within a <SCRIPT> tag, by specifying a file as the JavaScript source, by specifying a JavaScript expression as the value of an HTML attribute, or as event handlers within certain other HTML tags (primarily form elements). This chapter contains the following sections:
• Using the SCRIPT Tag
• Specifying a File of JavaScript Code
• Using JavaScript Expressions as HTML Attribute Values
• Using Quotation Marks
• Specifying Alternate Content with the NOSCRIPT Tag

Using the SCRIPT Tag
The <SCRIPT> tag is an extension to HTML that can enclose any number of JavaScript statements as shown here:
<SCRIPT>
JavaScript statements…
</SCRIPT>
A document can have multiple <SCRIPT> tags, and each can enclose any number of JavaScript statements.
Specifying the JavaScript Version
Each version of Navigator supports a different version of JavaScript. To ensure that users of various versions of Navigator avoid problems when viewing pages that use JavaScript, use the LANGUAGE attribute of the <SCRIPT> tag to specify the version of JavaScript with which a script complies. For example, to use JavaScript 1.2 syntax, you specify the following:
<SCRIPT LANGUAGE=”JavaScript1.2″>
Using the LANGUAGE tag attribute, you can write scripts compliant with earlier versions of Navigator. You can write different scripts for the different versions of the browser. If the specific browser does not support the specified JavaScript version, the code is ignored. If you do not specify a LANGUAGE attribute, the default behavior depends on the Navigator version. The following table lists the <SCRIPT> tags supported by different Netscape versions.

Navigator ignores code within <SCRIPT> tags that specify an unsupported version. For example, Navigator 3.0 does not support JavaScript 1.2, so if a user runs a JavaScript 1.2 script in Navigator 3.0, the script is ignored.
Example 1. This example shows how to define functions three times, once for JavaScript 1.0, once using JavaScript 1.1 features, and a third time using JavaScript 1.2 features.
<SCRIPT LANGUAGE=”JavaScript”>
// Define 1.0-compatible functions such as doClick() here
</SCRIPT>
<SCRIPT LANGUAGE=”JavaScript1.1″>
// Redefine those functions using 1.1 features
// Also define 1.1-only functions
</SCRIPT>
<SCRIPT LANGUAGE=”JavaScript1.2″>
// Redefine those functions using 1.2 features
// Also define 1.2-only functions
</SCRIPT>
<FORM …>
<INPUT TYPE=”button” onClick=”doClick(this)” …>

</FORM>
Example 2. This example shows how to use two separate versions of a JavaScript document, one for JavaScript 1.1 and one for JavaScript 1.2. The default document that loads is for JavaScript 1.1. If the user is running Navigator 4.0, the replace method replaces the page.
<SCRIPT LANGUAGE=”JavaScript1.2″>
// Replace this page in session history with the 1.2 version
location.replace(“js1.2/mypage.html”);
</SCRIPT>
[1.1-compatible page continues here...]
Example 3. This example shows how to test the navigator.userAgent property to determine which version of Navigator 4.0 is running. The code then conditionally executes 1.1 and 1.2 features.
<SCRIPT LANGUAGE=”JavaScript”>
if (navigator.userAgent.indexOf(“4.0″) != -1)
jsVersion = “1.2″;
else if (navigator.userAgent.indexOf(“3.0″) != -1)
jsVersion = “1.1″;
else
jsVersion = “1.0″;
</SCRIPT>
[hereafter, test jsVersion before use of any 1.1 or 1.2 extensions]

Hiding Scripts Within Comment Tags
Only Navigator versions 2.0 and later recognize JavaScript. To ensure that other browsers ignore JavaScript code, place the entire script within HTML comment tags, and precede the ending comment tag with a double-slash (//) that indicates a JavaScript single-line comment:
<SCRIPT>
<!– Begin to hide script contents from old browsers.
JavaScript statements…
// End the hiding here. –>
</SCRIPT>
Since browsers typically ignore unknown tags, non-JavaScript-capable browsers will ignore the beginning and ending SCRIPT tags. All the script statements in between are enclosed in an HTML comment, so they are ignored too. Navigator properly interprets the SCRIPT tags and ignores the line in the script beginning with the double-slash (//). Although you are not required to use this technique, it is considered good etiquette so that your pages do not generate unformatted script statements for those not using Navigator 2.0 or later.
NOTE: For simplicity, some of the examples in this book do not hide scripts.

Example: a First Script
Hello, net!
That’s all, folks.
Notice that there is no difference in appearance between the first line, generated with JavaScript, and the second line, generated with plain HTML.

Specifying a File of JavaScript Code

The SRC attribute of the <SCRIPT> tag lets you specify a file as the JavaScript source (rather than embedding the JavaScript in the HTML). For example:
<SCRIPT SRC=”common.js”>
</SCRIPT>
This attribute is especially useful for sharing functions among many different pages. The closing </SCRIPT> tag is required. JavaScript statements within a <SCRIPT> tag with a SRC attribute are ignored except by browsers that do not support the SRC attribute, such as Navigator 2.

URLs the SRC Attribute Can Specify
The SRC attribute can specify any URL, relative or absolute. For example:
<SCRIPT SRC=”http://home.netscape.com/functions/jsfuncs.js”>
If you load a document with any URL other than a file: URL, and that document itself contains a <SCRIPT SRC=”…”> tag, the internal SRC attribute cannot refer to another file: URL.

Requirements for Files Specified by the SRC Attribute

External JavaScript files cannot contain any HTML tags: they must contain only JavaScript statements and function definitions. External JavaScript files should have the file name suffix .js, and the server must map the .js suffix to the MIME type application/x-javascript, which the server sends back in the HTTP header. To map the suffix to the MIME type, add the following line to the mime.types file in the server’s config directory, and then restart the server.
type=application/x-javascript exts=js
If the server does not map the .js suffix to the application/x-javascript MIME type, Navigator improperly loads the JavaScript file specified by the SRC attribute.

Using JavaScript Expressions as HTML Attribute Values
Using JavaScript entities, you can specify a JavaScript expression as the value of an HTML attribute. Entity values are evaluated dynamically. This allows you to create more flexible HTML constructs, because the attributes of one HTML element can depend on information about elements placed previously on the page. You may already be familiar with HTML character entities by which you can define characters with special numerical codes or names by preceding the name with an ampersand (&) and terminating it with a semicolon (;). For example, you can include a greater-than symbol (>) with the character entity &GT; and a less-than symbol (<) with &LT;. JavaScript entities also start with an ampersand (&) and end with a semicolon (;). Instead of a name or number, you use a JavaScript expression enclosed in curly braces {}. You can use JavaScript entities only where an HTML attribute value would normally go. For example, suppose you define a variable barWidth. You could create a horizontal rule with the specified percentage width as follows:
<HR WIDTH=”&{barWidth};%” ALIGN=”LEFT”>
So, for example, if barWidth were 50, this statement would create the display shown in the following figure.

As with other HTML, after layout has occurred, the display of a page can change only if you reload the page. Unlike regular entities which can appear anywhere in the HTML text flow, JavaScript entities are interpreted only on the right-hand side of HTML attribute name/value pairs. For example, if you have this statement:
<H4>&{myTitle};</H4>
It displays the string myTitle rather than the value of the variable myTitle

Using Quotation Marks
Whenever you want to indicate a quoted string inside a string literal, use single quotation marks (‘) to delimit the string literal. This allows the script to distinguish the literal inside the string. In the following example, the function bar contains the literal “left” within a double-quoted attribute value:
function bar(widthPct) {
document.write(“<HR ALIGN=’left’ WIDTH=” + widthPct + “%>”)
}
Here’s another example:
<INPUT TYPE=”button” VALUE=”Press Me” onClick=”myfunc(‘astring’)”>

Specifying Alternate Content with the NOSCRIPT Tag
Use the <NOSCRIPT> tag to specify alternate content for browsers that do not support JavaScript. HTML enclosed within a <NOSCRIPT> tag is displayed by browsers that do not support JavaScript; code within the tag is ignored by Navigator. Note however, that if the user has disabled JavaScript from the Advanced tab of the Preferences dialog, Navigator displays the code within the <NOSCRIPT> tag. The following example shows a <NOSCRIPT> tag.
<NOSCRIPT>
<B>This page uses JavaScript, so you need to get Netscape Navigator 2.0
or later!
<BR>
<A HREF=”http://home.netscape.com/comprod/mirror/index.html”>
<IMG SRC=”NSNow.gif”></A>
If you are using Navigator 2.0 or later, and you see this message,
you should enable JavaScript by on the Advanced page of the
Preferences dialog box.
</NOSCRIPT>

Posted in Javascript | Tagged: | Leave a Comment »

Working With Objects

Posted by Ramkumar on January 30, 2009

JavaScript is designed on a simple object-based paradigm. An object is a construct with properties that are JavaScript variables or other objects. An object also has functions associated with it that are known as the object’s methods. In addition to objects that are predefined in the Navigator client and the server, you can define your own objects. This chapter describes how to use objects, properties, functions, and methods, and how to create your own objects. This chapter contains the following sections:
• Objects and Properties
• Creating New Objects
• Predefined Core Objects

Objects and Properties
A JavaScript object has properties associated with it. You access the properties of an object with a simple notation:
objectName.propertyName
Both the object name and property name are case sensitive. You define a property by assigning it a value. For example, suppose there is an object named myCar (for now, just assume the object already exists). You can give it properties named make, model, and year as follows:
myCar.make = “Ford”
myCar.model = “Mustang”
myCar.year = 1969;

An array is an ordered set of values associated with a single variable name. Properties and arrays in JavaScript are intimately related; in fact, they are different interfaces to the same data structure. So, for example, you could access the properties of the myCar object as follows:
myCar["make"] = “Ford”
myCar["model"] = “Mustang”
myCar["year"] = 1967

This type of array is known as an associative array, because each index element is also associated with a string value. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object’s name as arguments to the function:
function show_props(obj, obj_name) {
var result = “”
for (var i in obj)
result += obj_name + “.” + i + ” = ” + obj[i] + “\n”
return result
}
So, the function call show_props(myCar, “myCar”) would return the following:
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1967

Creating New Objects
JavaScript has a number of predefined objects. In addition, you can create your own objects. In JavaScript 1.2, you can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object using that function and the new operator.
Using Object Initializers
In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. “Object initializer” is consistent with the terminology used by C++. The syntax for an object using an object initializer is:
objectName = {property1:value1, property2:value2,…, propertyN:valueN}
where objectName is the name of the new object, each propertyI is an identifier (either a name, a number, or a string literal), and each valueI is an expression whose value is assigned to the propertyI. The objectName and assignment is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable. If an object is created with an object initializer in a top-level script, JavaScript interprets the object each time it evaluates the expression containing the object literal. In addition, an initializer used in a function is created each time the function is called. The following statement creates an object and assigns it to the variable x if and only if the expression cond is true.
if (cond) x = {hi:”there”}
The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.
myHonda = {color:”red”,wheels:4,engine:{cylinders:4,size:2.2}}
You can also use object initializers to create arrays. See “Array Literals” on page 37. JavaScript 1.1 and earlier versions. You cannot use object initializers. You can create objects only using their constructor functions or using a function supplied by some other object for that purpose.

Using a Constructor Function
Alternatively, you can create an object with these two steps:
1. Define the object type by writing a constructor function.
2. Create an instance of the object with new.
To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, year, and color. To do this, you would write the following function:
function car(make, model, year) {
this.make = make
this.model = model
this.year = year
}
Notice the use of this to assign values to the object’s properties based on the values passed to the function. Now you can create an object called mycar as follows:
mycar = new car(“Eagle”, “Talon TSi”, 1993)
This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string “Eagle”, mycar.year is the integer 1993, and so on. You can create any number of car objects by calls to new. For example,
kenscar = new car(“Nissan”, “300ZX”, 1992)
vpgscar = new car(“Mazda”, “Miata”, 1990)
An object can have a property that is itself another object. For example, suppose you define an object called person as follows:
function person(name, age, sex) {
this.name = name
this.age = age
this.sex = sex
}
and then instantiate two new person objects as follows:
rand = new person(“Rand McKinnon”, 33, “M”)
ken = new person(“Ken Jones”, 39, “M”)
Then you can rewrite the definition of car to include an owner property that takes a person object, as follows:
function car(make, model, year, owner) {
this.make = make
this.model = model
this.year = year
this.owner = owner
}
To instantiate the new objects, you then use the following:
car1 = new car(“Eagle”, “Talon TSi”, 1993, rand)
car2 = new car(“Nissan”, “300ZX”, 1992, ken)
Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:
car2.owner.name
Note that you can always add a property to a previously defined object. For example, the statement
car1.color = “black”
adds a property color to car1, and assigns it a value of “black.” However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car object type.

Indexing Object Properties
In JavaScript 1.0, you can refer to an object’s properties by their property name or by their ordinal index. In JavaScript 1.1 or later, however, if you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index. This applies when you create an object and its properties with a constructor function, as in the above example of the Car object type, and when you define individual properties explicitly (for example, myCar.color = “red”). So if you define object properties initially with an index, such as myCar[5] = “25 mpg”, you can subsequently refer to the property as myCar[5]. The exception to this rule is objects reflected from HTML, such as the forms array. You can always refer to objects in these arrays by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of “myForm”, you can refer to the form as document.forms[1] or document.forms["myForm"] or document.myForm.

Defining Properties for an Object Type
You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1.
Car.prototype.color=null
car1.color=”black”

Defining Methods
A method is a function associated with an object. You define a method the same way you define a standard function. Then you use the following syntax to associate the function with an existing object:
object.methodname = function_name
where object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function. You can then call the method in the context of the object as follows:
object.methodname(params);
You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects; for example,
function displayCar() {
var result = “A Beautiful ” + this.year + ” ” + this.make
+ ” ” + this.model
pretty_print(result)
}
where pretty_print is function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs. You can make this function a method of car by adding the statement
this.displayCar = displayCar;
to the object definition. So, the full definition of car would now look like
function car(make, model, year, owner) {
this.make = make
this.model = model
this.year = year
this.owner = owner
this.displayCar = displayCar
}
Then you can call the displayCar method for each of the objects as follows:
car1.displayCar()
car2.displayCar()

Using this for Object References
JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have a function called validate that validates an object’s value property, given the object and the high and low values:
function validate(obj, lowval, hival) {
if ((obj.value < lowval) || (obj.value > hival))
alert(“Invalid Value!”)
}
Then, you could call validate in each form element’s onChange event handler, using this to pass it the form element, as in the following example:
<INPUT TYPE=”text” NAME=”age” SIZE=3
onChange=”validate(this, 18, 99)”>
In general, this refers to the calling object in a method. When combined with the form property, this can refer to the current object’s parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form’s name. The button’s onClick event handler uses this.form to refer to the parent form, myForm.
<FORM NAME=”myForm”>
Form name:<INPUT TYPE=”text” NAME=”text1″ VALUE=”Beluga”>
<P>
<INPUT NAME=”button1″ TYPE=”button” VALUE=”Show Form Name”
onClick=”this.form.text1.value=this.form.name”>
</FORM>

Deleting Objects
You can remove an object by using the delete operator. The following code shows how to remove an object.
myobj=new Number()
delete myobj // removes the object and returns true

Predefined Core Objects
This section describes the predefined objects in core JavaScript: Array, Boolean, Date, Function, Math, Number, RegExp, and String.

Array Object
JavaScript does not have an explicit array data type. However, you can use the predefined Array object and its methods to work with arrays in your applications. The Array object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. It has a property for determining the array length and other properties for use with regular expressions. An array is an ordered set of values that you refer to with a name and an index. For example, you could have an array called emp that contains employees’ names indexed by their employee number. So emp[1] would be employee number one, emp[2] employee number two, and so on.

Creating an Array
To create an Array object:
1. arrayObjectName = new Array(element0, element1, …, elementN)
2. arrayObjectName = new Array(arrayLength)
arrayObjectName is either the name of a new object or a property of an existing object. When using Array properties and methods, arrayObjectName is either the name of an existing Array object or a property of an existing object. element0, element1, …, elementN is a list of values for the array’s elements. When this form is specified, the array is initialized with the specified values as its elements, and the array’s length property is set to the number of arguments. arrayLength is the initial length of the array. The following code creates an array of five elements:
billingMethod = new Array(5)
Array literals are also Array objects; for example, the following literal is an Array object. See “Array Literals” on page 37 for details on array literals.
coffees = ["French Roast", "Columbian", "Kona"]

Populating an Array
You can populate an array by assigning values to its elements. For example,
emp[1] = “Casey Jones”
emp[2] = “Phil Lesh”
emp[3] = “August West”
You can also populate an array when you create it:
myArray = new Array(“Hello”, myVar, 3.14159)

Referring to Array Elements
You refer to an array’s elements by using the element’s ordinal number. For example, suppose you define the following array:
myArray = new Array(“Wind”,”Rain”,”Fire”)
You then refer to the first element of the array as myArray[0] and the second element of the array as myArray[1]. The index of the elements begins with zero (0), but the length of array (for example, myArray.length) reflects the number of elements in the array.

Array Methods
The Array object has the following methods:
• concat joins two arrays and returns a new array.
• join joins all elements of an array into a string.
• pop removes the last element from an array and returns that element.
• push adds one or more elements to the end of an array and returns that last element added.
• reverse transposes the elements of an array: the first array element becomes the last and the last becomes the first.
• shift removes the first element from an array and returns that element
• slice extracts a section of an array and returns a new array.
• splice adds and/or removes elements from an array.
• sort sorts the elements of an array.
• unshift adds one or more elements to the front of an array and returns the new length of the array.
For example, suppose you define the following array:
myArray = new Array(“Wind”,”Rain”,”Fire”)
myArray.join() returns “Wind,Rain,Fire”; myArray.reverse transposes the array so that myArray[0] is “Fire”, myArray[1] is “Rain”, and myArray[2] is “Wind”. myArray.sort sorts the array so that myArray[0] is “Fire”, myArray[1] is “Rain”, and myArray[2] is “Wind”.

Two-Dimensional Arrays
The following code creates a two-dimensional array.
a = new Array(4)
for (i=0; i < 4; i++) {
a[i] = new Array(4)
for (j=0; j < 4; j++) {
a[i][j] = “["+i+","+j+"]“
}
}
The following code displays the array:
for (i=0; i < 4; i++) {
str = “Row “+i+”:”
for (j=0; j < 4; j++) {
str += a[i][j]
}
document.write(str,”<p>”)
}
This example displays the following results:
Row 0:[0,0][0,1][0,2][0,3]
Row 1:[1,0][1,1][1,2][1,3]
Row 2:[2,0][2,1][2,2][2,3]
Row 3:[3,0][3,1][3,2][3,3]

Arrays and Regular Expressions

When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of regexp.exec, string.match, and string.replace. For information on using arrays with regular expressions,

Boolean Object
The Boolean object is a wrapper around the primitive Boolean data type. Use the following syntax to create a Boolean object:
booleanObjectName = new Boolean(value)
Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.

Date Object
JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties. JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00. The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC. To create a Date object:
dateObjectName = new Date([parameters])
where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object. The parameters in the preceding syntax can be any of the following:
• Nothing: creates today’s date and time. For example, today = new Date().
• A string representing a date in the following form: “Month day, year hours:minutes:seconds.” For example, Xmas95 = new Date(“December 25, 1995 13:30:00″). If you omit hours, minutes, or seconds, the value will be set to zero.
• A set of integer values for year, month, and day. For example, Xmas95 = new Date(1995,11,25). A set of values for year, month, day, hour, minute, and seconds. For example, Xmas95 = new Date(1995,11,25,9,30,0).
JavaScript 1.2 and earlier versions. The Date object behaves as follows:
• Dates prior to 1970 are not allowed.
• JavaScript depends on platform-specific date facilities and behavior; the behavior of the Date object varies from platform to platform.

Methods of the Date Object
The Date object methods for handling dates and times fall into these broad categories:
• “set” methods, for setting date and time values in Date objects.
• “get” methods, for getting date and time values from Date objects.
• “to” methods, for returning string values from Date objects.
• parse and UTC methods, for parsing Date strings.
With the “get” and “set” methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:
• Seconds and minutes: 0 to 59
• Hours: 0 to 23
• Day: 0 (Sunday) to 6 (Saturday)
• Date: 1 to 31 (day of the month)
• Months: 0 (January) to 11 (December)
• Year: years since 1900
For example, suppose you define the following date:
Xmas95 = new Date(“December 25, 1995″)
Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 95. The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date object. For example, the following code displays the number of days left in the current year:
today = new Date()
endYear = new Date(1995,11,31,23,59,59,999) // Set day and month
endYear.setFullYear(today.getFullYear()) // Set year to this year
msPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per day
daysLeft = (endYear.getTime() – today.getTime()) / msPerDay
daysLeft = Math.round(daysLeft) //returns days left in the year
This example creates a Date object named today that contains today’s date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days. The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object:
IPOdate = new Date()
IPOdate.setTime(Date.parse(“Aug 9, 1995″))

Using the Date Object: an Example
In the following example, the function JSClock() returns the time in the format of a digital clock.
function JSClock() {
var time = new Date()
var hour = time.getHours()
var minute = time.getMinutes()
var second = time.getSeconds()
var temp = “” + ((hour > 12) ? hour – 12 : hour)
temp += ((minute < 10) ? “:0″ : “:”) + minute
temp += ((second < 10) ? “:0″ : “:”) + second
temp += (hour >= 12) ? ” P.M.” : ” A.M.”
return temp
}
The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute and seconds to hour, minute, and second. The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour – 13), otherwise simply hour. The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way. Finally, a conditional expression appends “PM” to temp if hour is 12 or greater; otherwise, it appends “AM” to temp.

Function Object
The predefined Function object specifies a string of JavaScript code to be compiled as a function. To create a Function object:
functionObjectName = new Function ([arg1, arg2, ... argn], functionBody)
functionObjectName is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror. arg1, arg2, … argn are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example “x” or “theForm”. functionBody is a string specifying the JavaScript code to be compiled as the function body. Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled. In addition to defining functions as described here, you can also use the function statement.The following code assigns a function to the variable setBGColor. This function sets the current document’s background color.
var setBGColor = new Function(“document.bgColor=’antiquewhite’”)
To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable:
var colorChoice=”antiquewhite”
if (colorChoice==”antiquewhite”) {setBGColor()}
You can assign the function to an event handler in either of the following ways:
1. document.form1.colorButton.onclick=setBGColor
2. <INPUT NAME=”colorButton” TYPE=”button”
VALUE=”Change background color”
onClick=”setBGColor()”>
Creating the variable setBGColor shown above is similar to declaring the following function:
function setBGColor() {
document.bgColor=’antiquewhite’
}
You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:
• The inner function can be accessed only from statements in the outer function.
• The inner function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the inner function.

Math Object
The predefined Math object has properties and methods for mathematical constants and functions. For example, the Math object’s PI property has the value of pi (3.141…), which you would use in an application as
Math.PI
Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write
Math.sin(1.56)
Note that all trigonometric methods of Math take arguments in radians. The following table summarizes the Math object’s methods

Posted in Javascript | Tagged: | Leave a Comment »

Differences Between PHP 4 and 5

Posted by Ramkumar on January 29, 2009

Differences Between PHP 4 and 5

Language Features

  • PHP 5 allows limited type hinting. This allows you to specify that the parameter

to a function or class method can only be of a specific class (or one of its

subclasses), or an array. However, you may not specify any other scalar types.

  • The foreach construct now supports by-reference declaration of the value element.
  • A number of new functions, particularly for string and arraymanipulation, has

also been added to the core platform.

Objects

  • For all intents and purposes, all objects in PHP 5 are passed by reference. This

means that assigning an object to a variable will not create a copy of the former,

but simply creates another reference to it.

  • Constants, aswell as staticmethods and properties, can nowbe definedwithin

the scope of a class.

  • Class methods and properties now feature visibility, and can be declared as

public, private or protected. Classes and methods can also be declared as

final to prevent further inheritance.

  • Since all objects are assigned by reference, you now need a specialized mechanism

to copy objects. This is provided by the clone construct and the __clone()

magic method.

  • PHP 5 features unified constructors and destructors-all constructors should

now be named __construct(), and the new __destruct() magic method has

been added for object destruction.

  • With the addition of interfaces and abstract classes, PHP developers now have

far greater control over how they implement their object-oriented code. Interfaces

can be used to define common APIs, while abstract classes provide

models for class implementations that follow a specific blueprint.

  • Class definitions can now be loaded on demand by using the __autoload()

function.

MagicMethods

A multitude of new “magic” methods has been introduced in PHP 5:

  • __get() and __set() are called when accessing or assigning an undefined object

property, while __call() is executed when calling a non-existent method

of a class.

  • __isset() is called when passing an undefined property to the isset() construct.
  • __unset() is called when passing an undefined property to unset().
  • __toString() is called when trying to directly echo or print() an object.
  • __set_state() is inserted dynamically by var_export() to allow for reinitialization

on execution of var_export()’s output.

Selected New Extensions

  • SimpleXML allows easy access to XML data using object and array notation.
  • PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in

the formof the libxml2-based DOM and XSL extensions.

  • The PHP Data Objects (PDO) extension provides a unified database access extension

that allows access to many different types of database systems by using

a common interface. PDO is not an abstraction layer-except for prepared

queries, it does nothing to abstract the actual database code (SQL), itself.

  • The hash extension is a new replacement for the GPLed libmhash; it was added

to the PHP core starting with version 5.1.2. It can produce hashes using many

algorithms, including the familiarMD5and SHA1, aswell as some more secure

(albeit slower) algorithms, such as snefru.

  • The Standard PHP Library (SPL) provides numerous interfaces that enhance

the way classes interact with the PHP language, including the new Iterator

interfaces.

  • The new Reflection extension allows for runtime introspection of executing

PHP code.

ErrorManagement

  • Classes now support exceptions; the new set_exception_handler() function

allows you to define a script-wide exception handler.

  • The E_STRICT error reporting level has been added to the language to emit notices

when legacy or deprecated code is encountered.

Posted in Interview Questions, Introduction, PHP | Tagged: , | 1 Comment »

India in Sri Lanka ODI Series – 1st ODI

Posted by Ramkumar on January 29, 2009

India won by 6 wickets (with 11 balls remaining)

click here to view detail scorecard

Posted in General, Sports | Tagged: , | Leave a Comment »

India Vs Srilanka ODI Match Schedule 2009

Posted by Ramkumar on January 27, 2009

1st ODI Match
28th Jan. 2009, Wednsday (D/N)
Rangiri Dambulla International Stadium

2nd ODI Match
30th Jan. 2009, Friday (D/N)
Rangiri Dambulla International Stadium

3rd ODI Match
3rd Feb. 2009, Monday (D/N)
R Premadasa Stadium, Colombo

4th ODI Match
5th Feb. 2009, Thursday (D/N)
R Premadasa Stadium, Colombo

5th ODI Match
8th Feb. 2009, Sunday (D/N)
Sinhalese Sports Club Ground, Colombo

Squard:

India
MS Dhoni (Captain), Virender Sehwag, Sachin Tendulkar, Gautam Gambhir, Yuvraj Singh, Rohit Sharma, Ishant Sharma, Yusuf Pathan, Zaheer Khan, Pragyan Ojha, Irfan Pathan, Suresh Raina, Munaf Patel, Praveen Kumar and new face Ravindra Jadeja.

Srilanka
Mahela Jayawardene (captain), Kumar Sangakkara, Sanath Jayasuriya, Upul Tharanga, Chamara Kapugedera, Jehan Mubarak, Tillakaratne Dilshan, Thilina Kandamby, Muttiah Muralitharan, Ajantha Mendis, Farveez Maharoof, Dilhara Fernando, Nuwan Kulasekara, Thilina Thushara, Angelo Mathews

Posted in General, Media, Sports | Tagged: , , | Leave a Comment »

Anna University Result 2008

Posted by Ramkumar on January 27, 2009

Click here to view Anna University Result 2008 [ B.E / B.Tech]

Link1

Link2

Posted in General, Media, Technology | Tagged: , | Leave a Comment »

Sensors

Posted by Ramkumar on January 26, 2009

A sensor is a physical device or biological organ that detects, or senses, a signal or physical condition and chemical compounds. There are various types of sensors used for different purpose. Among them, Passive sensors and active sensors are the most basic types of sensor. Passive sensors are used for detecting the reflected or emitted Electro-magnetic radiation from natural sources, while active sensors are used to detect reflected responses from objects which are irradiated from artificially generated energy sources, such as radar.
Further, each type of sensor is divided into two classes namely non-scanning and scanning systems. A sensor having a combination of passive, non-scanning and non-imaging method belongs to class of profile recorder, for example a microwave radiometer. A sensor having a combination of passive, non-scanning and imaging method belongs to class of camera-type devices, for example an aerial survey camera or a space camera.
Sensors classified as a combination of passive, scanning and imaging are further classified into two category viz. image plane scanning sensors, such as TV cameras and solid state scanners and object plane scanning sensors, such as multi-spectral scanners (optical-mechanical scanner) and scanning microwave radiometers.
In addition to this kind of classification, sensors can be classified according to the type of energy transfer that they detect. The various types of sensors are Thermal energy sensors, Electromagnetic sensor, Mechanical sensors, Chemical sensors, Optical and Radiation sensors, Ionizing radiation sensor, non-Ionizing radiation sensors, acoustic sensors and biological sensors.
Sensors can be used to monitor conditions at different locations, such as temperature, sound, vibration, pressure, motion or pollutants. Sensors used for such purpose are usually small and inexpensive, so that they can be produced and deployed in large numbers. In addition, it also helps to decrease resources in terms of energy and increases memory, computational speed and bandwidth.
In such network, numbers of sensors are deployed across a geographical area. Each sensor has wireless communication capability and some level of intelligence for signal processing and networking of the data. To be precise, each device consists of a radio transceiver, a small microcontroller, and an energy source (battery). These devices communicate with each other to deliver data to a monitoring computer. The areas covered by Sensor network are sensing, communications, and computation (hardware, software, and algorithms). After this process, data from the sensors is collected and analysed by a computer outside the network. This computer is connected to the network by a special network node called a gateway node or sink or base station

Use
Sensor networks are implemented in various areas for different purposes, like video surveillance, traffic monitoring, air traffic control, robotics, cars, home and health monitoring and manufacturing and industrial automation. One typical application in environmental monitoring is Sensor Web. Besides this, it is also used by military service to detect and gain as much information as possible about enemy movements, explosions, and other phenomena of interest.

Future sensors
Sensor has evolved as a great player in industrial application and in other areas also due to its ability to operate at much higher speeds; conduct repetitive, multiple, and consistent inspections all at significantly lower cost.
Furthermore, it has the potential to change the working of industrial world, making working process quicker and simpler. But, the challenge doesn`t end here. In the upcoming days, the biggest challenge for the engineers will be to manufacture a sensor, which is capable of tolerating any bad conditions, such as weather, chemicals, dust and humidity against electromagnetic interference (EMC).

Posted in General, Technology | Tagged: | Leave a Comment »