Wednesday, November 17, 2010

Ajax example

http://www.headfirstlabs.com/books/hrajax/chapter01/

function getBoardsSold() {
createRequest();
var url = "getUpdatedBoardSales-ajax.php";
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}

function updatePage() {
if (request.readyState == 4) {
if(request.status ==200) {
var somevariable = request.responseText;
document.getElementById("Id").value = somevariable;
...
}
}
}
<--input --value="Show Me the Money" onclick="getBoardsSold();" type="button">

(more event handler)
<--input type="text" name="abc" onChange="getBoardsSold();" >
<--input type="text" name="abc" onFocus="foo();" >
<--input type="text" name="abc" onBlur="foo();" >

<--textarea name ="Id" id = "id" >

Any JavaScript in your web page that is not in a function gets run statically.
if (request == null) check out of function, will have the users know right away. (page 92)

Friday, November 5, 2010

Ajax

1. Asynchronous applications make requests using a JavaScript Object, and not a form submit
2. your request and response are handled by the web browser, not directly by your JavaScript code.
3. Once the web browser gets a response to your asynchronous request, it will 'call back' your JavaScript with the server's response.

Tuesday, September 14, 2010

python help pages

python list : http://effbot.org/zone/python-list.htm

rollback deployment: http://benosullivan.co.uk/internet/google-app-engine/google-app-engine-fix-another-transaction-by-user-acct-is-already-in-progress/

sample rollback:
"C:\Python27\python" "C:\Program Files (x86)\Google\google_appengine\appcfg.py" -verbose --no_cookies -

-email=XXX@gmail.com --passin rollback "C:\\Documents and Settings\\kli\\My Documents\\Python\\helloworld"

Wednesday, September 1, 2010

some java interview questions(1)

http://www.interview-questions-java.com/java-questions/interview-questions-on-java


What if the main method is declared as private?

The program compiles properly but at runtime it will give “Main method not public.” message.


What are the differences between == and .equals() ?

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.


What is the difference between final, finally and finalize? What do you understand by the java final keyword?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.


When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?

Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.

What is reflection API? How are they implemented?

Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.


Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why

Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.

What is phantom memory?

Phantom memory is false memory. Memory that does not exist in reality.

Can a method be static and synchronized?

A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:

synchronized(XYZ.class) {

}

Garbage collection

Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.

A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists.

In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic process and can’t be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc().

Garbage collector is a daemon thread

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the object gets garbage collected. For example, closing an opened database Connection.

java options for Garbage collection

JDK 1.4.1 adds some new options to control garbage collection.

The options for server applications should be:

-server -Xms(size) -Xmx(size) -XX:+UseParallelGC -XX:UseAdaptiveSizePolicy
where (size) is the amount of memory your application will use (128m is 128 megabytes, 128 is 128 bytes). These options select the parallel scavenge collector for young generation garbage, and the mark-sweep-compact collector for old generation garbage. Old generation collection is still single threaded but the mark-sweep-compact collector is very efficient.

The options for applications where pauses are undesirable should be:

-server -Xms(size) -Xmx(size) -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:SurvivorRatio=2 -XX:NewRatio=8
where (size) is the amount of memory your application will use (128m is 128 megabytes, 128 is 128 bytes). These options select the parallel copying collector for the new generation, and the concurrent mark-sweep collector for the old generation. The new generation collection uses one thread for each processor on the machine. 1/8 of the memory is used for the new generation, and 7/8 for the old generation. The new generation memory is broken into three pieces, 1/16 of the memory is the eden where new objects are created, and the rest of the new generation is stored in two semi spaces.

Monday, August 30, 2010

Lazy initialization

http://www.javapractices.com/topic/TopicAction.do?Id=34

Lazy initialization of a field may be useful when both of these conditions are true :

* the field is particularly expensive to create
* the field has an optional character, in the sense that it may or may not be of interest to the caller

In this case, the construction of such a field may be deferred till the moment it is actually required. This increases performance by avoiding unnecessary creation of expensive objects.

Immutable objects

http://www.javapractices.com/topic/TopicAction.do?Id=29

Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.

Immutable objects greatly simplify your program, since they :

* are simple to construct, test, and use
* are automatically thread-safe and have no synchronization issues
* do not need a copy constructor
* do not need an implementation of clone
* allow hashCode to use lazy initialization, and to cache its return value
* do not need to be copied defensively when used as a field
* make good Map keys and Set elements (these objects must not change state while in the collection)
* have their class invariant established once upon construction, and it never needs to be checked again
* always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state

Immutable objects have a very compelling list of positive qualities. Without question, they are among the simplest and most robust kinds of classes you can possibly build. When you create immutable classes, entire categories of problems simply disappear.

Make a class immutable by following these guidelines :

* ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
* make fields private and final
* force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
* do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
* if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller

Hash Code

http://www.devx.com/tips/Tip/5839



What is an Object's Hash Code?
Objects in Java have hash codes associated with them. An object's hash code is a signed number that identifies the object (for example, an instance of the parent class). An object's hash code may be obtained by using the object's hashCode() method as follows:


int hashCode = SomeObject.hashCode();

The method hashCode() is defined in the Object class and is inherited by all Java objects. The following code snippet shows how the hash codes of two objects relate to the corresponding equals() method:


1. // Compare objects and then compare their hash codes
2. if (object1.equals(object2)
3. System.out.println("hash code 1 = " + object1.hashCode() +
4. ", hashcode 2 = " + object2.hashCode());
5.
6. // Compare hash codes and then compare objects
7. if (object1.hashCode() == object2.hashCode())
8. {
9. if (object1.equals(object2))
10. System.out.println"object1 equals object2");
11. else
12. System.out.println"object1 does not equal object2");
13. }

By definition if two objects equal (o1.equals(o2)) then calling their hashCode() method must produce the same integer value.
This is essencial to the correct working of a hash table. Don't forget if you override equals, always override hashCode() as well.

Thursday, August 26, 2010

Python

Python is an interpreted programming language.-- a language which is never actually compiled in full,it compiles the bits of the program you are using as you are using them.

indention is very important


Friday, July 9, 2010

Singleton

public class Aclass{

private static A uniqueInstance;

private Aclass();

public Static Aclass getInstance(){
if(uniqueInstance == null)
uniqueInstance = new Aclass();
return uniqueInstance;
}

}

Monday, June 7, 2010

Strategy Pattern

defines a family of algorithms, encapsulates each one, and makes them interchangeable.Strategy lets the algorithm vary independently from clients that use it.

Class A{
SortInterface i;
}

Interface SortInterface{
sort();
}

Class ConcreteAlgorithm1 implements SortInterface{
sort(){
...
}

}

Class ConcreteAlgorithm2 implements SortInterface{
sort(){
...
}

}


a family of sort algorithms

Sunday, June 6, 2010

Design principles

1. Identify the aspects of your application that vary and separate them from what stays the same. Take the parts that vary and encapsulate them,

take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don't.

All patterns provide a way to let some part of a system vary independently of all other parts.

2. Program to an interface, not an implementation.

The point is to exploit polymorphism by programming to a supertype so that the actual runtime object isn't locked into the code.

The declared type of the variables should be a supetype, usually an abstract class or interface, so that the objects assigned to those variables can be of any concrete implementation of the supertype, which means the class declaring them doesn't have to know about the actual object type. (page 12)

3. Favor composition over inheritance.
class A{
BehaviorClass1 behavior1;
BehaviorClass1 behavior2;
}

When you put two classes together like this you're using composition. Instead of inheriting their behavior,the class A get their behavior by being composed with the right behavior object.

Not only does it let you encapsulate a family of algorithms into their own set of classes, but it also lets you change behavior at runtime as long as the object you'are composing with implements the correct behavior interface.

Wednesday, June 2, 2010

Floating point Types

float 4 bytes (7 significant decimal digits)
double 8 bytes (15 significant decimal digits)

The name double refers to the fact that these numbers have twice the precision of the float type. (double-precision). Most applications choose double. the only reaons to use float are in the rare situation in which the slightly faster processing of single-precision numbers is important.

float have a suffix F 3.402F

floating point numbers without an F suffix are always considered to be of type double. you can optionally suppfly suffix D

SE5.0 0x1.0-3 = 0.125 (floating point in hexadecimal)

three special floating point values to denote overflows and errors
Double.POSITIVE_INFINITY
DOUBLE.NEGATIVE_INFINITY
DOUBLE.NaN( not a number)

ALL 'not a number' values are considered distinct.

Thursday, May 27, 2010

Charater set vs encoding

A character set is a set of graphic, textual symbols, each of which is mapped to a set of nonnegative integers.

examples:
ASCII, ISO-8859-1 to ISO-8859-13 ISO-8859-15 (each set represent a different language set)
Unicode

An encoding maps a character set's code points to units of a specific width, and defines byte serialization and ordering rules.

example: UTF-8
UTF-8 unifies US-ASCII with Unicode.

http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/i18n/i18n2.html

Locale

The set of political, cultural, and region-specific elements represented in an application is called a locale.

Internationalization, also known as "I18n," is the process of separating locale dependencies from an application's source code.
Examples of locale dependencies include messages and user interface labels, character set, encoding, and currency and time formats.

Localization (also called "L10n") is the process of adapting an internationalized application to a specific locale. An application must first be internationalized before it can be localized.

Class java.util.Locale represents a locale in the Java 2 Platform, Standard Edition (J2SE). A Locale object is an identifier in a program that determines such factors as how numbers, currency, and time should be displayed, and the human language used to present data in a user interface.

Thursday, May 20, 2010

Localization vs. Internationalization

* Internationalization is the process of designing software so that it can be adapted (localized) to various languages and regions easily, cost-effectively, and, in particular, without engineering changes to the software.
* Localization of internationalized software is done by simply adding locale-specific components, such as translated messages, data describing locale-specific behavior, fonts, and input methods, etc.

http://javaboutique.internet.com/tutorials/leskov/

More Reading
http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/i18n/i18n.html

Tuesday, May 18, 2010

comment in java

/**
and */ can be used to generate documentation

/* */ comments do not nest

Data Types

Java is strongly typed language, this means that every viable must have a declared type.

Java does not have any unsigned types

4 integer types
(int, long, short, byte)
4 bytes, 8 bytes, 2 bytes, 1 byte

long number: 400000000L
Hexadecimal: 0xCAFE
Octal: 0700

2 Floating point types
float (4), double (8)

exit code in Java

unlike C/C++, The main method does not return an 'exit code' to the operating system. If the main method exits normally, the Java program has the exit code 0, indicating successful completion. To terminate the program with a different exit code, use the System.exit()

Thursday, May 13, 2010

5 Questions About Agile with PayPal’s Scott Killen

http://www.rallydev.com/agileblog/2010/05/5-questions-about-agile-with-paypals-scott-killen/

Principles behind the Agile Software Development

http://agilemanifesto.org/principles.html

Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.

Welcome changing requirements, even late in development. Agile processes harness change for the customer's competitive advantage.

Deliver working software frequently, from a couple of weeks to a couple of months, with a
preference to the shorter timescale.

Business people and developers must work together daily throughout the project.

Build projects around motivated individuals. Give them the environment and support they need,and trust them to get the job done.

The most efficient and effective method of conveying information to and within a development team is face-to-face conversation.

Working software is the primary measure of progress.

Agile processes promote sustainable development.The sponsors, developers, and users should be able to maintain a constant pace indefinitely.

Continuous attention to technical excellence and good design enhances agility.

Simplicity--the art of maximizing the amount of work not done--is essential.

The best architectures, requirements, and designs emerge from self-organizing teams.

At regular intervals, the team reflects on how to become more effective, then tunes and adjusts its behavior accordingly.

linklist implementation in Java

class Node{
private Object element ;
private Node next;
private Node prev;

// constructors
public Node(Object element){
this.element = element;
next = null;
prev = null;
}
}

public class LinkedList{

private Node tail;
private Node head;

//construct an empty list
public LinkedList(){
head= new Node(null);
tail = head;
}

public void addFirst(Node n){ // add to the beginning of the list
n.next = header.next ;
header.next = n;
}

public void addLast(Node n){ // add to the end of the list
n.prev = tail.prev ;
tail.prev = n;
}
remove();
find();
size();

}

the difference between a linked list and an array

A linked list consists of data nodes, each pointing to the next in the list.They can grow to any size.each node can be a different size. Memory allocation for a node is done as needed.Linked lists can be circular, or doubly-linked (pointers forward and backward), and new nodes can be inserted anywhere in the chain.

downside: sequential access. Finding a node takes linear time. O(n)

Arrays are fixed in size, so resources must be anticipated and consumed in advance. Each element is the same size and must contain the same data type.Finding a node is fast, can be calculated mathmetically

Wednesday, May 12, 2010

Thread Safe Collections

A new Java JDK package was introduced at Java 1.5, that is java.util.concurrent. This package supplies a few Collection implementations designed for use in multithreaded environments.

You can use the non-synchronized implementations in multiple thread environments, when you make sure that only one thread updating the collection at any given time.

The following table list all the syncronized collection classes:


syncronized non-syncronized

Vector ArrayList
Stack

LinkList
CopyOnWriteArrayList


jTreeSet

HashSet

LinkHashSet
CopyOnWriteArraySet


TreeMap
Hashtable

ConcurrentHashMap

jHashMap

LinkHashMap

IdentityHashMap

EnumMap

Collection

http://en.wikibooks.org/wiki/Java_Programming/Collection_Classes

the UML diagram are very clear on this page.

The Java JDK contains two high level Interfaces:
  • java.util.Collection
  • java.util.Map
here is no direct implementation for the java.util.Collection interface. The Collection interface has three sub interfaces.

java.util.Set (implementation are TreeSet,HashSet ...)
Set cannot have duplicates in it.
java.util.List
( implementation are Vector,Stack,ArrayList,LinkedList,AttributeList,RoleList...)
interfaces SortedSet
java.util.Queue ( implementation are: PriorityQueue, ArrayBlockingQueue ..)
interface: BlockingQueque
----------
java.util.Map implementations are:
TreeMap,HashMap, HashTable,LinkedHashMap,IdentityHashMap ..

Before selecting a particular collection implementation, ask the following question:

  • Can my collection contain the same elements, i.e. are duplicates allowed?
  • Can my collection contain the null element?
  • Should the collection maintain the order of the elements? Is the order important in any way?
  • How do you want to access an element? By index, key or just with an iterator?
  • Does the collection need to be synchronized?
  • From a performance perspective, which one needs to be faster, updates or reads?
  • From a usage perspective, which operation will be more frequent, updates or reads?

Tuesday, May 11, 2010

Java Annotations

http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html

Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.

Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.

Define : An at-sign (@) precedes the interface keyword

/**
* Describes the Request-For-Enhancement(RFE) that led
* to the presence of the annotated API element.
*/
public @interface infoForMethod {
int id();
String s1();
String s2() default "[unassigned]";
String s3(); default "[unimplemented]";
}

Use Annotation:
An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used.

@infoForMethod (
id = 123456,
s1= "AAAAA",
s2= "BBBB",
s3= "4/1/2009"
)
public static void aMethod(Date destination) { ... }

---
An annotation type with no elements is termed a marker annotation type
define: public @interface example{ }
Use:
@example
public void aMethod()

--
In annotations with a single element, the element should be named value,
/**
* Associates a copyright notice with the annotated API element.
*/
public @interface Author{
String value();
}

use
m.isAnnotationPresent() 

Sample Junit Test

import org.junit.* ;
import static org.junit.Assert.* ;

public class ATest {

@Test
public void test_method() {
A a = new A(200,2) ;
assertTrue
(a.getM() == 1.0) ;
}

The marker @Test is called an
annotation in Java. When we later execute JUnit’s test runner it needs
to know which methods in your test class are test methods (e.g. you may
have several helper methods in your test class). The @Test is used to mark that a method is a test method.

Junit Version

JUnit is linked as a JAR at compile-time; the framework resides under packages junit.framework for JUnit 3.8 and earlier and under org.junit for JUnit 4 and later.

currently I am using junit-3.8.2.jar which is installed eclipse plugin.

You can also find out Junit Version in Java by doing the following:



import junit.runner.Version;

System.out.println("JUnit version is: " + Version.id());