Thursday, November 26, 2009

URI, URL and URN

URI, URL and URN
A URI can be further classified as a locator, a name, or both. The term "Uniform Resource Locator" (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network "location"). The term "Uniform Resource Name" (URN) has been used historically to refer to both URIs under the "urn" scheme [RFC2141], which are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable, and to any other URI with the properties of a name.

Computer scientists may classify a URI as a locator (URL), or a name (URN), or both. A Uniform Resource Name (URN) functions like a person's name, while a Uniform Resource Locator (URL) resembles that person's street-address. In other words: the URN defines an item's identity, while the URL provides a method for finding it.

Saturday, October 24, 2009

eclipser-blog: Automatic generation of BIRT reports

eclipser-blog: Automatic generation of BIRT reports: "Automatic generation of BIRT reports
Automatic generation of BIRT reports is a common task for every company that has reports that should be presented to the customers.

Those reports should be delivered regularly. If howto that I am going to present is available somewhere than I am sorry, but I was not able to find it out and I had to merge knowledgle scattered in a several wiki pages.

But in the ends solution seems to be very easy:

1. Download BIRT runtime and unzip it somewhere. You should have now birt-runtime-2_2_1_1 folder.
2. Set up environment variable to point to that folder either in OS or inside birt-runtime-2_2_1_1\ReportEngine\genReport.bat(sh for linux).
3. Put your jdbc jar file in folder birt-runtime-2_2_1_1\ReportEngine\plugins\org.eclipse.birt.report.data.oda.jdbc_2.2.1.r22x_v20070919\drivers.
4. Execute genReport.bat script to see usage. For all those good computer scientists (and good computer scientist is a lazy one) I present sample command:
genReport.bat -f PDF -o outputfile.pdf -F report_design.rptdesign"

Wednesday, October 21, 2009

Javascript Tutorial - Draggable View In A Container | Switch on the Code

Javascript Tutorial - Draggable View In A Container | Switch on the Code: "<div id='containerBox' style='position:relative;
border:1px solid black;width:520px;
height:250px;overflow:hidden;' >
<img id='draggableElement' src='duck.jpg'
style='width:1024px;height:1024px;position:absolute;
top:-333px;left:-500px;cursor:move;' />
</div>

<script type='text/javascript'>
var el = document.getElementById('draggableElement');
var parent = el.parentNode;
var leftEdge = parent.clientWidth - el.clientWidth;
var topEdge = parent.clientHeight - el.clientHeight;
var dragObj = new dragObject(el, null,
new Position(leftEdge, topEdge), new Position(0, 0));
</script>"

Tuesday, October 6, 2009

Simple Navigation Bar With CSS And (x)HTML | Van SEO Design


Simple Navigation Bar With CSS And (x)HTML | Van SEO Design
: "Complete Navigation Bar (x)HTML And CSS

The complete code for our simple navigation bar is:


<ul id='list-nav'>
<li><a href='#'>Home</a></li>
<li><a href='#'>About Us</a></li>
<li><a href='#'>Services</a></li>
<li><a href='#'>Products</a></li>
<li><a href='#'>Contact</a></li>
</ul>

ul#list-nav {
list-style:none;
margin:20px;
padding:0;
width:525px
}

ul#list-nav li {
display:inline
}

ul#list-nav li a {
text-decoration:none;
padding:5px 0;
width:100px;
background:#485e49;
color:#eee;
float:left;
text-align:center;
border-left:1px solid #fff;
}

ul#list-nav li a:hover {
background:#a2b3a1;
color:#000
}"

Friday, October 2, 2009

Array.prototype.sum,max,min [javascript] [array] [prototype]

Array.prototype.sum,max,min [javascript] [array] [prototype]: "Array.prototype.sum = function(){
for(var i=0,sum=0;i<this.length;sum+=this[i++]);
return sum;
}
Array.prototype.max = function(){
return Math.max.apply({},this)
}
Array.prototype.min = function(){
return Math.min.apply({},this)
}



numeric value only.

[1,2,3].sum() => 6
[1,2,3].max() => 3
[1,2,3].min() => 1"

Wednesday, May 27, 2009

Javascript - Calculating Elapsed Time

// using static methods
var start = Date.now();
// the event you'd like to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // time in milliseconds

// if you have Date objects
var start = new Date();
// the event you'd like to time goes here:
doSomethingForALongTime();
var end = new Date();
var elapsed = end.getTime() - start.getTime(); // time in milliseconds"

// About Date()
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, date [, hour, minute, second, millisecond ])

today = new Date();
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);

Thursday, May 21, 2009

Linux Shell Script - Find Relative Path of Current Script

Linux Shell Script - Find Relative Path of Current Script:

"echo 'Path to $(basename $0) is $(readlink -f $0)'

CURRENTDIR=`dirname $0`
echo 'Path is: ${CURRENTDIR}'

reldir=`dirname $0`
echo 'RelDir $reldir'
cd $reldir
CURRENTDIR=`pwd`
echo 'Directory is ${CURRENTDIR}'
sh ${CURRENTDIR}/samp1.sh
sh ${reldir}/samp1.sh"

Wednesday, May 13, 2009

CSS Properties: Display vs. Visibility

CSS Properties: Display vs. Visibility: "CSS Properties: Display vs. Visibility
Browsers Targeted: Internet Explorer 3+

It's fairly easy to confuse the Cascading Style Sheets (CSS) properties display and visibility, because it would seem that they do much the same thing. However, the two properties are in fact quite different. The visibility property determines whether a given element is visible or not (visibility='visible|hidden'). However, when visibility is set to hidden, the element being hidden still occupies its same place in the layout of the page.


<script language='JavaScript'>
function toggleVisibility(me){
if (me.style.visibility=='hidden'){
me.style.visibility='visible';
}
else {
me.style.visibility='hidden';
}
}
</script>


<div onclick='toggleVisibility(this)' style='position:relative'>
This example displays text that toggles between a visibility of 'visible' and 'hidden'.
Note the behavior of the next line.</div><div>This second line shouldn't
move, since visibility retains its position in the flow</div>

This example displays text that toggles between a visibility of 'visible' and 'hidden'. Note the behavior of the next line.
This second line shouldn't move, since visibility retains its position in the flow

Note that when an item is hidden, it doesn't receive events. Thus in the sample code, the first sentence never detects that there has been a mouse click once the item is hidden, so you can't click the area to make it visible again. The display property, on the other hand, works a little differently. Where visibility hides the element but keeps its flow position, display actually sets the flow characteristic of the element. When display is set to block, for example, everything within the containing element is treated as a separate block and is dropped into the flow at that point as if it were a <DIV> element (you can actually set the display block of a <SPAN> element and it will act like a <DIV>. Setting the display to inline will make the element act as an inline element—it will be composed into the output flow as if it were a <SPAN>>, even if it were normally a block element such as a <DIV>. Finally, if the display property is set to none, then the element is actually removed from the flow completely, and any following elements move forward to compensate:


<script language='JavaScript'>
function toggleDisplay(me){
if (me.style.display=='block'){
me.style.display='inline';
alert('Text is now 'inline'.');
}
else {
if (me.style.display=='inline'){
me.style.display='none';
alert('Text is now 'none'. It will reappear in three seconds.');
window.setTimeout('blueText.style.display='block';',3000,'JavaScript');
}
else {
me.style.display='block';
alert('Text is now 'block'.');
}
}
}
</script>


<div>Click on the <span id='blueText' onclick='toggleDisplay(this)'
style='color:blue;position:relative;cursor:hand;'>blue text</span> to
see how it affects the flow.</div>

Click on the blue text to see how it affects the flow.

Notice that if the display property is not explicitly set, it defaults to the display type the element normally has. Of the two, the display property is definitely the more useful, as most instances of needing to hide text also involve shifting the surrounding HTML flow to accommodate it (think tree structures, as an example)."

Tuesday, May 12, 2009

ANT Task Sending Email to Multiple Receipients with attachments

ANT Task Sending Email to Multiple Receipients with attachments: <project name='SendMail' default='SendEmail'>

<target name='SendEmail'>
<property name='ToEmail' value='To.User1@gmail.com, To.User2@gmail.com'/>
<mail mailhost='smtp.gmail.com' mailport='465' subject='Test Mail from ANT' from='User.Name@gmailcom' tolist='${ToEmail}' user='User.Name@gmail.com' password='passwordhere' ssl='yes'>
<message>Hi, This is Test Mail. </message>
<fileset dir='${basedir}' includes='*.PDF'/>
</mail>
</target>
</project>

ANT Task - Delete Files and Directories

ANT Task - Delete Files and Directories :
<project default='DeleteFilesDirectories' basedir='.'>

<!-- @Ref: http://ant.apache.org/manual/CoreTasks/delete.html -->

<target name='DeleteFilesDirectories'>
<!-- Deletes All Files and Directories (Including Empty Directory) -->
<delete includeemptydirs='true'>
<fileset dir='${basedir}/User' includes='**/*'/>
</delete>

<!-- Deletes All Files and Directories (Excluding Empty Directory) -->
<!--
<delete includeemptydirs='true'>
<fileset dir='${basedir}/User' includes='**/*.*'/>
</delete>
-->

<!-- Deletes All Files and Directories (Including 'User' Directory itself) -->
<!--
<delete includeEmptyDirs='true'>
<fileset dir='User'/>
</delete>
-->

</target>
</project>

ANT Task [propertyregex] - String Replace

ANT Task [propertyregex] - String Replace:
<project name='PRJStringOperations' default='StringOperations' basedir='.'>

<!-- To Remove '' in EmailID's List -->
<typedef resource='./lib/antcontrib.properties' classpath='${basedir}/lib/ant-contrib-1.0b3.jar'/>

<property name='MailTo' value='''sakthi@gmail.com,sakthi@gmail.com'''/>
<target name='StringOperations'>
<propertyregex property='prop.MailTo'
input='${MailTo}'
regexp='([']*)(.*[a-zA-Z])([']*)'
select='\2'
casesensitive='false'/>

<echo message='${prop.MailTo}'/>
</target>

</project>

Thursday, May 7, 2009

Ant - Passing Argument in Command Line

Ant - Passing Argument in Command Line:

Case 1 : Using own bat file (ant.bat) for executing ant
=======================================================
Passing Arguments in Command Line
C:/ant/apache-ant-1.6.2/bin/ant.bat -DArg4First=SUN -DArg4Second=JAVA

In build.xml file
<project default='testAnt'>
<target name='First'>
<echo message='Input value is: ${Arg4First}' />
</target>

<target name='Second'>
<echo message='Input value is: ${Arg4Second}' />
</target>
</project>

Case 2 : Using another batch file(testCallAnt.bat) for calling ant.bat file
===========================================================================
Inside testCallAnt.bat will be,
C:/ant/apache-ant-1.6.2/bin/ant.bat -buildfile testAnt.xml First Second -DArg4First=SUN -DArg4Second=JAVA

Call the Batch file like this,
c:\Ant\> testCallAnt.bat %1 %2

Eg: c:\Ant\> testCallAnt.bat SUN JAVA

Friday, May 1, 2009

10 reasons Why Cloud Computing is the Wave of the Future - LaptopLogic.com

10 reasons Why Cloud Computing is the Wave of the Future - LaptopLogic.com: "10 reasons Why Cloud Computing is the Wave of the Future

April 29, 2009 at 10:04:35 AM, by Gilberto J. Perera Rating: 0 out of 5

What is all this Cloud computing mumbo jumbo about and why should I care? Our editor Gilberto J. Perera puts it to us straight.

Before we delve into the reasons why cloud computing is the wave of the future we must first understand what cloud computing is. According to Berkeley scientists, 'Cloud computing refers to both the applications delivered as services over the Internet and the hardware and systems software in the datacenters that provide those services. The services themselves have long been referred to as Software as a Service (SaaS), so we use that term. The datacenter hardware and software is what we will call a Cloud.'

So what does this mean? Simply put, companies (Google, Microsoft, Amazon) will provide users with software that resides on their servers in the 'cloud' or the 'grid' so that users can access that software and information from anywhere and on any computer attached to the internet. In other words software would cease to be just a tangible product that you buy and install on your computer. Software is evolving into a service that you access from your computer over the internet. Examples of cloud computing can be seen with services like Gmail, Google Docs, Office Live, SOHO, and other online platforms.

In the past couple of years software providers have been moving more and more applications to the 'cloud', this article discusses some of the reasons why cloud computing is the wave of the future in terms of delivering software as a service.

1. Software as a Subscription

In a cloud, software resides on a service providers servers external to a user’s computer. In a sense users would not have to buy software for their computers because the software is loaded per use while the user is online (via a browser or some kind of connector application). The only models that would support this type of software use would be a subscription based or pay as you go model. Instead of shelling $149 for Office Home & Student, a user may pay a set fee/month; say $5.95/month and the user can tailor their subscription to meet their needs. This will keep users from buying software that is bundled with applications the user may not care for. A perfect example of this is the Office Suite.

2. Reduced Software Maintenance

By keeping the software in the 'clouds' users can reduce the amount of maintenance on their computers. Nowadays essentially every program installed on a computer has an update function that searches for the latest software changes in order to patch security flaws, correct software issues, and/or introduce new functionality. When upgrades are made to software on the cloud it does not affect the user's computer, it would not require for the user to restart their computers, it would simply mean that unless the change affects functionality or visual elements, the user will be oblivious to those updates and their computers will never be affected by those updates. A reasonable reduction in systems maintenance would be expected as a result of this.

3. Increased Reliability

Increased reliability stems from the fact that the cloud runs on systems that are extremely reliable and provide some form of redundancy. Unless a user takes the time to setup a backup system for their files or sets up some kind of redundancy with offsite backups, etc. Users run the risk of losing valuable and sometime unrecoverable data on their computers. In the case of grid computing if a storage server on the cloud fails due to hardware or software issues, the service provider needs only to shift the load over to other servers or bring up a backup server in its place. If it occurred at a users premises with installed software a simple issue can turn to hours of technical support over the phone, costly downtime, and unhappy users and customers.

4. Increased Scalability

Running out of hard drive space at home? Looks like an additional hard drive along with a visit to a computer technician for installation will solve the problem. However in a cloud computing environment, storage is not an issue, as long as you can pay for it. Service providers need only to add servers or shift load from one server to another to accommodate for the additional use of space. The same goes for application use, instead of a small business adding additional servers to handle business transactions all they have to do is contact the service provider to let them know that they will need additional resources.

5. Cost Reduction

Costs are reduced in a number of ways. Capital expenditures are reduced because a lot of the load and storage will be shifted over to the service provider who can provide that service at a lower cost. Aside from decreased capital expenditures associated with hardware purchases, users would see the cost of software decrease due to the reduced cost of subscription software. IT staff at businesses would be reduced because the majority of the maintenance is performed at the service provider.

6. Environmentally Friendly

One of the greatest advantages of cloud computing is the increased longevity and use of older hardware used by datacenters. This in turn lessens the amount of electronic waste dumped because equipment is older and increased use of those resources. When businesses use current assets instead of purchasing additional hardware they reduce the size of their carbon footprint because it is one less server that is put into service, it is one less server that is consuming electricity .

7. Matches Current Computing Trends

The introduction of the netbooks has moved a lot of sales from computers and laptops with more powerful processors and extended capabilities to less powerful and more efficient platforms . This signals that users are looking for computers that meet their needs and are affordable. The advent of cloud computing will be able to match this trend because a lot of the processing overhead is performed at the servers and not the computer, so the need for an extremely powerful computer is muted. As cloud computing matures and more and more processing is shifted to the cloud, computers will require less processing power and will have basic functionality.

8. Portability/Accessibility

One the greatest advantages to grid computing is the availability of files and software anywhere that there is an active internet connection. This brings forth added accessibility and productivity for those that are on the road and require access to files and software. With a large number of companies looking for alternatives to employees working at the office and the increasing number of employees making up a mobile workforce. The reduction in application costs and technical support would easily continue to support this trend towards a mobile workforce that would utilize the computer grid.

9. Efficient Use of Computer Resources

The advent of virtualization has provided companies with ways to efficiently used their computer resources. Users no longer require separate servers for different applications. With virtualization multiple server technologies can run from a single server. This shift to virtualization supports the growth of cloud computing due to the increased capabilities of servers. Cloud computing would also simplify IT's role in computer management because computers would be software agnostic.

10. Versionless Software

Versionless software refers to the elimination of software upgrade projects. Changes and updates to software would be constant and version numbers would be transparent to the user, all the user would see is added functionality. It would also give users '...access to new technology early and often rather than forcing them to wait for a final, packaged product to be shipped. ' This concept will enable the enterprise to remain in the cutting edge of technology and would reduce training costs associated with new software releases.

As one can see the case for cloud computing is quite appealing. The shift towards cloud computing would enable businesses to save money while minimizing their impact on the environments. Users would have the flexibility of accessing information from anywhere on the planet where an internet connection exists. Everyone will benefit from the increased availability and affordability of applications that were beyond their reach due to cost and complexity with maintenance and installation. Lastly the need for additional training associated with new product releases would be eliminated to due to the nature of the applications constant changing state."

Tuesday, April 21, 2009

LCD TV - PC World


LCD TV - PC World: "LCD TV
Expert advice on buying an LCD TV.
PC World Staff (Good Gear Guide) 26/02/2009 15:50:00
Page:

*
1
* 2
* 3
* 4
* 5
* 6
* next >

* How does LCD Work?
* Does size matter?
* Is the native resolution really High Definition?
* What differentiates one LCD TV from another?
* What do you need to connect?
* Watching TV
* Don't wait forever!

We use LCD technology every day, from a simple alarm clock to the screen on your mobile phone. LCD television is the pinnacle of that technology; the end product of continual rigorous development and ingenious design. As each new generation rolls out of the world's LCD plants, the innovations are numerous and accompanied by a leap in quality and capability. This poses a unique problem for consumers that they have never really had to face before when buying a television. The market is flooded with choice, and with the high price of flat panel televisions it is hard to make the right decision with confidence. The purpose of this Buying Guide is to show you what to look out for so that you will take home the panel that best suits your needs, your budget and your lounge room.

How does LCD Work?"

Server Operating Systems - PC World

Server Operating Systems - PC World: "Server Operating Systems
PC World Staff (PC World) 18/10/2002 11:50:05



So you're looking at moving to a client-server model. You want to take the documents that are randomly scattered on the hard disks of the office PCs and manage them in a single directory, accessible at any time from any PC in the office. Maybe you want to get your own Internet domain name and have a Web site that you host locally, or build an Intranet for staff information and communication. Perhaps you just want to take your single DSL link and provide secure Net access for everybody in the office.

If you're running a small business and have more than two or three PCs in the office, it's time to start looking at setting up a server. One of your first considerations will be which server operating system (OS) to use.



What is a server operating system? (Back to contents)

Server OSes are designed from the ground up to provide platforms for multi-user, frequently business-critical, networked applications. As such, the focus of such operating systems tends to be security, stability and collaboration, rather than user interface.

Server OSes provide a platform for multi-user applications, and most come bundled with a batch of common server applications, such as Web servers, e-mail agents and terminal services.

Back"

Drag & Drop <DIV> in HTML Using Java script

<head>
<title>Drag 'N' Drop</title>
<script>
function $(v) { return(document.getElementById(v)); }
function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function xy(e,v) { return(v?(agent('msie')?event.clientY+document.body.scrollTop:e.pageY):(agent('msie')?event.clientX+document.body.scrollTop:e.pageX)); }

function dragOBJ(d,e) {

function drag(e) { if(!stop) { d.style.top=(tX=xy(e,1)+oY-eY+'px'); d.style.left=(tY=xy(e)+oX-eX+'px'); } }

var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=xy(e),eY=xy(e,1),tX,tY,stop;

document.onmousemove=drag; document.onmouseup=function(){ stop=1; document.onmousemove=''; document.onmouseup=''; };

}
</script>
</head>
<body>
<div style="cursor: pointer; position: relative; top: 0; left: 0; background-color: #009ACF; height: 20px; width:120;" onmousedown="dragOBJ(this,event); return false;"> Drag 'N' Drop this </div>
</body>

Sunday, April 12, 2009

How to change Eclipse SVN Plugin Password?

How to change Eclipse SVN Plugin Password: "Subclipse does not collect or store username and password credentials when defining a repository. This is because the JavaHL and SVNKit client adapters are intelligent enough to prompt you for this information when they need to — including when your password has changed.

You can also allow the adapter to cache this information and a common question is how do you delete this cached information so that you can be prompted again? We have an open request to have an API added to JavaHL so that we could provide a UI to do this. Currently, you have to manually delete the cache. The location of the cache varies based on the client adapter used.

JavaHL caches the information in the same location as the command line client — in the Subversion runtime configuration area. On Windows this is located in %APPDATA%\Subversion\auth. On Linux and OSX it is located in ~/.subversion/auth. Just find and delete the file with the cached information.

SVNKit caches information in the Eclipse keyring. By default this is a file named .keyring that is stored in the root of the Eclipse configuration folder. Both of these values can be overriden with command line options. To clear the cache, you have to delete the file. Eclipse will create a new empty keyring when you restart."

Wednesday, April 8, 2009

Tutorial: Hello World with Ant

Tutorial: Hello World with Ant: "Tutorial: Hello World with Ant

This document provides a step by step tutorial for starting java programming with Ant. It does not contain deeper knowledge about Java or Ant. This tutorial has the goal to let you see, how to do the easiest steps in Ant.
Content

* Preparing the project
* Enhance the build file
* Enhance the build file
* Using external libraries
* Resources

Preparing the project

We want to separate the source from the generated files, so our java source files will be in src folder. All generated files should be under build, and there splitted into several subdirectories for the individual steps: classes for our compiled files and jar for our own JAR-file.

We have to create only the src directory. (Because I am working on Windows, here is the win-syntax - translate to your shell):

md src

The following simple Java class just prints a fixed message out to STDOUT, so just write this code into src\oata\HelloWorld.java.

package oata;

public class HelloWorld {
public static void main(String[] args) {
System.out.println('Hello World');
}
}

Now just try to compile and run that:

md build\classes
javac -sourcepath src -d build\classes src\oata\HelloWorld.java
java -cp build\classes oata.HelloWorld

which will result in

Hello World

Creating a jar-file is not very difficult. But creating a startable jar-file needs more steps: create a manifest-file containing the start class, creating the target directory and archiving the files.

echo Main-Class: oata.HelloWorld>myManifest
md build\jar
jar cfm build\jar\HelloWorld.jar myManifest -C build\classes .
java -jar build\jar\HelloWorld.jar

Note: Do not have blanks around the >-sign in the echo Main-Class instruction because it would falsify it!
Four steps to a running application

After finishing the java-only step we have to think about our build process. We have to compile our code, otherwise we couldn't start the program. Oh - 'start' - yes, we could provide a target for that. We should package our application. Now it's only one class - but if you want to provide a download, no one would download several hundreds files ... (think about a complex Swing GUI - so let us create a jar file. A startable jar file would be nice ... And it's a good practise to have a 'clean' target, which deletes all the generated stuff. Many failures could be solved just by a 'clean build'.

By default Ant uses build.xml as the name for a buildfile, so our .\build.xml would be:

<project>

<target name='clean'>
<delete dir='build'/>
</target>

<target name='compile'>
<mkdir dir='build/classes'/>
<javac srcdir='src' destdir='build/classes'/>
</target>

<target name='jar'>
<mkdir dir='build/jar'/>
<jar destfile='build/jar/HelloWorld.jar' basedir='build/classes'>
<manifest>
<attribute name='Main-Class' value='oata.HelloWorld'/>
</manifest>
</jar>
</target>

<target name='run'>
<java jar='build/jar/HelloWorld.jar' fork='true'/>
</target>

</project>

Now you can compile, package and run the application via

ant compile
ant jar
ant run

Or shorter with

ant compile jar run"

Technology... Innovation... Automation

Technology... Innovation... Automation: "ANT as a automation tool

When it come to build automations, ANT is one of the most powerful tool that can be used. There might be other tools too, but ANT is most widely available and usable. If you are new to ANT then visit http://ant.apache.org. If you want to explore the power of ANT then visit http://ant.apache.org/manual/index.html.
To write or use ANT first you will have to install it. To find out from where to download and how to isntall ANT please visit http://ant.apache.org/manual/install.html.

Here I will take an process as an example and we'll see how we can automate the process using ANT and make our life easier.
Consider the following process:
You have some bunch of programmers working on a project and you are using a central repository; CVS or VSS. At the end of the day when all the programmers are done with their devlopment/bug fixing task for the day a monotonous process is required to be followed. All the source code from the repository needs to be taken and sent to your team at other end (Onsite) through ftp. This process can be broken down in to following steps:
1. Get the latest source code from the repository.
2. Label the source code appropriately to indicate today's work.
3. Filter the files that need to be send.
4. Archive your source code to zip or gzip.
5. Upload the zip file to ftp.
6. And finally send a mail to all the stakeholders stating the upload path and a release note.

Now if we perform this process manually, it will take considerable time and might also cause problems due to human errors.
But if we automate this process, believe me it will not take more than 30 secs to release a project with around 500 source files. What we need to do is identify the atomic tasks to be performed and automate them.

As you can see, the steps mentioned above are atomic tasks that needs to be performed. ANT provides a huge set of core as well as optional tasks [].
I hope that you have basic knowledge about targets, tasks, taskdef etc.

We will define each step or set of steps as a target. Though the complete script can be writting in one target, I prefer it former way for obvious reasons.

The paramters specified in the code snippets are explained in the end.
Considering the above process;

1. Get the latest source code from the repository.
If you are using CVS, ANT provides core task to perform CVS operations.
This can be written in ANT as:

<cvspass cvsRoot='${cvs.root}' password='${cvs.pass}' passfile='.cvs-pass'/>
<cvs command='login' cvsRoot='${cvs.root}' passfile='.cvs-pass'/>
<cvs dest='${base.dir}' cvsRoot='${cvs.root}' command='update -A -dPC' passfile='.cvspass'/>

If you are using VSS, ANT provides optional task for the same.
<vssget serverpath='${vss.server}' vsspath='${vss.path}/${app.name}' ssdir='${vss.ssdir}' localpath='${base.dir}' login='${vss.username},${vss.pass}' recursive='true' />
The piece of code above will get the latest version of code from repository into the specified destination folder.

2. Label the source code appropriately to indicate released work.

<echo message='Tag ${vss.path}/${app.name} with ${app.name}-${timestamp}'/>
<cvs cvsRoot='${cvs.root}' command='tag ${app.name}-${timestamp}' package='${app.name}' passfile='.cvspass'/>

If you are using VSS, ANT provides optional task for the same.
<echo message='Label ${vss.path}/${app.name} with ${app.name}-${timestamp}'/>
<vsslabel serverpath='${vss.server}' vsspath='${vss.path}/${app.name}' ssdir='${vss.ssdir}' login='${vss.username},${vss.pass}' label='${app.name}-${timestamp}' />

The above two tasks can be specified in one target for modularity and hence the reaulting target will be:

<!-- CVS task Starts-->
<target name='cvs' description='get the latest source code from CVS' >
<cvspass cvsRoot='${cvs.root}' password='${cvs.pass}' passfile='.cvs-pass'/>
<cvs command='login' cvsRoot='${cvs.root}' passfile='.cvs-pass'/>
<cvs dest='${base.dir}' cvsRoot='${cvs.root}' command='update -A -dPC' passfile='.cvspass'/>
<cvs cvsRoot='${cvs.root}' command='tag ${app.name}-${timestamp}' package='${app.name}' passfile='.cvspass'/>
</target>
<!-- CVS task ends -->

<!-- VSS task starts -->
<target name='vss' description='get the latest source code from VSS' >
<vssget serverpath='${vss.server}' vsspath='${vss.path}/${app.name}' ssdir='${vss.ssdir}' localpath='${base.dir}' login='${vss.username},${vss.pass}' recursive='true' />
<echo message='Label ${vss.path}/${app.name} with ${app.name}-${timestamp}'/>
<vsslabel serverpath='${vss.server}' vsspath='${vss.path}/${app.name}' ssdir='${vss.ssdir}' login='${vss.username},${vss.pass}' label='${app.name}-${timestamp}' />
</target>
<!-- VSS task ends -->

Now moving to next steps:
3. Filter the files that need to be send.
4. Archive your source code to zip or gzip.
These two steps include filtering out those files which need to be sent and bundle those files.
The target to accomplish this task would look something like this:

<target name='package' description='Package the source code and Contextroot' >
<property name='target.filename' value='${app.name}-${timestamp}.zip'/>
<zip zipfile='${zip.dir}/${app.name}/${target.filename}' >
<fileset dir='${base.dir}'>
<include name='src/**'/>
<include name='ContextRoot/jsp/**'/>
<include name='ContextRoot/WEB-INF/**'/>
<include name='src/META_INF/ejb-jar.xml'/>
<exclude name='ContextRoot/WEB-INF/classes/**'/>
<exclude name='ContextRoot/WEB-INF/lib/**'/>
<exclude name='ContextRoot/jsp/**/*.gif'/>
<exclude name='ContextRoot/jsp/image/**'/>
<exclude name='src/META_INF/**'/>
</fileset>
</zip>
</target>

We have used here ANT task to zip a set of files. The set of files can be specified
Here you need to specify the parameters like the target path and name of the zip file, the source files to be zipped, etc.

5. Upload the zip file to ftp server.
ANT provides a task that allows you to upload files to ftp server. The ANT target for the same is:

<target name='upload' description='uploads to FTP'>
<echo message='Uploading file to ftp : ${target.filename}'/>
<ftp server='${ftp.url}' userid='${ftp.username}' password='${ftp.password}' binary='yes' remotedir='${ftp.remotedir}'>
<fileset dir='${zip.dir}/${app.name}'>
<include name='${target.filename}'/>
</fileset>
</ftp>
<echo message='Release uploaded successfully '/>
</target>

As you can see, the parameters that needs to be provided are connection details for ftp server, transfer mode, files upload path and source file.

The next and final step:
6. And finally send a mail to all the stakeholders stating the upload path and a release note.
ANT provides a optional task for sending MIME mail. But this task highly depends on what contents you require in your mail.
For this task, I have written a class that generates a release note for me which I attach to my mail. Though this highly depends on your requirement but here I have used a very important feature of ANT that is developing custom tasks.
To know how to develop a custoom task, please visit ant.apache.org/manual/develop.html
Here taskdef is used to declare a new Task to ANT and which class should be loaded to implement this task.
The below code declares a new task which is named as releasenote and then this task is to create the release note.

<taskdef name='releasenote' classname='com.note.ReleaseNoteCreator'/>
<releasenote appName='${app.name}' noteName='${note.name}' releasedFile='ftp://ftp.zensar.com/${ftp.remotedir}/${target.filename}'/>

Once the release note is created, the following task will release a mail for you according to the paramters provided.

<mail from='${mail.from}' tolist='${mail.to}' cclist='${mail.cc}' files='${note.name}' user='${mail.user}' password='${mail.pass}' ssl='no' replyto='${mail.reply}' subject='${mail.subject}' mailhost='${mail.host}' mailport='${mail.port}' messagefile='${mail.message}'/> <!--message='${mail.message}'/-->

The complete target will look something like this:

<target name='mail' description='Send release mail' depends='init'>
<echo message='Generating Release Note'/>
<property name='note.name' value='${zip.dir}/${app.name}/ReleaseNote-${timestamp}.txt'/>
<mail from='${mail.from}' tolist='${mail.to}' cclist='${mail.cc}' files='${note.name}' user='${mail.user}' password='${mail.pass}' ssl='no' replyto='${mail.reply}' subject='${mail.subject}' mailhost='${mail.host}' mailport='${mail.port}' messagefile='${mail.message}'/> <!--message='${mail.message}'/-->
</target>

As you can see each target depends on a 'init' target. This 'init' target is used to perform some chores before starting the reelase process. Here it defines a timestamp variable which is used to generate distinct filesnames. The init target will look something like this
Here the record task is used for ANT logging.

<target name='init' description='Create password file and try Login'>
<tstamp/>
<property name='timestamp' value='${DSTAMP}-${TSTAMP}'/>
<record name='${log.file}-${timestamp}.log' action='start' append='yes' loglevel='debug'/>
<echo message='Update, Tag, Package, Upload, and release latest source code from ${rep.type} for ${app.name}'/>
</target>

And finally you can either define a target which will call other targets or set the target execution sequence while executing ANT build file.

My final ANT build file for this process comes out to be:

<?xml version='1.0' encoding='ISO-8859-1'?>
<project name='RELEASE_BUILD' default='getsource' basedir='.'>

<property file='${arg-app}-build.properties'/>
<property name='rep.type' value='${arg-rep}'/>
<property name='base.dir' value='${ws.dir}/${app.name}'/>

<taskdef name='releasenote' classname='com.note.CreateReleaseNote'/>
<target name='init' description='Create password file and try Login'>
<tstamp/>
<property name='timestamp' value='${DSTAMP}-${TSTAMP}'/>
<record name='${log.file}-${timestamp}.log' action='start' append='yes' loglevel='debug'/>
<echo message='Update, Tag, Package, Upload, and release latest source code from ${rep.type} for ${app.name}'/>
</target>

<!-- CVS Starts-->
<target name='cvs' description='get the latest source code from CVS' >
<cvspass cvsRoot='${cvs.root}' password='${cvs.pass}' passfile='.cvs-pass'/>
<cvs command='login' cvsRoot='${cvs.root}' passfile='.cvs-pass'/>
<cvs dest='${base.dir}' cvsRoot='${cvs.root}' command='update -A -dPC' passfile='.cvspass'/>
<cvs cvsRoot='${cvs.root}' command='tag ${app.name}-${timestamp}' package='${app.name}' passfile='.cvspass'/>
</target>
<!-- CVS ends -->

<!-- VSS starts -->
<target name='vss' description='get the latest source code from VSS' >
<vssget serverpath='${vss.server}' vsspath='${vss.path}/${app.name}' ssdir='${vss.ssdir}' localpath='${base.dir}' login='${vss.username},${vss.pass}' recursive='true' />
<echo message='Label ${vss.path}/${app.name} with ${app.name}-${timestamp}'/>
<vsslabel serverpath='${vss.server}' vsspath='${vss.path}/${app.name}' ssdir='${vss.ssdir}' login='${vss.username},${vss.pass}' label='${app.name}-${timestamp}' />
</target>
<!-- VSS ends -->

<!-- Common Packaging, uploading and mail starts -->
<taskdef name='releasenote' classname='com.note.CreateReleaseNote'/>

<target name='package' description='Package the source code and Contextroot' >
<property name='target.filename' value='${app.name}-${timestamp}.zip'/>
<zip zipfile='${zip.dir}/${app.name}/${target.filename}' >
<fileset dir='${base.dir}'>
<include name='src/**'/>
<include name='ContextRoot/jsp/**'/>
<include name='ContextRoot/WEB-INF/**'/>
<include name='src/META_INF/ejb-jar.xml'/>
<exclude name='ContextRoot/WEB-INF/classes/**'/>
<exclude name='ContextRoot/WEB-INF/lib/**'/>
<exclude name='ContextRoot/jsp/**/*.gif'/>
<exclude name='ContextRoot/jsp/image/**'/>
<exclude name='src/META_INF/**'/>
</fileset>
</zip>
</target>

<target name='upload' description='uploads to FTP'>
<echo message='Uploading file to ftp : ${target.filename}'/>
<ftp server='${ftp.url}' userid='${ftp.username}' password='${ftp.password}' binary='yes' remotedir='${ftp.remotedir}'>
<fileset dir='${zip.dir}/${app.name}'>
<include name='${target.filename}'/>
</fileset>
</ftp>
<echo message=' Release uploaded successfully '/>
</target>

<target name='mail' description='Send release mail' depends='init'>
<echo message='Generating Release Note'/>
<property name='note.name' value='${zip.dir}/${app.name}/ReleaseNote-${timestamp}.txt'/>
<releasenote appName='${app.name}' noteName='${note.name}' releasedFile='ftp://ftp.zensar.com/${ftp.remotedir}/${target.filename}'/>
<mail from='${mail.from}' tolist='${mail.to}' cclist='${mail.cc}' files='${note.name}' user='${mail.user}' password='${mail.pass}' ssl='no' replyto='${mail.reply}' subject='${mail.subject}' mailhost='${mail.host}' mailport='${mail.port}' messagefile='${mail.message}'/> <!--message='${mail.message}'/-->
</target>

<!-- Common Packaging, uploading and mail ends -->
<target name='getsource' description='Update, Tag, Package, Upload, and release latest source code from repository' depends='init'>
<antcall target='${rep.type}' />
<echo message='Update Latest Source code completed'/>
<antcall target='release' />
</target>

<target name='release' description='Package, Upload, and release Mail' depends='package,upload,mail'>
<echo message='**Release of ${app.name} latest source code completed successfully**'/>
</target>

</project>

And the properties file that specifies all the paramters required is...

# Application Name as used in APWORKS.
app=MyProject
app.name=MyProject


###### CVS Path (Optional) ########
cvs.root=:pserver:husain@192.168.1.155:/app/cvs/cvsroot
#CVS Password
cvs.pass=

# The cvs module path of the application required for checkout operation.
cvs.module=DEVELOPMENT/MyProject
######## VSS Details #########
# As specified in VSS server path
vss.server=\\\\servername\\repository\\
vss.path=$/VSS/DEVELOPMENT
vss.ssdir=D:/VSS Client
vss.username=vssuser
vss.pass=vssuserpass

####### Workspace Details ##########
#Workspace location. The code from CVS is updated at ws.dir/app.name
ws.dir=D:/ide/workspace
#Target local as well as backup Directory to store zip files to be uploaded to ftp server. Used as parent dir to app.name dir.
zip.dir=D:/BackUp


######## ftp Details ########
ftp.url=ftp.ind.zensar.com
#Target ftp directory
ftp.remotedir=SOURCE/MyProject
ftp.username=user
#ftp password.
ftp.password=password

##############Mail Settings. Used to mail the release note.
mail.message=mailBody.txt
mail.host=mail.mailserver.com
mail.port=25
# list of mail ids
mail.to=target1@domain.com,cm@domain.com
mail.cc=target3@domain.com,cm2@domain.com

#Senders mail-id
mail.user=myself@domain.com
mail.from=myreplymail@domain.com

#Reply mail-id
mail.reply=myreplymail@domain.com
#Senders mail-id password.
mail.pass=mypassword
mail.subject=Source Code Release [Auto-Generated]

#Logger
log.file=D:/BackUp/buildlog


Resources:
Ant Home Page: http://ant.apache.org
Ant installation Manual: http://ant.apache.org/manual/install.html
Ant Manual: http://ant.apache.org/manual/index.html
A good article on ANT Automation: http://www.onjava.com/pub/a/onjava/2002/07/24/antauto.html"

Tuesday, April 7, 2009

Speed Up Start Menu in Windows XP

Speed Up Start Menu in Windows XP: "The Start Menu can be leisurely when it decides to appear, but you can speed things along by changing it's settings from the Registry:

1.

Start Registry Editor (Regedit.exe).
2.

Locate the following key in the registry:

HKEY_CURRENT_USER/Control Panel/Desktop/

3.

On the Edit menu, click Add Value, and then add the following registry value:

'MenuShowDelay'=0
4.

Close the registry editor.

Another easy way to speed up the display of the Start Menu Items is to turn off the menu shadow:

1.

Right click on an open area of the Desktop.
2.

Select Properties.
3.

Click on the Appearance tab.
4.

Click on the Effects button.
5.

Uncheck Show shadows under menus."

Cool Deepz!

Cool Deepz!: "Billionaire School/College Dropouts
Bill Gates

Are college dropouts more successful than people with good education? It would seem so if you consider that many billionaires are people who dumped college. However, what this hides is the fact that although millions quit studies before completing them, very few of them go on to become rich.
What the list of the super-rich dropouts signifies is that in business, a top degree is not as important as having the right aptitude, attitude, determination and vision.

Here are some dropouts who went on to become billionaires:
William Henry Gates III (1955-), along with Paul Allen, co-founded Microsoft Corporation, the world's largest software maker. Bill Gates, the wealthiest person in the world with an estimated net worth of $480 crores (Rs 211,200 crore!), is probably the best-known college dropout.

Gates attended an exclusive prep school in Seattle, went on to study at Harvard University, then dropped out to pursue software development. As students in the mid-70s, he and Paul Allen wrote the original Altair BASIC interpreter for the Altair 8800, the first commercially successful PC.
In 1975, Micro-Soft - later Microsoft Corporation - was born. Three decades on, Gates has been Number One on the Forbes 400 for over a dozen years. And here's something you probably didn't know: The Bill & Melinda Gates Foundation currently provides 90 per cent of the world budget for the attempted eradication of polio.

Larry Ellison

Lawrence Joseph Ellison (1944-) , co-founder and CEO of Oracle Corporation, founded his company in 1977 with a sum of $2,000. Once a school dropout, he is now, according to Forbes, one of the richest people in America with a net worth of around $184 crores. The figure also makes him the ninth richest in the world.

As a young man, Ellison worked for the Ampex Corporation, where one of his projects was a database for the CIA. He called it Oracle, a name he was to reuse years later for the company that made him famous.
Interestingly, the organisation' s initial release was Oracle 2. The number supposedly implied that all bugs had been eliminated from an earlier version.

Ellison is quite a colourful man, and has long dabbled in all kinds of things. Want to learn more? Try his biography, The Difference Between God and Larry Ellison.

Dhirubhai Ambani

Dhirajlal Hirachand Ambani (1932-2002) was born into the family of a schoolteacher. It was a family of modest means. When he turned 16, Dhirubhai moved to Aden, working first as a gas-station attendant, then as a clerk in an oil company.

He returned to India at 26, starting a business with a meagre capital of $375. By the time of his demise, his company - Reliance Industries Ltd - had grown to become an empire, with an estimated annual turnover of $120 crores!

Dhirubhai was, in his lifetime, conferred the Indian Entrepreneur of the 20th Century Award by the Federation of Indian Chambers of Commerce and Industry. A Times of India poll in the year 2000 also voted him one of the biggest creators of wealth in this century.

Dhirubhai's is not just the usual rags-to-riches story. He will be remembered as the one who rewrote Indian corporate history and built a truly global corporate group. He is also credited with having single-handedly breathed life into the Indian stock markets and bringing in thousands of investors to the bourses.

Steve Jobs

Steven Paul Jobs (1955-) and Apple Computer are names that have long gone together.

Born in the United States to an unknown Egyptian-Arab father, Jobs was adopted soon after birth. After graduating high school, he enrolled in Reed College, dropping out after one semester.

In 1976, 21-year-old Jobs and 26-year old Steve Wozniak founded Apple Computer Co. in the family garage. Jobs revolutionised the industry by popularising the concept of home computers.

By 1984, the Macintosh was introduced. He had an influential role in the building of the World-Wide Web, and also happens to be Chairman and CEO of Pixar Animation Studios.

Today, with the iPod, Apple is bigger than ever. Incidentally, Jobs worked for several years at an annual salary of $1. It got him a listing in the Guinness Book as `Lowest Paid Chief Executive Officer.' He was once gifted a $9 crores jet by the company though. And his net worth? More than $3 billion.

Michael Dell

Michael Saul Dell (1965- ) joined the University of Texas at Austin with the intention of becoming a physician. While studying there, he started a computer company in his dormitory, calling it PC's Limited. By the time he turned 19, it had notched up enough success to prompt Dell to dropout.

In 1987, PC's Limited changed its name to Dell Computer Corporation. By 2003, Dell, Inc. was the world's most profitable PC manufacturer.

Dell has won more than his fair share of accolades, including Man of the Year from PC Magazine and EM>CEO of the Year from Financial World . Forbes, in 2005, lists him as the 18th richest in the world with a net worth of around $1600 Crores. Not bad for just another dropout.

Subhash Chandra Goel

Here's something not many people know about Subhash Chandra Goel : The Zee chairman dropped out after standard 12.

Subhash Chandra started his own vegetable oils unit at 19. It was, in a manner of speaking, his first job. Years later, a casual visit to a friend at Doordarshan gave him the idea of starting his own broadcasting company. We all know how that story ran.

Chandra knew nothing about programming, distribution or film rights. What he did understand quite well was the Indian sensibility though. Funded by UK businessmen, Zee came into being as India's first satellite TV network.
Today, it reaches 320 lakhs homes, connecting with 20 crores people in South Asia alone. The network also covers Asians in America, the Middle East, Europe, Australia and Africa, making this dropout a very rich one."

Types of Server

Types of Server: "A Server is a computer or device on a network that manages network resources. For example, a file server is a computer and storage device dedicated to storing files Any user on the network can store files on the server. A print server is a computer that manages one or more printers and a network server is a computer that manages network traffic.

Servers are often dedicated, meaning that they perform no other tasks besides their server tasks. On multiprocessing operating systems however, a single computer can execute several programs at once. A server in this case could refer to the program that is managing resources rather than the entire computer.

What is Server Platform?
A term often used synonymously with operating system. A platform is the underlying hardware or software for a system and is thus the engine that drives the server.

Server types:

Application Servers
Sometimes referred to as a type of middleware, application servers occupy a large chunk of computing territory between database servers and the end user, and they often connect the two.

Middleware is a software that connects two otherwise separate applications For example, there are a number of middleware products that link a database system to a Web server This allows users to request data from the database using forms displayed on a Web browser and it enables the Web server to return dynamic Web pages based on the user's requests and profile.

The term middleware is used to describe separate products that serve as the glue between two applications. It is, therefore, distinct from import and export features that may be built into one of the applications. Middleware is sometimes called plumbing because it connects two sides of an application and passes data between them. Common middleware categories include:


* TP monitors
* DCE environments
* RPC systems
* Object Request Brokers (ORBs)
* Database access systems
* Message Passing


Audio/Video Servers
Audio/Video servers bring multimedia capabilities to Web sites by enabling them to broadcast streaming multimedia content. Streaming is a technique for transferring data such that it can be processed as a steady and continuous stream. Streaming technologies are becoming increasingly important with the growth of the Internet because most users do not have fast enough access to download large multimedia files quickly. With streaming, the client browser or plug-in can starts displaying the data before the entire file has been transmitted.

For streaming to work, the client side receiving the data must be able to collect the data and send it as a steady stream to the application that is processing the data and converting it to sound or pictures. This means that if the streaming client receives the data more quickly than required, it needs to save the excess data in a buffer If the data doesn't come quickly enough, however, the presentation of the data will not be smooth.

There are a number of competing streaming technologies emerging. For audio data on the Internet, the de facto standard is Progressive Network's RealAudio.

Chat Servers
Chat servers enable a large number of users to exchange information in an environment similar to Internet newsgroups that offer real-time discussion capabilities. Real time means occurring immediately. The term is used to describe a number of different computer features. For example, real-time operating systems are systems that respond to input immediately. They are used for such tasks as navigation, in which the computer must react to a steady flow of new information without interruption. Most general-purpose operating systems are not real-time because they can take a few seconds, or even minutes, to react.

Real time can also refer to events simulated by a computer at the same speed that they would occur in real life. In graphics animation, for example, a real-time program would display objects moving across the screen at the same speed that they would actually move.

Fax Servers
A fax server is an ideal solution for organizations looking to reduce incoming and outgoing telephone resources but that need to fax actual documents.

FTP Servers
One of the oldest of the Internet services, File Transfer Protocol makes it possible to move one or more files securely between computers while providing file security and organization as well as transfer control.

Groupware Servers
A GroupWare server is software designed to enable users to collaborate, regardless of location, via the Internet or a corporate Intranet and to work together in a virtual atmosphere.

IRC Servers
An option for those seeking real-time capabilities, Internet Relay Chat consists of various separate networks (or 'nets') of servers that allow users to connect to each other via an IRC network.

List Servers
List servers offer a way to better manage mailing lists, whether they are interactive discussions open to the public or one-way lists that deliver announcements, newsletters, or advertising.

Mail Servers
Almost as ubiquitous and crucial as Web servers, mail servers move and store mail over corporate networks via LANs and WANs and across the Internet.

News Servers
News servers act as a distribution and delivery source for the thousands of public news groups currently accessible over the USENET news network. USENET is a worldwide bulletin board system that can be accessed through the Internet or through many online services The USENET contains more than 14,000 forums called newsgroups that cover every imaginable interest group. It is used daily by millions of people around the world.

Proxy Servers
Proxy servers sit between a client program typically a Web browser and an external server (typically another server on the Web) to filter requests, improve performance, and share connections.

Telnet Servers
A Telnet server enables users to log on to a host computer and perform tasks as if they're working on the remote computer itself.

Web Servers
At its core, a Web server serves static content to a Web browser by loading a file from a disk and serving it across the network to a user's Web browser. The browser and server talking to each other using HTTP mediate this entire exchange."

Thursday, March 26, 2009

TIOBE Software: Tiobe Index

TIOBE Software: Tiobe Index:
TIOBE Programming Community Index for March 2009
March Headline: All time high for JavaScript, all time low for Perl

The TIOBE Programming Community index gives an indication of the popularity of programming languages. The index is updated once a month. The ratings are based on the number of skilled engineers world-wide, courses and third party vendors. The popular search engines Google, MSN, Yahoo!, and YouTube are used to calculate the ratings. Observe that the TIOBE index is not about the best programming language or the language in which most lines of code have been written."

Thursday, March 19, 2009

Learning Binary...

Learning Binary...: "
Introduction

We’ve all seen binary code. We’ve come to think of them as a bunch of ones and zeroes in long strings… 010010101010101001101011

But these ones and zeroes can also represent decimal numbers. First off, I will show you how to read these numbers as the decimal numbers we’re used to in our daily life. Then, I will show you how to use those numbers and your keypad to translate them into text. Note that your computer doesn’t use the decimal system, so technically, when it converts binary to text, it doesn’t go through the process I will show you. This is just a divertive way of explaining you how the binary system works.

The Binary System

Basics

Let’s think of the example above as empty slots:


First off, you read binary from right-to-left. It’s just the way it’s designed. The first slot from the right represents a value of one, the second from the right a value of two, the third from the right a value of four, the fourth from the right a value of eight, the fifth from the right a value of sixteen, and the cycle continues by multiples of 2. This will never change.


By putting a 1 or a 0 in those slots you are either saying you want to corresponding value that’s attached to that slot or you don’t. A 1 means yes, and a 0 means no. For example, putting a zero in the first slot from the right, but a 1 in the second slot from the right means you want a two, but not a one:

-------------------------------------------------

1 0

-------------------------------------------------

As such, the number above equals to a decimal value of two.


As an example, let’s say you want to represent eight in binary form. Well, thinking about the slots, you want the first slot to be 0 because you don’t want a one, you want the second slot to also be 0 because you don’t want a two, you want the third slot to also to be 0 because you don’t want a four, but you want the fifth slot to be 1 because you want a value of eight. As such, eight in binary form is:

-------------------------------------------------

1 0 0 0 (or simply 1000 without those underlines)

-------------------------------------------------

Now it is important to note that the amount of zeroes that precede the first value of one from the left is unimportant. So for example:

-------------------------------------------------

1 0 0 0 is the same as 0 0 0 1 0 0 0 (1000 = 000100)

-------------------------------------------------

To get it cleared up, here’s another example:

-------------------------------------------------

0 1 is the same as 1

-------------------------------------------------


Exercises

Question: What do the following equal in decimal terms?

a) 100

b) 000100

c) 100000

d) 0010

Answers:

a) 4

b) 4

c) 32

d) 2


More Binary!

If you got the answers above right, then you pretty much understand the basics of binary. Let’s now understand how to get the corresponding decimal values to the numbers which are not multiples of 2.


To get the total value of a binary number, add the values corresponding to each slot. So, for example, three in binary would be:

----------------------------------------------------

11

----------------------------------------------------

The above corresponds to three because if you add the total values of all the slots, that is to say a one from the slot to the right, and a two from the second slot to the right, then it equals three.


As another example, let’s say you want to represent 5 in binary terms. Then you would need a value of one to be added to a value of four, and you would not want a value of two:

---------------------------------------------------

101 [Reading from the right: 1(one) + 0(two) + 1(four) = five]

---------------------------------------------------

Here’s an additional example:

---------------------------------------------------

001011 [Reading from the right: 1(one) + 1(two) + 0(four)
+ 1(eight) + 0(sixteen) + 0(thirty-two) = eleven)

---------------------------------------------------

Exercises

Question: What do the following equal in decimal terms?

a) 11011

b) 110

c) 010101

d) 10110

Answers:

a) 27

b) 6

c) 21

d) 22


If you got the above questions correct [without cheating], then you essentially understand the binary system. Understanding the binary system was the hard part. What follows is pretty easy.


Converting Binary to ASCII (Text)

Basics

ASCII is essentially the letters, numbers and symbols that are stored in our computers through the use of fonts. When the keyboard relays the buttons you pressed, it sends in a code which is then converted to the ASCII equivalent of “k” or “5” or whatever key you pressed.

Here’s an example of a message “hidden” in binary text:

---------------------------------------------------------

0100100001100101011011000110110001101111

---------------------------------------------------------

Now there are only so many letters, numbers and symbols stored for ASCII. Having sets of 8 digits for their binary equivalent is more than enough to represent all of these letters and the like. As such, all strings that represent text like in the above are separated into bits of 8 for simplicity:


----------------------------------------------------------

01001000 01100101 01101100 01101100 01101111

----------------------------------------------------------

Okay, so our example message was separated into 8 digit strings. The decimal value for each of these strings in the example was calculated for you.


----------------------------------------------------------

01001000 = 72
01100101 = 101
01101100 = 108
01101100 = 108
01101111 = 111

----------------------------------------------------------

The result was 72,101,108,108,111. Now, there is something called the ASCII table. It essentially corresponds to the binary numbers from yore to the equivalent letters/symbols/numbers. But since we found the decimal values of these binary strings, we can use a major shortcut.


By pressing ALT + [The Number], you will get the ASCII equivalent of that number. For example, by pressing the ALT key and at then (while keeping it down) the numbers 72 in any text editor, you will get the corresponding “H” to show up.


Let’s do so for the entire example message:

-----------------------------------------------------

72 = H
101 = e
108 = l
108 = l
111 = o

-----------------------------------------------------

So the entire “hidden” message translates to “Hello”.

Excercise

Question: Decode the following message

01000011011011110110111001100111011100100110000101 11010001110
10101101100011000010111010001101001011011110110111 00111001100100001


Hint: The first step on your way to decoding the message (separated into bytes for you)

---------------------------------------------------------

01000011 01101111 01101110 01100111 01110010
01100001 01110100 01110101 01101100 01100001
01110100 01101001 01101111 01101110 01110011
00100001

---------------------------------------------------------"

Thursday, March 12, 2009

Virtualization & Cloud Computing Providers and Contributors

Virtualization & Cloud Computing Providers and Contributors : "Virtualization Technology Providers and Contributors in 2008-2009
The following companies are among the providers and contributors of Virtualization technology: 3PAR, Accellion, Acronis, Actional, Active Endpoints, ActiveGrid, activePDF, ActiveServers, ActiveState, Actuate, Adaptec, Agile Software, AGiLiENCE, Agilysys, Akorri, AlachiSoft, Alter Logic, Altor Networks, Altova, AMD, AMDAHL, Amentra, Amyuni, anacubis, Apani, APC, Appcelerator, AppSense, AppStream, Array Networks, Ascential, Astaro, Attune Systems, Autodesk, AutoVirt, Availl, Avanade, Azul Systems, Barracuda Networks, BEA Systems, B-hive, Black Duck Software, Blackbaud, Blade Network Technologies, Blue Coat, Blue Lane, BlueArc, BlueNote Networks, BluePheonix Solutions, BMC Software, Borland, Bristol Technology, Brix Networks, BroadVision, Brocade, Burton Group, Business Objects, CA, CalAmp, Cassatt, Cast Iron Systems, Catbird, Cayenne Technologies, Ceedo Technologies, Cenzic, Certeon, CiRBA, Cisco Systems, Cision, Citrix Systems, ClearApp, ClearCube Technology, CollabNet, Compass America, Composite Software, Compugen, Compuware, Configuresoft, Continuity Software, Coraid, Courion, Coyote Point Systems, Crescendo Networks, CSC, DataCore, DataSynapse, Dell, Desktone, Digipede Technologies, Double-Take Software, Ecora Software, EDS, eG Innovations, Egenera, Elastra Corporation, Electric Cloud, Embotics, EMC Corporation, Emulex, Endeavors Technology, Enigmatic Corporation, Enterprise Management Associates, Entuity, EqualLogic, Ericom Software, ESRI, EVault, eXludus Technologies, F5 Networks, FalconStor, FastScale Technology, Foedus, Force10 Networks, Fortisphere, Forum Systems, Fujitsu, GemStone Systems, Getronics, GlassHouse, Green Hills Software, Grid Dynamics, GridGain Systems, GT Software, Hitachi, HP, Hyper9, Hyperic, IBM, ICEsoft, IGEL Technology, Illumita, ILOG, IMEX Research, Information Builders, Ingres, InstallFree, Integrien, Intel, Intellium, International Computerware, iTKO LISA, JBoss, Juniper, KACE, Kidaro, LeftHand Networks, Leostream, Lifeboat Distribution, Liquid Computing Corporation, Liquid Technology, Lynux Works, Mainline, ManageIQ, Managed Methods, ManageSoft, Marathon Technologies, McAfee, Mellanox Technologies, Microsoft, Mid-Atlantic Computers, Mindbridge Software, Mindreef, MKS, MonoSphere, Motorola, MQSoftware, mySoftIT, NASTEL, Ncomputing, NEC, Neocleus, NeoPath Networks, Neoware, NetApp, Netegrity, Neterion, Netuitive, Neverfail, Nexaweb, NextAxiom, Nimbus, Nimsoft, Niyuta, NoMachine, Novell, ONStor, Opalis Software, Open Kernel Labs, OpenSpan, OPNET Technologies, Optaros, OpTier, Oracle, Pano Logic, Parallels, Parasoft, Perforce Software, PHD Technologies, Phoenix Technologies, Phurnace Software, Pillar Data Systems, PlateSpin/Novell, Progress Software, Prolifics, ProSync Technology, Provision Networks, QLogic, Quest Software, Racemi, Raritan, Raxco Software, Red Hat, Reflex Security, Resolution Enterprises, RingCube Technologies, Riverbed Technology, Rogue Wave Software, RSA Security, Sagnet Solutions, SanDisk Corporation, SAP, SAVVIS, ScaleMP, Scalent Systems, Seanodes, Secure Command, Secure Computing, Sentillion, Shavlik Technologies, ServInt Internet Services, Silpion IT Solutions, SIMtone, Skytap, Skyway Software, Software AG, Sonasoft, SourceGear, Splunk, StackSafe, SteelEye Technology, StillSecure, StoneFly, Stonesoft, Stoneware, StoreVault, StrikeIron, STT WebOS, Sun Microsystems, SunGard, Supermicro Computer, Surgient, SWsoft, Sybase, Symantec, Systar, TBD Networks, Tenfold, TheInfoPro, Thinstall, Third Brigade, TIBCO Software, Tidal Software, Tideway Systems, TOA Solutions, TRANGO Virtual Processors, Trend Micro, Tresys Technology, Trigence, Tripwire, Ulteo, Unisys, United Devices, VaST Systems, VDIworks, VeeAm Software, Verari Systems, Verio, VeriSign, Vicom Computer Services, VirtenSys, Virtera, Virtual Iron, VirtualLogix, Virtugo Software, Virtutech, VisionCore, Vizioncore, VKernel, VMLogix, vmSight, VMware, Vordel, vThere-Sentillion, Vyatta, WaveMaker, Web Age Solutions, WSO2, Wyse Technology, XDS, XenoCode, Xiotech, xkoto, Xsigo Systems, Zenith Optemedia, Zeus Technology.

Cloud Computing Technology Providers and Contributors in 2008-2009
The following companies are among the providers and contributors of Cloud Computing technology: 10Gen, 3Leaf, 3Tera, Absolute Performance, Accenture, Akamai, Amazon.com, Appirio, Appistry, Areti Internet, Boomi, Box.net, Canaan Partners, Cloud9 Analytics, CloudWorks, CNI Systems, CohesiveFT, CSRware, DataDirect, Dell, DNAmail, eBay, Elastra, EMC, EngineYard, Enki Consulting, Enomaly, Excelian, Flexiscale, Fortress ITX, Forum, GigaSpaces, GoGrid, Google, HP, IBM, IBRIX, Joyent, JumpBox, Layered Technologies, Level 3 Communications, Linxter, LongJump, MDV, Microsoft, Moka5 (MokaFive), Mosso, NewServers, Nirvanix, Ocarina Networks, OpSource, Panorama Software, Peer1 Networks, Pervasive Software, Platform Computing, PLX Technology, Qlayer, Rackspace, RampRate, Red Hat, RightScale, rPath, Salesforce.com, Saugatuck Technology, ServePath, Skills Matter, Skytap, SnapLogic, SOASTA, Sun Microsystems, Symphoniq, Symphony Services, Tap In Systems, Teneros, Terremark, Transitive Corporation, Univa UD, Verizon Business, Vertica, VMware, XCalibre, Zabovo.com, ZOHO and Zuora."

Friday, March 6, 2009

Jumper: JasperReport Export to Excel Snippet code


Jumper: JasperReport Export to Excel Snippet code
:
"Sample code that will export JasperReport(.jasper) to excel, pay attention to the bold code
that's all the tricks. The sample servlet will accept two parameter the date and the name of the report.


/*
* JasperToExcel.java
*/

import bean.report.RowStatistics;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

/**
*
* @author amontejo
* @version
*/
public class JasperToExcel extends HttpServlet {

public static final String REPORT_DIRECTORY = '/reports';

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String reportName = request.getParameter('reportname');
String selectedyear = request.getParameter('SelectedYear');
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream('/' + REPORT_DIRECTORY + '/' + reportName + '.jasper');

ServletContext context = this.getServletConfig().getServletContext();
JasperPrint jasperPrint = null;
HashMap parameterMap = new HashMap();

parameterMap.put('parayear', new String(selectedyear));

try {
ServletOutputStream servletOutputStream = response.getOutputStream();
JRDataSource dataSource = createReportDataSource(request, selectedyear, reportName);
jasperPrint = JasperFillManager.fillReport(reportStream, new HashMap(), dataSource);
generateXLSOutput(reportName, jasperPrint, response);
} catch (Exception e) {
}
}

private String tagreport(String string) {
java.util.Calendar calendar = java.util.Calendar.getInstance();
return string + calendar.get(calendar.MONTH) + calendar.get(calendar.DAY_OF_MONTH) + calendar.get(calendar.YEAR);
}

private void generateXLSOutput(String reportname,
JasperPrint jasperPrint,
HttpServletResponse resp)
throws IOException, JRException {
String reportfilename = tagreport(reportname) + '.xls';
JExcelApiExporter exporterXLS = new JExcelApiExporter();

exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, resp.getOutputStream());
resp.setHeader('Content-Disposition', 'inline;filename=' + reportfilename);
resp.setContentType('application/vnd.ms-excel');

exporterXLS.exportReport();
}


//
/** Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Returns a short description of the servlet.
*/
public String getServletInfo() {
return 'Short description';
}
//
}"

Wednesday, February 25, 2009

jQuery plugin: Add2Cart Example

I want to be free » Blog Archive » jQuery plugin: Add2Cart: "
This plugin implements visual effect of adding something to cart (busket). Visually it’s similar to Microsoft Word post-save visual effect, when a gray rectangular of page moves down to the toolbar.

Example of usage:

<input type='button' value='Add to cart'
onclick='$.add2cart( 'product1_id', 'cart_img_id' )' />

You can try it out at demo page."

32 tips to speed up your queries

32 tips to speed up your queries:
1. Use persistent connections to the database to avoid connection overhead.
2. Check all tables have PRIMARY KEYs on columns with high cardinality (many rows match the key value). Well,`gender` column has low cardinality (selectivity), unique user id column has high one and is a good candidate to become a primary key.
3. All references between different tables should usually be done with indices (which also means they must have identical data types so that joins based on the corresponding columns will be faster). Also check that fields that you often need to search in (appear frequently in WHERE, ORDER BY or GROUP BY clauses) have indices, but don’t add too many: the worst thing you can do is to add an index on every column of a table :) (I haven’t seen a table with more than 5 indices for a table, even 20-30 columns big). If you never refer to a column in comparisons, there’s no need to index it.
4. Using simpler permissions when you issue GRANT statements enables MySQL to reduce permission-checking overhead when clients execute statements.
5. Use less RAM per row by declaring columns only as large as they need to be to hold the values stored in them.
6. Use leftmost index prefix — in MySQL you can define index on several columns so that left part of that index can be used a separate one so that you need less indices.
7. When your index consists of many columns, why not to create a hash column which is short, reasonably unique, and indexed? Then your query will look like:

SELECT *
FROM table
WHERE hash_column = MD5( CONCAT(col1, col2) )
AND col1='aaa' AND col2='bbb';

8. Consider running ANALYZE TABLE (or myisamchk --analyze from command line) on a table after it has been loaded with data to help MySQL better optimize queries.
9. Use CHAR type when possible (instead of VARCHAR, BLOB or TEXT) — when values of a column have constant length: MD5-hash (32 symbols), ICAO or IATA airport code (4 and 3 symbols), BIC bank code (3 symbols), etc. Data in CHAR columns can be found faster rather than in variable length data types columns.
10. Don’t split a table if you just have too many columns. In accessing a row, the biggest performance hit is the disk seek needed to find the first byte of the row.
11. A column must be declared as NOT NULL if it really is — thus you speed up table traversing a bit.
12. If you usually retrieve rows in the same order like expr1, expr2, ..., make ALTER TABLE ... ORDER BY expr1, expr2, ... to optimize the table.
13. Don’t use PHP loop to fetch rows from database one by one just because you can ;) — use IN instead, e.g.

SELECT *
FROM `table`
WHERE `id` IN (1,7,13,42);

14. Use column default value, and insert only those values that differs from the default. This reduces the query parsing time.
15. Use INSERT DELAYED or INSERT LOW_PRIORITY (for MyISAM) to write to your change log table. Also, if it’s MyISAM, you can add DELAY_KEY_WRITE=1 option — this makes index updates faster because they are not flushed to disk until the table is closed
16. Think of storing users sessions data (or any other non-critical data) in MEMORY table — it’s very fast.
17. For your web application, images and other binary assets should normally be stored as files. That is, store only a reference to the file rather than the file itself in the database.
18. If you have to store big amounts of textual data, consider using BLOB column to contain compressed data (MySQL’s COMPRESS() seems to be slow, so gzipping at PHP side may help) and decompressing the contents at application server side. Anyway, it must be benchmarked.
19. If you often need to calculate COUNT or SUM based on information from a lot of rows (articles rating, poll votes, user registrations count, etc.), it makes sense to create a separate table and update the counter in real time, which is much faster. If you need to collect statistics from huge log tables, take advantage of using a summary table instead of scanning the entire log table every time.
20. Don’t use REPLACE (which is DELETE+INSERT and wastes ids): use INSERT … ON DUPLICATE KEY UPDATE instead (i.e. it’s INSERT + UPDATE if conflict takes place). The same technique can be used when you need first make a SELECT to find out if data is already in database, and then run either INSERT or UPDATE. Why to choose yourself — rely on database side.
21. Tune MySQL caching: allocate enough memory for the buffer (e.g. SET GLOBAL query_cache_size = 1000000) and define query_cache_min_res_unit depending on average query resultset size.
22. Divide complex queries into several simpler ones — they have more chances to be cached, so will be quicker.
23. Group several similar INSERTs in one long INSERT with multiple VALUES lists to insert several rows at a time: quiry will be quicker due to fact that connection + sending + parsing a query takes 5-7 times of actual data insertion (depending on row size). If that is not possible, use START TRANSACTION and COMMIT, if your database is InnoDB, otherwise use LOCK TABLES — this benefits performance because the index buffer is flushed to disk only once, after all INSERT statements have completed; in this case unlock your tables each 1000 rows or so to allow other threads access to the table.
24. When loading a table from a text file, use LOAD DATA INFILE (or my tool for that), it’s 20-100 times faster.
25. Log slow queries on your dev/beta environment and investigate them. This way you can catch queries which execution time is high, those that don’t use indexes, and also — slow administrative statements (like OPTIMIZE TABLE and ANALYZE TABLE)
26. Tune your database server parameters: for example, increase buffers size.
27. If you have lots of DELETEs in your application, or updates of dynamic format rows (if you have VARCHAR, BLOB or TEXT column, the row has dynamic format) of your MyISAM table to a longer total length (which may split the row), schedule running OPTIMIZE TABLE query every weekend by crond. Thus you make the defragmentation, which means more speed of queries. If you don’t use replication, add LOCAL keyword to make it faster.
28. Don’t use ORDER BY RAND() to fetch several random rows. Fetch 10-20 entries (last by time added or ID) and make array_random() on PHP side. There are also other solutions.
29. Consider avoiding using of HAVING clause — it’s rather slow.
30. In most cases, a DISTINCT clause can be considered as a special case of GROUP BY; so the optimizations applicable to GROUP BY queries can be also applied to queries with a DISTINCT clause. Also, if you use DISTINCT, try to use LIMIT (MySQL stops as soon as it finds row_count unique rows) and avoid ORDER BY (it requires a temporary table in many cases).
31. When I read “Building scalable web sites”, I found that it worth sometimes to de-normalise some tables (Flickr does this), i.e. duplicate some data in several tables to avoid JOINs which are expensive. You can support data integrity with foreign keys or triggers.
32. If you want to test a specific MySQL function or expression, use BENCHMARK function to do that.

Some of these hints are unapplicable if you use a framework because direct queries are uninvited guests in the case: focus on competent database optimization — tune indexes and server parameters.

More on queries optimization:

* Optimizing SELECT and Other Statements
* Optimizing for Query Speed (more about good index creating practices).
* ORDER BY RAND()"

Tuesday, February 17, 2009

Differences Between Parameters and Arguments

Differences Between Parameters and Arguments:

In most cases, a procedure must have some information about the circumstances in which it has been called. A procedure that performs repeated or shared tasks uses different information for each call. This information consists of variables, constants, and expressions that you pass to the procedure when you call it.

To communicate this information to the procedure, the procedure defines a parameter, and the calling code passes an argument to that parameter.
You can think of the parameter as a parking space and the argument as an automobile. Just as different automobiles can park in a parking space at different times, the calling code can pass a different argument to the same parameter every time that it calls the procedure.

Parameters

A parameter represents a value that the procedure expects you to pass when you call it. The procedure's declaration defines its parameters.

When you define a Function or Sub procedure, you specify a parameter list in parentheses immediately following the procedure name. For each parameter, you specify a name, a data type, and a passing mechanism (ByVal or ByRef). You can also indicate that a parameter is optional. This means that the calling code does not have to pass a value for it.

The name of each parameter serves as a local variable in the procedure. You use the parameter name the same way you use any other variable.

Arguments

An argument represents the value that you pass to a procedure parameter when you call the procedure. The calling code supplies the arguments when it calls the procedure.

When you call a Function or Sub procedure, you include an argument list in parentheses immediately following the procedure name. Each argument corresponds to the parameter in the same position in the list.

In contrast to parameter definition, arguments do not have names. Each argument is an expression, which can contain zero or more variables, constants, and literals. The data type of the evaluated expression should typically match the data type defined for the corresponding parameter, and in any case it must be convertible to the parameter type."

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming:
"Java is designed around the principles of object-oriented programming. To truly master Java you must understand the theory behind objects. This article is an introduction to object-oriented programming outlining what objects are, their state and behaviors and how they combine to enforce data encapsulation.

What Is Object-Oriented Programming?

To put it simply, object-oriented programming focuses on data before anything else. How data is modeled and manipulated through the use of objects is fundamental to any object-oriented program.

What Are Objects?

If you look around you, you will see objects everywhere. Perhaps right now you are drinking coffee. The coffee mug is an object, the coffee inside the mug is an object, even the coaster it's sitting on is one too. Object-oriented programming realizes that if we're building an application it's likely that we will be trying to represent the real world. This can be done by using objects.

Let's look at an example. Imagine you want to build a Java application to keep track of all your books. The first thing to consider in object-oriented programming is the data the application will be dealing with. What will the data be about? Books.

We've found our first object type - a book. Our first task is to design an object that will let us store and manipulate data about a book. In Java, the design of an object is done by creating a class. For programmers, a class is what a blueprint of a building is to an architect, it lets us define what data is going to be stored in the object, how it can be accessed and modified, and what actions can be performed on it. And, just like a builder can build more than more building using a blueprint, our programs can create more than one object from a class. In Java, each new object that is created is called an instance of the class.

Let's go back to the example. Imagine you now have a book class in your book tracking application. Bob from next door gives you a new book for your birthday. When you add the book to the tracking application a new instance of the book class is created. It is used to store data about the book. If you then get a book from your father and store it in the application, the same process happens again. Each book object created will contain data about different books.

Maybe you frequently lend your books out to friends. How do we define them in the application? Yes, you guessed it, Bob from next door becomes an object too. Except we wouldn't design a Bob object type, we would want to generalize what Bob represents to make the object as useful as possible. After all there is bound to be more than one person you lend your books to. Therefore we create a person class. The tracking application can then create a new instance of a person class and fill it with data about Bob.
What Is the State of an Object?

Every object has a state. That is, at any point in time it can be described from the data it contains. Let's look at Bob from next door again. Let's say we designed our person class to store the following data about a person: their name, hair color, height, weight, and address. When a new person object is created and stores data about Bob, those properties go together to make Bob's state. For instance today, Bob might have brown hair, be 205 pounds, and live next door. Tomorrow, Bob might have brown hair, be 200 pounds and have moved to a new address across town.

If we update the data in Bob's person object to reflect his new weight and address we have changed the state of the object. In Java, the state of an object is held in fields. In the above example, we would have five fields in the person class; name, hair color, height, weight, and address.
What Is the Behavior of an Object?

Every object has behaviors. That is, an object has a certain set of actions that it can perform. Let's go back to our very first object type – a book. Surely a book doesn't perform any actions? Let's say our book tracking application is being made for a library. There a book has lots of actions, it can be checked out, checked in, reclassified, lost, and so on. In Java, behaviors of an object are written in methods. If a behavior of an object needs to be performed, the corresponding method is called.

Let's go back to the example once more. Our booking tracking application has been adopted by the library and we have defined a check out method in our book class. We have also added a field called borrower to keep track of who has the book. The check out method is written so that it updates the borrower field with the name of the person who has the book. Bob from next door goes to the library and checks out a book. The state of the book object is updated to reflect that Bob now has the book.
What Is Data Encapsulation?

One of the key concepts of object-oriented programming is that to modify an object's state, one of the object's behaviors must be used. Or to put it another way, to modify the data in one of the object's fields, one of its methods must be called. This is called data encapsulation.

By enforcing the idea of data encapsulation on objects we hide the details of how the data is stored. We want objects to be as independent of each other as possible. An object holds data and the ability to manipulate it all in one place. This makes it is easy for us to use that object in more than one Java application. There's no reason why we couldn't take our book class and add it to another application that might also want to hold data about books.

If you want to put some of this theory into practice, you can join me in creating a Book class."