Jun 17, 2009

Small Description on Java WURFL Api

WURFL Java API

The API is simple. You have basically three objects which give you all the methods to obtain the info you need:
CapabilityMatrix , UAManager and ListManager.

CapabilityMatrix:
getCapabilityForDevice() requires a DeviceID and a capability name and it will return the value of the capability.

UAManager:
getDeviceIDFromUA() and getDeviceIDFromUALoose() require a User-Agent string and return the WURFL device ID.
It comes with two flavors: strict matching and loose matching. If in doubt, use the loose matching.

ListManager:
contains method that return lists of WURFL related data, such as list of capabilities, list of devices, etc.

To add to that, you have a singleton (ObjectsManager) that makes sure that all the WURFL data is initialized at least once and only once.
The three objects above are returned by the ObjectsManager() with calls like:

CapabilityMatrix cm = ObjectsManager.getCapabilityMatrixInstance();

One important aspect of this API is that you need *no* XML knowledge whatsoever to use it.
You just deal with strings and lists of different kinds (ArrayLists and HashMaps).

Here is a simple example of how to use the library


import net.sourceforge.wurfl.wurflapi.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Test extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//HTML Syntax
out.println("Request Information Example");

out.println("

Request Information Example

");

UAManager uam = ObjectsManager.getUAManagerInstance();
CapabilityMatrix cm = ObjectsManager.getCapabilityMatrixInstance();
out.println(uam.getDeviceIDFromUA("MOT-T720/05.08.41R MIB/2.0 Profile/MIDP-1.0 Configuration/CLDC-1.0"));

out.println("loose matching MOT-T720/G_05.01.43R");
out.println(uam.getDeviceIDFromUALoose("MOT-T720/G_05.01.43R"));

out.println(uam.getDeviceIDFromUALoose("UP.Browser"));
out.println(uam.getDeviceIDFromUALoose("Nokia7650"));

out.println("Capability Matrix:");
out.println("Device ID: telit_gm822_ver1_sub302_5017 , Capability Name: mms_wbxml")
out.println(cm.getCapabilityForDevice("telit_gm822_ver1_sub302_5017","mms_wbxml"));
out.println("");
out.println("");


}

This will produce:

mot_t720_ver1_sub050841r

loose matching MOT-T720/G_05.01.43R
mot_t720_ver1_subg050143r

samsung_r200s_ver1_sub4119kxxxx
nokia_7650_ver1_subnover
Capability Matrix:
Device ID: telit_gm822_ver1_sub302_5017 , Capability Name: mms_wbxml
false


One important aspect to note is that the results of your queries are cached. This speeds up WURFL access enormously.
The cache is the same for all of the servlet/JSP pages running inside the same webapplication.

Of course, any WURFL-based application will need to be initialized with a wurfl.xml file. This may happen in two different ways,
depending on wether you are deploying in a web (Servlet/JSP) environment or it's a stand-alone application.

Initializing stand-alone application
You can explicitly initialize the WURFL by telling the system where to find the file:

ObjectsManager.getWurflInstance("C:\wurfl_stuff\wurfl.xml");

if you don't tell the library where to find the wurfl programmatically using the method above, the API will initially look for a file
called wurfl.properties to see if the location of the wurfl is specified there: sample wurfl.properties:

wurflpath = file://C:\\projects\\wurfl\\antbuild\\resources\\wurfl.xml

If the property file is not found, the API will look for "C:\temp\wurfl.xml" on Windows and "/tmp/wurl.xml" on UNIX.

If nothing is found, an exception is thrown and a message is printed.




Retrieving a Device ID through the User-Agent

Two different methods in the UAManager class can do the job:

* getDeviceIDFromUA(String user-agent)
returns a String representing a WURFL device ID. This function looks in the WURFL for an exact match. If you don't get it, you will receive "generic" (i.e. the ID of the unrecognized device).
* getDeviceIDFromUALoose (String user-agent)
also returns a string representing a WURFL device ID. The difference is that this method won't take no for an answer nearly as easily. In case an exact match is not found, a few heuristics are applied to find a device that's reasonably similar.

At the time of this writing, the heuristics are the following:

1. Chars are removed one at the time from the end of the string. At each step a match is attempted between the string and the first part of each existing user-agent. This ends when either a match is found or the query string has become five chars.
2. Vodafone has introduced on its network a bunch of devices that add the "Vodafone/" string at the beginning of the user-agent. Those devices are listed in the WURFL. In case of a miss, the "Vodafone/" string is removed and the matching algorithm is applied from start.
3. If a match is not found, the matching algorithm looks for hints that still can lead to some useful assumptions: "UP.Browser/4","UP.Browser/5","UP.Browser/6", "Series60","Mozilla/4.0" and so on.
4. Defeat! return "generic".

If you wonder about the performance of this animal, don't worry. Queries are cached, so any subsequent query with the same data is resolved with a simple HashMap lookup.

Retrieving Capability Values

Once you have a device ID, you are ready to rock and roll: just use getCapabilityForDevice() to retrieve the value of any capability. This is a method of the CapabilityMatrix class.

- getCapabilityForDevice(String deviceID, String capabilityName)
Returns the value of a capability for a given device. There is not much to add here:

System.out.println(cm.getCapabilityForDevice("sie_m50_ver1","resolution_width"));
Q: Excuse me, Mr. Capability Matrix, how many horizontal pixels can I rely on for a Siemens M50?
A: 110 pixels, Sir.



Simple and powerful.

Setting up the Singletons

The methods above are simple to use, but there is a tiny bit of work you need to do before you can use them. Parsing the WURFL and traversing it to retrieve information is heavy stuff. The API is architected in a way that time-consuming operations are performed either at start-up or only once.

For this reason, you need to create a UAManager and CapabilityMatrix before you invoke the corresponding methods above. For the same reason, you don't just create a UAManager and CapabilityMatrix using 'new()', rather you request ObjectsManager to give them to you. ObjectsManager will make sure that a new object is created only if you are the first to request. Otherwise, you get the existing one (or better a reference to it, but I assume you have a smattering of Java from before). UAManger and CapabilityMatrix are examples of Singletons, in case you are familiar with pattern-theory parlance. If you are not, there's no need to worry: Just make sure that you have these two lines in your code, and you will have someone to talk to when you need to make a query:

UAManager uam = ObjectsManager.getUAManagerInstance();
CapabilityMatrix cm = ObjectsManager.getCapabilityMatrixInstance();

A link to a resource about Singletons can be found in the references.

Time for an another Example

The java snippet at the end of the WURFL intro last month was an example of usage of the Java API. Let's have a look at something more practical here: the implementation of the 'br' tag of the WALL library. There is no common 'br' (breakline) tag for CHTML, XHTML MP and WML, but ... almost.

* Most CHTML devices honor the
tag and simply ignore
tags
* Most XHTML MP devices will honor both
and
tags.
* Some XHTML MP device will throw an error if a single unslashed
is found and no information will be displayed (except a pretty useless error message)

This is a job for WALL, the Wireless Abstraction library:

------------------------------------------------------------------------------
public int doStartTag() throws JspException {

try {
cm = ObjectsManager.getCapabilityMatrixInstance();
uam = ObjectsManager.getUAManagerInstance();
request = (HttpServletRequest) pageContext.getRequest();

//get the user agent
UA = TagUtil.getUA(this.request);

//Check the capability string
warning = TagUtil.checkCapability("preferred_markup");
if (warning.length() > 0) {
throw new JspException(warning);
}

device_id = uam.getDeviceIDFromUALoose(UA);

capability_value = cm.getCapabilityForDevice(device_id, "preferred_markup");
capability_value = TagUtil.getWallMarkup(capability_value);

if ( capability_value.startsWith("xhtmlmp") ) {
try {
JspWriter out = pageContext.getOut();
out.print("
");
} catch(IOException ioe) {
throw new JspException("Error in WALL tag 'br': " + ioe.getMessage());
}
}

if ( capability_value.startsWith("wml") ) {
try {
JspWriter out = pageContext.getOut();
out.print("
");
} catch(IOException ioe) {
throw new JspException("Error in WALL tag 'br': " + ioe.getMessage());
}
}

//CHTML
without trailing slash
if ( capability_value.startsWith("chtml") ) {
try {
JspWriter out = pageContext.getOut();
out.print("
");
} catch(IOException ioe) {
throw new JspException("Error in WALL tag 'br': " + ioe.getMessage());
}

}

return (SKIP_BODY);

} catch (Exception e) {
throw new JspException("Error in WALL tag 'br': " + e.getMessage());
}

}
------------------------------------------------------------------------------



As usual, real apps need to spend much time in managing errors, so, here is an abridged version that shows the relevant parts:

------------------------------------------------------------------------------
1 cm = ObjectsManager.getCapabilityMatrixInstance();
2 uam = ObjectsManager.getUAManagerInstance();
3 request = (HttpServletRequest) pageContext.getRequest();
4
5 //get the user agent
6 UA = TagUtil.getUA(this.request);
7
8 device_id = uam.getDeviceIDFromUALoose(UA);
9
10 capability_value = cm.getCapabilityForDevice(device_id, "preferred_markup");
11 capability_value = TagUtil.getWallMarkup(capability_value);
12
13 if ( capability_value.startsWith("xhtmlmp") ) {
14 out.print("
");
15 }
16
17 if ( capability_value.startsWith("wml") ) {
18 out.print("
");
19 }
20
21 //CHTML
without trailing slash
22 if ( capability_value.startsWith("chtml") ) {
23 out.print("
");
24 }
------------------------------------------------------------------------------

* lines 1 and 2 create our singletons.
* lines 3 and 6 extract the User-Agent string out of the request. TagUtil.getUA() simple gives the developer a chance to override the User-Agent HTTP header for debugging purposes.
* line 8 does whatever it can to retrieve the ID of the device definition that best models the requesting device out of the user-agent string.
* lines 10 and 11 query the 'preferred_markup' for the device. TagUtil.getWallMarkup() normalizes the retrieved value into one of the three that WALL expects ('wml','xhtmlmp' and 'chtml')
* lines 13 through 24 send the most appropriate break-line tag back according to the preferred markup.

It's simple stuff. No rocket science here.

All That We Have Left Behind

The main functionalities of the API are covered, but a bunch of other things are worth mentioning.

* CapabilitMatrix.isCapabilityIn(String capability_name)
In real apps, you may want to check that a given capabilities is defined in the WURFL before querying it. An error here and you may spend more time than you wish tracking out what went wrong where. This method does that.

* ListManager is also a singleton and it supports a bunch of methods to retrieve lists of devices and capabilities you can loop on. In practical applications, you don't need those methods, since you typically deal with one device at the time. The methods become necessary when you want to implement WURFL utilities to analyze the WURFL repository and build reports. For example, you may request a list of all actual devices (devices with 'actual_device_root==true').

* WurflDevice encapsulates in a Java class everything the WURFL knows about a given device. Also not very useful unless you need to build reports of some kind. This also includes the use of the WurflDevice.getActual_device_root(), which can be used to tell if a given device is marked as 'actual device' in the WURFL.

* WurflSource is an interface that lets you initialize the API using alternative sources from which to read wurfl.xml. Totally honestly, this functionality is not very tested. If it doesn't work, give the WURFL team a holler on the WMLProgramming mailing list.

Apr 5, 2009

Graphs

9.1 Introduction

A graph G consists of a set V, whose members are called vertices of G, together with a set E of pairs of distinct vertices from V. These pairs are called the edges of G. If the pairs are unordered then G is called undirected Graph and if they are in order they are called Directed or digraphs.

9.2 Computer Representation of Graphs

1. The set representation
2. Adjacency Table or Adjacency Matrix
3. Adjacency List
a. Linked Implementation
b. Contiguous List
c. Mixed Implementation

9.3 Operations on Graphs
1. Breadth First Traversal
2. Depth First traversal

Experiment 27

Aim –Write a program to execute a Breadth First search on a Graph G beginning at A

Algorithm -

1. Initialize all node to ready state (Status = 1)
2. Put the starting node A in Queue and change its state to waiting (status = 2)
3. Repeat steps 4 and 5 until queue is empty
4. Remove the first node N of queue. Process N and change its status to processed state (status=3)
5. Add to the rear of queue all the neighbors of N that are in the ready state (status=1)
and change their status to waiting (status=2)
[End of Step 2 Loop]
6. Exit

Experiment 28


Aim –Write a program to execute a Depth First search on a Graph G beginning at A

Algorithm –

1. Initialize all nodes to ready state (Status = 1)
2. Push the starting node A in Queue and change its state to waiting (status = 2)
3. Repeat steps 4 and 5 until stack is empty
4. Pop the Top node N of stack . Process N and change its status to processed state (status=3)
5. Push onto stack all the neighbors that are in the ready state (status=1)
and change their status to waiting (status=2)
[End of Step 3 Loop]
6. Exit


9.4 Viva Voice

1. Define graph, directed and undirected graph?
2. Define the following:
a. Adjacent vertices
b. Path
c. Cycle
d. Connected graph
e. Degree
f. Complete graph
g. Weighted graph
3. How the graph is represented in computers memory?
4. What do you mean by graph traversal? What are different traversal methods of graph?
5. Minimum spanning tree are designed on directed or undirected graph?
6. What must a graph look like if a row of its matrix consists only of zeros?

Trees

8.1 Introduction-
A binary tree is either empty or it consists of a node called the root together with two binary trees called the Left subtree and the right subtree of the root.

8.2 Operations on Binary trees.
1. Insertion in Binary Tree
2. Deletion in Binary Tree
3. Traversal of Trees
a. Pre-order Traversal ( Root-Left-Right )
b. In-order Traversal ( Left-Root-Right )
c. Post-order Traversal ( Left-Right-Root )

Applications

1. Comparison Trees
2. Expression Trees


Experiment 24

Aim –Write a program to create a binary tree

Algorithm -

Let create_tree (info,node) be a procedure where info is the information for which we have to create node and node is a structure type variable with pointers to point to both left and right child.

1. [check whether the tree is empty]
If node = NULL
Node=create a node
Left[node]=NULL
Right[node]=NULL
2. [Test for the left child]
If info[node] >= info
Left[node]=Call create_tree(info,left[node])
else
Right[node]=Call create_tree(info,right[node])
3. return (Node)

8.3 Viva Voice

1. What is a Tree
2. Define the following terms
a. Degree
b. Depth
c. Path
d. Forest
3. Differentiate between Terminal nodes and non-terminal nodes
4. What is Binary tree.
5. Mention the properties of binary tree
6. What is Strictly & completely binary Tree
7. How binary tree is represented in computers memory?
8. What is thearded binary tree? It’s advantages and disadvantages
9. Draw the binary tree using the given traversals?
10. What is AVL tree?
11. Whait if forest?

Searching

7.1 Introduction
Searching is used to find the location where element is available or not. There are two types of searching techniques as given below :
1. Linear or sequential searching
2. Binary searching


Experiment 22

Aim –Write a program to search the given element using linear search.

Theory
In linear search, we access each element of an array one by one sequentially and see whether it is desired element or not. A search will be unsuccessful if all the elements are accessed and the desired element is not found. In the worst case the number of average case we may have to scan half of the size of the array. Therefore, linear search can be defined as a technique which traverses the array sequentially to locate the given item.
The time taken or the number of comparisons made in searching a record in search table determines the efficiency of the technique. If the desired record is present in the first position then only one comparison is made. If the desired record is last one then n comparisons have to made.


Algorithms
Let A is a linear array with N elements, and ITEM is a given item of information. This algorithm finds the location LOC of ITEM in A, or sets LOC=0 if the search is unsuccessful.

1. [Initialize counter]
set LOC = 1
2. [Serach for item]
repeat while A[LOC] != ITEM
set LOC=LOC+1
3.[Successful]
if LOC = N+1, then
set LOC=0
4. Exit.



Experiment 23

Aim –Write a program to search the given element using binary search.

Theory- The search technique searches the given item in minimum possible comparisons. To do the Binary search, first the array is sorted. The logic behind the technique is
1. First find the middle element of the array.
2. Compare the mid element with the item
3. There are three cases:
a. If it is the desired element search is successful.
b. If it is less than desired item, then search the first half of the array
c. If it is greater than desired item, then search the second half of the array
Repeat the same steps until the search is exhausted.


Algorithms
Let A is sorted array with lower bound LB and upper bound UB, and ITEM is a given ITEM of information. The variables BEG, END and MID denoted, respectively, the beginning, end and middle location of a segment of element of A. This algorithm finds the location LOC of ITEM in A or sets LOC = NULL.

1. [Initialize segment variables]
Set BEG = LB ,END = UB and MID = int (( BEG + End)) / 2
2. Repeat steps 3 and 4 while BEG <= END and A[MID] != ITEM
3. if ITEM < A [MID] , then
Set END = MID – 1
Else
Set BEG = MID +1
[end of if structure]
4. set mid = int ((BEG + END))/2
[End of step 2 loop]
5. if A[MID] = ITEM then
set LOC = MID
else
set LOC = NULL
[end of if structure]
6.exit


7.2 Viva voice

1.What is sorting? List different types of sorting techniques.
2. What are the factors to be considered during the selection of sorting technique.
3.Which of the following sorts will take longest time to execute and which will take the shortest time?
a) Merge sort
b) Heap sort
c) Selection sort
d) Shell sort
e) Quick sort
f) Insertion sort

4. How many comparisons are required to sort an array of 10 elements using selection sort , if the original array values already sorted?
5. What do you mean by efficiency of the algorithm?
6. What is the best case , average case and worst case complexity of following:
a) merge sort
b) heap sort
c) selection sort
d) shell sort
e) quick sort
f) insertion sort
7.What are the factors on which complexity of algorithm depends? Which factor is taken into consideration while determining the complexity of algorithm for searching and sorting?
8.Suppose name consist of following list of names with n= 5
Amit, jaswinder , chander, gagan, seema
Find the number of comparisons to sort name using radix sort.
9.What is searching?
10.Distinguish between the following
a) Internal search and external search
b) Primary key and secondary key
c) Internal key and external key
10. Which is efficient search technique?
11. What is hashing? What is the need for a hashing?
12. What is the need for an ordered table searching?
13. What are the techniques to resolve hash clashes?

Sorting

6.1 Introduction
Sorting of an array is the technique of arranging the array elements in a specified order i.e either in ascending or descending order. Sorting is one of the operation which make the job of retrieval of data from the storage devices, easier, speedier and efficient.

There are several sorting techniques available. They are :

1. Bubble sort
2. Selection sort
3. Shell sort
4. Heap sort
5. Insertion sort
6. Quick sort
7. Merge sort


6.2 Efficiency of Sorting Algorithms


Performance analysis & measurement
The time and space the algorithm uses are the two major measures of the efficiency of the algorithm. The complexity of the algorithm is the function which gives the running time and/or space in terms of the input size.
Space complexity
The space complexity of a program is the amount of memory it needed to fun to completion.
Time Complexity:
It is the amount of computer time needs to run to completion.

Big OH Notation
Big OH is a characterization scheme that allows to measure properties of algorithm complexity performance and/or memory requirements in a general fashion.

LINKED LIST

5.1 INTRODUCTION
Linked lists are special list of some data element pointing to one another.The logical ordering is represented by having each element pointing to the next element.Each element is called a node, which has two parts.INFO part which stores the information and POINTER which points to the next element.

5.2 OPERATIONS ON LINKED LIST
The basic operation to be performed on linked list are as follows :
1. Creation 2. Insertion
3. Deletion 4. Traversing
5. searching 6.Concatenation
7.Display

5.3 TYPES OF LINKED LIST
1. Singly linked list 2. Doubly linked list
3. Circular linked list 4. Circular Doubly linked list

SINGLY LINKED LIST
singly linked list are known as one way list. In this one pointer is maintained , which points to the next node called the NEXT pointer. One can traverse the list in forward direction.

DOUBLY LINKED LIST
Doubly linked list are known as two way list. In this two pointers are maintained :One which points to the next node called the NEXT pointer and other which points to previous node called the PREV pointer. One can traverse the list both in forward as well as backward direction.

CIRCULAR LINKED LIST
A Circular Linked List is one which has no beginning and no end. In this two pointers are maintained: One which points to the next node called the NEXT pointer and other which points to previous node called the PREV pointer. One can traverse the list both in forward as well as backward direction. It is very similar to doubly linked list except that in doubly linked list the prev pointer of the first node and the next pointer of the last node points to NULL where as in circular linked list the last node contains the address of the first node and the last node contains the address of the first node. All operation are similar to doubly linked list

Queues

4.1 INTRODUCTION

A queue is a non-primitive linear data structure .It is an homogeneous collection of elements in which new elements are added at one end called the Rear end , and the existing elements are deleted from other end called the Front end.

4.2 OPERATION ON QUEUES

The basic operations that can be performed on queue are:
To insert an element in the queue.
To delete an element from the queue.

4.3 DEQUEUES

It is homogeneous list of elements in which insertion and deletion operations are performed from both the ends.

4.4 Operations on Dequeue

1. Insertion of an element at the REAR end of the queue.
2. Deletion of an element from the FRONT end of the queue.
3. Insertion of an element at the FRONT end of the queue.
4. Deletion of an element from the REAR end of the queue

For an input-restricted deque only the operations specified in 1, 2, 3 and 4 are valid. And for out- restricted deque only the operations specified in 1, 2, 3 are valid.


4.5Application of arrays

1. Round robin technique for processor scheduling is implemented using queues.
2. All types of customer service (like railway ticket reservation) center software’s are designed using queues to store customers information.
3. Printer server routines are designed using queues.


Experiment 7

Aim- Write a program to perform add and delete operations in the linear queue

Algorithm (Insertion)
Let QUEUE be the array of some specified size say MAXSIZE, then the insertion algorithm will be as given below.While implementing a queue using arrays we must check underflow and overflow conditions for queue.

1. Initialize Front =0 and Rear = -1
2. If Rear b>= MAXSIZE [Check overflow condition]
Write Queue Overflow and return
Else
Set Rear = Rear + 1
3. QUEUE[Rear] = Item
4. If Front = -1 [Set the front pointer]
5. Return.

Algorithm (Deletion)

1. [Check underflow condition]
If Front < 0
Print : Queue is Empty and return
Else :
Item = QUEUE[Front] [Remove Element from front]
3. [Find new value of front.]
If (Front= = Rear) [Checking for empty queue]
Set front=0 , Rear = -1 [Re- initialize the pointers]
Else:
Front = Front +1
4. Return

4.7VIVA VOICE

1.What is a queue?
2.What does ‘front’ and ‘rear’ of the queue?
3. What is the full form of DEQUEUE?
4. How is queue different from stack?
5. Distinguish between LIFO and FIFO.
6. What is full queue and empty queue condition
7. What is circular queue and how do you represent it?
8. What is Dequeue?
9. What is meant by priority queues?

Stacks

3.1 Introduction

A Stack is a non-primitive linear data Structure. It is a ordered list in which addition and deletion of data items is done only from one end, known as top of stack (TOS). As all the deletions and insertions in a stack is done from the top of the stack the last added element will be the first to be removed from the stack that is the reason why stack is called Last in first out (LIFO) type of list.

3.2 Stack Implementation
Stack can be implemented in two ways:
(i) Static implementation: - It uses array to create stack.
(ii) Dynamic implementation: - Also called linked list representation and uses pointers to implement the stack type of data structure.

3.3 Operations on Stack
(i) PUSH
(ii) POP
(iii) PEEP

3.4 Applications of Stacks

1. Evaluation of Postfix Expression
2. Conversion of infix to Postfix
3. Conversion of infix to Prefix
4. Validity of an Expression

Experiment 1

Aim – Write a program to perform push and pop operations on stack.
Theory- The process of adding a new element to the top of stack is called PUSH operation and after every push operation the top of the stack is incremented by one. In case the array is full and no new element can be accommodated, it is called overflow condition.

The process of deleting an element from the top of the stack is called POP operation and after every pop operation the top of the stack is decremented by one.In case the array is empty , the condition is called underflow condition.
The process of accessing the elements is PEEP operation.

Algorithm- (PUSH)
Let stack [Maxsize] is an array for implementing the stack.

1. [Check for stack overflow]
If Top = Maxsize – 1, then : print : overflow and exit
2. [increment Top by one
Set Top = Top + 1
3. [Insert item in the new Top position]
Set stack[Top] = item
4. Exit

Algorithm- (POP)

Let stack[Maxsize] is an array for implementing the stack and assign to variable item.
2. [Check for stack underflow]
If Top < 0 then :
Print : “Stack overflow” and Exit
Else [Remove the top element]
Set Item = Stack[Top]
3. [decrement the Stack top]
Set Top = Top – 1
4. [Return the Deleted Item from the stack]
5. Exit

Arrays

2.1 Introduction

An array is defined as a set of finite number of homogeneous elements or data items. Some common operations performed on arrays are:
1. Creation of an array
2. Traversing an array (accessing array elements)
3. Insertion of new elements.
4. Deletion of required element.
5. Modification of an element
6. Merging of arrays.
7. Searching an element.
8. Sorting the elements.


2.2 Limitation of arrays
1.The prior knowledge of number of elements in the array is necessary.
2. These are static structures.
3. Since the elements of these arrays are stored in these arrays are time consuming. This is because of moving down or up to create a new space of a new element or to occupy the space vacated by the deleted item.



Experiment 1

Aim – Write a program to insert, delete and traverse an array

Theory –
Inserting an element at the end of array can be easily done, provided the memory space allocated for array is large enough to accommodate the additional element. For inserting the element at required position , elements must be moved downwards or rightwards to create space for the element to be inserted.

Deleting an element at the end of array presents no difficulties, but deleting element somewhere in the middle of the array would require to shift all the elements to fill the space emptied by the deletion of the element, then element following it are moved upward or left by one location.

Traversing means to access all the elements of array, starting from first element (Lower bound) upto the last element (Upper bound ) in the array one-by-one.


Algorithm (Insertion)

Assume len to be the length of the array A, NE be the total no. of elements, pos denotes index no. or position, num to be the element to be inserted.

1. [Initialize the value of I ]
Set I = NE
2. Repeat for I=NE to pos
[Shift the elements down by one element]
Set a[I+1]=a[I]
[end of Loop]
3. [Insert the element at required position]
Set A[pos]=num
4. [Reset len]
Set NE=len+1
5. display yhe new list of arrays
6. End




Algorithm (Deletion)
Assume len to be the length of the array A, NE be the total no. of elements, pos denotes index no. or position, num to be the element to be deleted.

1. Set item=A[pos]
2. Repeat for j = pos to NE-1
[Shifting elements 1 position upwards or left]
Set A[j] = A[j+1]
[End of loop]
3. Reset NE = NE -1
4. Display the new list of arrays
5. End


Algorithm (Traversal)
Let LB be the lower bound and UB be the upper bound of linear array A.

1. [Initialize counter.]
Set I at lower bound LB
2. Repeat for I=LB to UP
[visit element]
Display A[I]
[End of the loop]
3. Exit.


2.2 Viva Questions

1. What is meant by static implementation of the array
2. What is meant by dynamic implementation of the array
3. Name some Data structures, which can be implemented with the help of arrays.
4. Does deletion operation in static implementation, actually deletes the array element or it overwrites it.
5. What are the limitations of the array.

Data Structures

1 What is Data Structure
Data Structure is a representation of logical relationship existing between individual elements of data. In other words, a data structure is a way of organizing all data items that considers not only the elements stored but also their relationship to each other.
It is a mathematical or logical model for particular organization of data items.
It mainly specifies the following things:-
1. Organization of data
2. Accessing methods
3. Processing alternatives for information

1.1 Classification of Data Structures
Data structures are normally divided into two categories: -
1. Primitive Data Structure:- These are basic structures and are directly operated upon by the machine instructions.
2. Non-primitive Data structure:- These are derived from primitive data structures. It emphasize on structuring of a group of homogeneous or heterogeneous data items.

1.2 Operations on Data structure
The design of an efficient data structure must take operations to be performed on the data structure into account. The data structure is to be manipulated in a number of major program functions. After evaluating the operations to be performed on the data structure, an abstract data type is defined to use it in subsequent programs.
The most commonly used operations on data structure are :
1. Creation
2. Insertion
3. Deletion
4. Selection
5. Updation
6. Searching
7. Sorting
8. Merging

1.3 Algorithms
An algorithm is any well- formed –defined computational procedure that takes some value or set of values as input and procedure some values or set of values as output.

1.4 Analyzing algorithms
Analyzing an algorithm measuring computational time and memory space required during execution.

1.5 Performance analysis & measurement

1.5.1 Space complexity
The space complexity of a program is the amount of memory it needed to fun to completion.
1.5.2 Time Complexity:
It is the amount of computer time needs to run to completion.

1.6 Big OH Notation
Big OH is a characterization scheme that allows to measure properties of algorithm complexity performance and/or memory requirements in a general fashion.

1.7 Categories of Algorithms
Based on Big OH notation the algorithms can be categorized as follows:
• Constant time (O(1)) algorithm.
• Logarithmic time (O(log n)) algorithms.
• Linear time (O(n)) algorithms.
• Polynomial time (O(n**k),for k >1) algorithms
• Exponential time (O(k**n), for k >1) algorithms.
• Many algorithms are O(n log n).

How to Face Interview

1. Plan to arrive 10 minutes early. This will give you ample time to catch your breath, gather your thoughts and make a quick trip to the washroom to give your appearance one final check. To avoid unnecessary stress, choose your interview attire the night before.

2. Greet the interviewer by his or her last name. If you are unsure of the pronunciation, do ask the employer to repeat it. Or better still, check it with the front desk personnel or receptionist before walking into the interview room.

3. Let the interviewer lead the conversation but try to get him/her to describe the position and duties to you early in the interview. This will allow you to apply your background, skills and achievements to the position.

4. When asked: "Tell me about yourself?", focus your answers on your background and a few professional and personal accomplishments.

5. Stress on your achievements. For example: your sales records, the processes you have developed or systems installed, projects that you initiated, etc.

6. Show enthusiasm. This can be demonstrated through verbal and non-verbal cues (for example, appropriate body language like nodding can be used to support your interest). Enthusiastic feedback can enhance your chances of being further considered.

7. Answer questions by speaking in terms of the position. Emphasise what you can do for the company. Mention specific accomplishments that show your abilities and determination to succeed in this job. Your answers describe the position and duties to you early in the interview. This will allow you to apply your background, skills and achievements to the position. should tell the employer why you would be an asset to the company and not why you need a job.

8. Bring an extra copy of your resume.

9. Explain whenever possible; don't answer with a simple "yes" or "no."










Be prepared to answer questions such as:

* Tell me about yourself.
* Tell me about your background and accomplishments.
* What are your strengths? Weaknesses?
* How would you describe your most recent job performance?
* What interests you about our company?

Also, be prepared to ask questions such as:

* What would I be expected to accomplish in this position?
* What are the greatest challenges in this position?
* How do you think I fit the position?

Remember, your lack of questions may be mistaken as lack of interest in the job.

Summary

If you are interested in the position, stress this to the interviewer. If you get the impression that the interview is not going well and that you have already been rejected, do not let your discouragement show. Once in a while an interviewer who is genuinely interested in you may seem to discourage you as a way of testing your reaction. Remember to thank the interviewer for his/her time and end the session with a confident and firm handshake.

Jan 27, 2009

J2ME Client Code for acessing Adressbook

How to Modify and other operations on AdressBook

Code:-

import javax.microedition.pim.*;
import java.util.Enumeration;
import java.util.Calendar;
import java.util.Date;
public class PIMTest {
public PIMTest() {
}
/**************************************************************************
* Contact/ContactList sample code
***************************************************************************/
public void createAContact() {
// Create a support contact entry in the device's
//local address book
// so that the users have has the contact
//information for anything that they
// need help with about your application
PIM pim = PIM.getInstance();
ContactList cl = null;
Contact new_contact = null;
try {
// Open write only since you're just going to
// add your support contact
// info to the device's database
cl = (ContactList)
pim.openPIMList(PIM.CONTACT_LIST, PIM.WRITE_ONLY);
} catch (PIMException e) {
// failed opening the default contact list!
// Error case - abort this attempt
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
//write access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't add the contact");
return;
}
// Create an "empty" contact to work with
new_contact = cl.createContact();
// Add your company's info: company name,
//two support phone numbers, a support
// email, and a note about what product the user has. Add whatever
// information that the native contact list
//supports and don't add it if
// the field is not supported.
if (cl.isSupportedField(Contact.ORG))
new_contact.addString(Contact.ORG, PIMItem.ATTR_NONE,
"Acme, Inc.");
if (cl.isSupportedField(Contact.TEL)) {
new_contact.addString(Contact.TEL, PIMItem.ATTR_NONE,
"800-888-8888");
new_contact.addString(Contact.TEL, PIMItem.ATTR_NONE,
"800-888-8889");
}
if (cl.isSupportedField(Contact.EMAIL))
new_contact.addString(Contact.EMAIL,
PIMItem.ATTR_NONE, "support@acme.com");
if (cl.isSupportedField(Contact.NOTE))
new_contact.addString(Contact.NOTE, PIMItem.ATTR_NONE,
"You've purchased application XXX with registration number NNN.");
try {
// commits it to the list and the native database
new_contact.commit(); // commits it to the list and the native database
}
catch (PIMException e) {
// failed committing the contact
System.err.println(
"This application cannot add the contact info");
}
try {
cl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void retrieveContacts() {
// Get all contacts with last name starting with "S" (e.g.
// Smith, Sanders, Stargell, etc.) for a listing screen
PIM pim = PIM.getInstance();
ContactList cl = null;
Contact search_template = null;
Enumeration s_contacts = null;
try {
cl = (ContactList) pim.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
} catch (PIMException e) {
// failed opening the default contact list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't get contacts");
return;
}
// first create a "template" contact which we'll use for matching
search_template = cl.createContact();
if (cl.isSupportedArrayElement(Contact.NAME,
Contact.NAME_FAMILY)) {
// this particular contact list does contain last names, so we
// can now do the search
// now fill in the search parameters of last name
// starting with 'S'
String[] name_struct = new String[Contact.NAMESIZE];
name_struct[Contact.NAME_FAMILY] = "S";
search_template.addStringArray(Contact.NAME,
PIMItem.ATTR_NONE, name_struct);
}
else if (cl.isSupportedField(Contact.FORMATTED_NAME)) {
// the contact implementation doesn't have individual name
// fields, so try the single name field FORMATTED_NAME
search_template.addString(Contact.FORMATTED_NAME,
PIMItem.ATTR_NONE, "S");
}
try {
// Get the enumeration of matching elements
s_contacts = cl.items(search_template);
} catch (PIMException e) {
// failed to retrieve elements due to error!
System.err.println(
"This application cannot retrieve the contacts");
}
try {
cl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void modifyAContact() {
// Code sample:
// Update John Smith's home phone number
// from "555-0000" to "555-1212"
// since he moved...
PIM pim = PIM.getInstance();
ContactList cl = null;
Enumeration contacts = null;
try {
cl = (ContactList) pim.openPIMList(
PIM.CONTACT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default contact list!
System.err.println(
"This application failed to open the contact list");
} catch (SecurityException e) {
// user rejected application's request
// for read/write access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't get contacts");
return;
}
// first create a "template" contact which we'll use for matching
// to find John Smith's contact entry
Contact template = cl.createContact();
String tel_number = "";
if (cl.isSupportedField(Contact.NAME)) {
String[] name_struct = new String[Contact.NAMESIZE];
name_struct[Contact.NAME_FAMILY] = "Smith";
name_struct[Contact.NAME_FAMILY] = "John";
template.addStringArray(
Contact.NAME, PIMItem.ATTR_NONE, name_struct);
}
if (cl.isSupportedField(Contact.TEL)) {
template.addString(Contact.TEL, Contact.ATTR_HOME, "555-0000");
}
try {
// Get the enumeration of matching elements
contacts = cl.items(template);
} catch (PIMException e) {
// failed retrieving the items enumeration due to an error
System.err.println(
"This application cannot retrieve the contact");
}
// update all John Smith entries with old home numbers of 555-0000
while (contacts!= null && contacts.hasMoreElements()) {
Contact c = (Contact) contacts.nextElement();
for (int index = c.countValues(Contact.TEL); index != 0; index--)
{
if (c.getString(Contact.TEL, index).equals("555-0000")) {
c.setString(Contact.TEL, index, Contact.ATTR_HOME,
"555-1212");
try {
// save change to the database
c.commit();
} catch (PIMException e) {
// Oops couldn't save the data...
System.err.println(
"This application cannot commit the contact info");
}
break; // go to next matching element
}
}
}
try {
cl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void deleteContacts() {
// Delete all contacts at company WorldCom
// since they won't be answering
// phone calls anymore...
PIM pim = PIM.getInstance();
ContactList cl = null;
Enumeration contacts = null;
try {
cl = (ContactList) pim.openPIMList(
PIM.CONTACT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default contact list!
System.err.println(
"This application failed to open the contact list");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read/write access to contact list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't get contacts");
return;
}
// first create a "template" contact which we'll use for matching
// to find WorldCom contact entries
Contact template = cl.createContact();
if (cl.isSupportedField(Contact.ORG)) {
template.addString(Contact.ORG,
PIMItem.ATTR_NONE, "WorldCom");
try {
// Get the enumeration of matching elements
contacts = cl.items(template);
} catch (PIMException e) {
// failed retrieving the items enumeration due to an error
System.err.println(
"This application cannot commit the contact info");
}
}
// delete all WorldCom entries
while (contacts != null && contacts.hasMoreElements()) {
Contact c = (Contact) contacts.nextElement();
try {
cl.removeContact(c);
} catch (PIMException e) {
// couldn't delete the entry for some
// reason (probably shredded)
System.err.println(
"This application cannot remove the contact info");
}
}
try {
cl.close();
} catch (PIMException e) {
// failed to close the list
}
}
/***************************************************************************
Event/EventList sample code
***************************************************************************/
public void createAnEvent() {
// Create an event entry in the device's local calendar
// reminding the user to register your application
PIM pim = PIM.getInstance();
EventList el = null;
Event new_event = null;
try {
// Open write only since you're just going to
//add your registration
// event info to the device's database
el = (EventList) pim.openPIMList(
PIM.EVENT_LIST, PIM.WRITE_ONLY);
} catch (PIMException e) {
// failed opening the default event list!
// Error case - abort this attempt
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
// for write access to event list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't add the event");
return;
}
// Create an "empty" event to work with
new_event = el.createEvent();
// Add a registration reminder event:
// make it two weeks from now with an
// alarm 10 minutes before the occurrence, and
// add a note with the phone or email to call.
if (el.isSupportedField(Event.START)) {
Date d = new Date();
long l = d.getTime() + (long)1209600000;
new_event.addDate(Event.START, PIMItem.ATTR_NONE, l);
}
if (el.isSupportedField(Event.ALARM))
new_event.addInt(Event.ALARM, PIMItem.ATTR_NONE, 600);
if (el.isSupportedField(Event.SUMMARY))
new_event.addString(Event.SUMMARY, PIMItem.ATTR_NONE,
"Register Your Product!");
if (el.isSupportedField(Event.NOTE))
new_event.addString(Event.NOTE, PIMItem.ATTR_NONE, "You've purchased application XXX with registration number NNN. Please register it now. Look in the Contact List for information on how to contact us.");
try {
// commits it to the list and the native database
new_event.commit(); // commits it to the list and the native database
}
catch (PIMException e) {
// failed committing the event
System.err.println("This application cannot add the event");
}
try {
el.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void retrieveEvents() {
// Get all events occurring for the coming week,
// for a listing screen
PIM pim = PIM.getInstance();
EventList el = null;
Event search_template = null;
Enumeration this_weeks_events = null;
try {
el = (EventList) pim.openPIMList(
PIM.EVENT_LIST, PIM.READ_ONLY);
} catch (PIMException e) {
// failed opening the default event list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read access to event list
// This is not an error condition and can be normal
System.out.println("Okay, this application won't get events");
return;
}
// calculcate today's date and next week's date
long current_time = (new Date()).getTime();
long next_week = current_time + 604800000;
try {
// Get the enumeration of matching elements
this_weeks_events = el.items(
EventList.OCCURRING, current_time, next_week, true);
} catch (PIMException e) {
// failed to retrieve elements due to error!
// Error case - abort this attempt
System.err.println(
"This application cannot retrieve the events");
}
try {
el.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void modifyEvents() {
// Code sample:
// Postpone all events from today until
// tomorrow (sick day today...)
PIM pim = PIM.getInstance();
EventList el = null;
Enumeration todays_events = null;
try {
el = (EventList) pim.openPIMList(
PIM.EVENT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default event list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's requestfor read/write access to contact list
// This is not an error condition and can be normal
System.out.println("Okay, this application won't modify any event");
return;
}
// calculate today's start and end times
Calendar start_of_day = Calendar.getInstance();
// start of work day is 7am
start_of_day.set(Calendar.HOUR_OF_DAY, 7); // start of work day is 7am
Calendar end_of_day = Calendar.getInstance();
// end of work day is 8pm
end_of_day.set(Calendar.HOUR_OF_DAY, 20); // end of work day is 8pm
try {
// Get the enumeration of matching elements
todays_events = el.items(Event.OCCURRING, start_of_day.getTime().getTime(), end_of_day.getTime().getTime(), true);
} catch (PIMException e) {
// failed to retrieve elements due to error!
System.err.println(
"This application cannot retrieve the events");
}
// update all events by one day
while (todays_events != null && todays_events.hasMoreElements()) {
Event e = (Event) todays_events.nextElement();
e.setDate(Event.START, 0, PIMItem.ATTR_NONE,
e.getDate(Event.START, 0) + 86400000);
try {
// save change to the database
e.commit();
} catch (PIMException exe) {
// Oops couldn't save the data...
System.err.println(
"This application cannot commit the event");
}
}
try {
el.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void deleteEvents() {
// Delete all events having to do with Christmas (bah humbug!)
PIM pim = PIM.getInstance();
EventList el = null;
Enumeration xmas_events = null;
try {
el = (EventList) pim.openPIMList(
PIM.EVENT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default event list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
// for read/write access to event list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't modify any event");
return;
}
try {
// Get the enumeration of matching elements
xmas_events = el.items("Christmas");
} catch (PIMException e) {
// failed retrieving the items enumeration due to an error
System.err.println(
"This application cannot retrieve the events");
return;
}
// delete all event entries containing Christmas
while (xmas_events != null && xmas_events.hasMoreElements()) {
Event e = (Event) xmas_events.nextElement();
try {
el.removeEvent(e);
} catch (PIMException exe) {
// couldn't delete the entry for some reason
System.err.println(
"This application cannot remove the event info");
}
}
try {
el.close();
} catch (PIMException e) {
// failed to close the list
}
}
/**************************************************************************
* ToDo/ToDoList sample code
***************************************************************************/
public void createAToDo() {
// Create a todo entry in the device's local todo list
// reminding the user to register your application
PIM pim = PIM.getInstance();
ToDoList tl = null;
ToDo new_todo = null;
try {
// Open write only since you're just going to
// add your registration
// todo info to the device's todo database
tl = (ToDoList) pim.openPIMList(PIM.TODO_LIST, PIM.WRITE_ONLY);
} catch (PIMException e) {
// failed opening the default todo list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
// for write access to todo list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't add the todo");
return;
}
// Create an "empty" todo to work with
new_todo = tl.createToDo();
// Add a registration todo: make it have a
// due date of two weeks from now
// with a low priority, and
// add a note with the phone or email to call.
if (tl.isSupportedField(ToDo.DUE)) {
Date d = new Date();
long l = d.getTime() + (long)1209600000;
new_todo.addDate(ToDo.DUE, PIMItem.ATTR_NONE, l);
}
if (tl.isSupportedField(ToDo.PRIORITY))
new_todo.addInt(ToDo.PRIORITY, PIMItem.ATTR_NONE, 5);
if (tl.isSupportedField(ToDo.SUMMARY))
new_todo.addString(ToDo.SUMMARY, PIMItem.ATTR_NONE,
"Register Your Product!");
if (tl.isSupportedField(ToDo.NOTE))
new_todo.addString(ToDo.NOTE, PIMItem.ATTR_NONE,
"You've purchased application XXX with registration number NNN. Please register it now.Look in the Contact List for information on how to contact us.");
try {
// commits it to the list and the native database
new_todo.commit(); // commits it to the list and the native database
}
catch (PIMException e) {
// failed committing the todo
System.err.println("This application cannot add the todo");
}
try {
tl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void retrieveToDos() {
// Get all todos due today, for a listing screen
PIM pim = PIM.getInstance();
ToDoList tl = null;
ToDo search_template = null;
Enumeration todos = null;
try {
tl = (ToDoList) pim.openPIMList(PIM.TODO_LIST, PIM.READ_ONLY);
} catch (PIMException e) {
// failed opening the default todo list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read access to todo list
// This is not an error condition and can be normal
System.out.println("Okay, this application won't get todo items");
return;
}
// calculate today's start and end times
Calendar start_of_day = Calendar.getInstance();
start_of_day.set(Calendar.HOUR_OF_DAY, 0);
Calendar end_of_day = Calendar.getInstance();
end_of_day.set(Calendar.HOUR_OF_DAY, 24);
try {
// Get the enumeration of matching elements
todos = tl.items(
ToDo.DUE, start_of_day.getTime().getTime(),
end_of_day.getTime().getTime());
} catch (PIMException e) {
// failed to retrieve elements due to error!
// Error case - abort this attempt
System.err.println(
"This application cannot retrieve the todos");
}
try {
tl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void modifyToDos() {
// Mark all stuff from yesterday as completed
PIM pim = PIM.getInstance();
ToDoList tl = null;
ToDo search_template = null;
Enumeration todos = null;
try {
tl = (ToDoList) pim.openPIMList(PIM.TODO_LIST, PIM.READ_ONLY);
} catch (PIMException e) {
// failed opening the default todo list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request for
// read access to todo list
// This is not an error condition and can be normal
System.out.println("Okay, this application won't get todo items");
return;
}
// calculate today's start and end times
Calendar start_of_day = Calendar.getInstance();
start_of_day.set(Calendar.HOUR_OF_DAY, 0);
Calendar end_of_day = Calendar.getInstance();
end_of_day.set(Calendar.HOUR_OF_DAY, 24);
try {
// Get the enumeration of matching elements
todos = tl.items(
ToDo.DUE, start_of_day.getTime().getTime() - 86400000,
end_of_day.getTime().getTime() - 86400000);
} catch (PIMException e) {
// failed to retrieve elements due to error!
// Error case - abort this attempt
System.err.println("This application cannot retrieve the todos");
}
// set all todos due yesterday to completed
//with updated completion date
while (todos != null && todos.hasMoreElements()) {
ToDo t = (ToDo) todos.nextElement();
if (tl.isSupportedField(ToDo.COMPLETED))
t.setBoolean(ToDo.COMPLETED, 0, PIMItem.ATTR_NONE, true);
if (tl.isSupportedField(ToDo.COMPLETION_DATE))
t.setDate(ToDo.COMPLETION_DATE, 0,
PIMItem.ATTR_NONE, (new Date()).getTime());
try {
// save change to the database
t.commit();
} catch (PIMException exe) {
// Oops couldn't save the data...
System.err.println(
"This application cannot commit the todo");
}
}
try {
tl.close();
} catch (PIMException e) {
// failed to close the list
}
}
public void deleteToDos() {
// Delete all ToDos having to do with cleaning (hired a maid instead)
PIM pim = PIM.getInstance();
ToDoList tl = null;
Enumeration todos = null;
try {
tl = (ToDoList) pim.openPIMList(PIM.TODO_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// failed opening the default todo list!
System.err.println(
"Error accessing database - aborting action");
return;
} catch (SecurityException e) {
// user rejected application's request
// for read/write access to todo list
// This is not an error condition and can be normal
System.out.println(
"Okay, this application won't modify any todo");
return;
}
try {
// Get the enumeration of matching elements
todos = tl.items("clean");
} catch (PIMException e) {
// failed retrieving the items enumeration due to an error
System.err.println(
"This application cannot retrieve the todos");
return;
}
// delete all event entries containing 'clean'
while (todos != null && todos.hasMoreElements()) {
ToDo t = (ToDo) todos.nextElement();
try {
tl.removeToDo(t);
} catch (PIMException exe) {
// couldn't delete the entry for some reason
System.err.println(
"This application cannot remove the todo info");
}
}
try {
tl.close();
} catch (PIMException e) {
// failed to close the list
}
}
}

Jan 18, 2009

Aptitude Q & A

Section I - Logical & Analytical Ability

1. In a girls’ school, 128 girls play skipping, 102 play throwball. Out of these 30 girls play both throwball and skipping . Find the percentage of girls not playing any of these games, if the number girls playing less than two games is nine times the number of girls playing two games.

(a) 33+1/3% (b) 35% (c) 37% (d) 42% ans=a


2. In a village with a population of 1000 people each person reads either the Times of India or the Free Press.112 persons read only the Times of India, 512 persons read only the Free press and the remaining persons read both. Find the total numbers of persons reading Times of India and Free Press respectively.

(a) 480 & 800 (b) 488 & 888(c) 488 & 800 (d) 480 & 888 ans=b


3. Out of a total 120 musicians in a club, 5% can play all three instruments - guitar, violin and flute. The number of musicians who can play any two and only two of the above instruments is 30. The number of musicians who can play the guitar alone is 40. What is the total number of those who can play violin alone or flute alone?

(a) 30 (b) 44 (c) 38 (d) 45 ans=b


4. There are three sets of numbers Set I, Set II and Set III. From a given larger set of numbers, 78% of the numbers are at least part of either Set I, Set II or Set III. 50% of the numbers are part of set I, 30% for Set II and 20% for Set III. 5% of the numbers are part of all three sets. What percentage of the numbers are part of more than one set?

(a) 10 (b) 17 (c) 12 (d) 22 ans=d


5. In a group of 76 children, 53 belonged to the Youth Club, 46 to the Sports Club and 40 to the Friends Club. Of these 15 were members of all three clubs, 22 were common to Friends & Sports Club and 23 were common to Youth Club & Friends Club. The number of children common to Youth and Sports Club, who are not members of Friend's club is

(a) 17 (b) 18 (c) 19 (d) 20 ans=b


Directions for Questions 6-10: Read the following information to answer the questions that follow Madhu and Shobha are good in Dramatics and Computer Science.
Anjali and Madhu are good in Computer Science and Physics.
Anjali, Poonam and Nisha are good in Physics and History.
Nisha and Anjali are good in Physics and Mathematics.
Poonam and Shobha are good in History and Dramatics.

6. Who is good in Computer Science, History and Dramatics?

(a) Anjali (b) Madhu (c) Nisha (d) Shobha ans=d


7. Who is good in Physics, Dramatics and Computer Science?

(a) Shobha (b) Poonam (c) Madhu (d) Anjali ans=c


8. Who is good in Physics, History and Dramatics?

(a) Anjali (b) Shobha (c) Madhu (d) Poonam ans=e


9. Who is good in History, Physics, Computer Science and Mathematics?

(a) Poonam (b) Anjali (c) Madhu (d) Nisha ans=b


10. Who is good in Physics, History and Mathematics but not in Computer Science?


(a) Nisha (b) Poonam (c) Madhu (d) Anjali ans=a


11. You have a barrel, filled to the top with water, which weighs 150 pounds. What can you add to the barrel in order to make it lighter?

(a) ice cubes (b) air (c) stones (d) holes ans=??????????????


Directions for Questions 12-14: Read the following information to answer the questions that follow There are six teachers in a school A,B,C,D, E & F in a school. Each of the teachers teaches two subjects, one compulsory subject and one optional subject. - D's optional subject was History while three others have it as a compulsory subject- E and F have Physics as one of their subjects.- F's compulsory subject is Mathematics, which is an optional subject for C and E- History and English are A's subjects but in terms of compulsory and optional subjects, they are the reverse of those of D's- Chemistry is an optional subject of only one of them. - The only female teacher in the school has English as her compulsory subject

12. What is C's compulsory subject?

a) English b) Physics c) Chemistry d) History e) Mathematics ans=d


13. Who among the following has the same compulsory and optional subjects as those of F?

(a) D (b) B (c) None of the other options listed for this question (d) C (e) A ans=c



14. Who is a female member in the group?

(a) A (b) B (c) C (d) D (e) E ans=d


15. Johnny is playing with cubical building blocks. He begins building a giant cube and finds he needs six more blocks to complete the cube. Next, Susan starts building a cube with the same building blocks and has 85 extra building blocks after completing her cube. How many blocks were they playing with?

(a) 155 (b) 270 (c) 210 (d) 189 (e) 201 ans=c

Telephone Interview Etiquette

When you conduct a telephone interview for a job, it is important to show the proper etiquette. Not only is it important, it is critical is you wish to be hired by the company. There are a number of things you will want to do, and other things should never be done.

When you speak to the interviewer, you should never use their first name unless they have specifically told you that it is ok. If they have not, address them by their title. To keep your voice from becoming dry, you will want to have a glass of water nearby.

When you take a sip from the glass of water, make sure your head is away from the phone. Do not allow the interviewer to hear you drinking the water. This is an example of bad telephone etiquette. In addition to this, you will want to avoid eating food while you are talking on the phone. If you are hungry, eat before the interview starts, or wait until the interview is over. Not eating on the phone while you're being interviewed for a job should be common sense, but there are a number of people who do it anyway. It is also important to smile while you are talking to the interviewer. Believe it or not, they will hear it in your voice, even if they cannot see the expression on your face. It is essential for you to convey a friendly impression.

The tone of your voice is extremely crucial during the telephone interview. It could be argued that the tone of your voice during this interview is more important than the tone you use during interviews which are held in person. It is easy to see why some people would believe this. During the telephone interview, the person you're talking to can't see your body language, and they can't watch the expression on your face. It is also not possible for them to see how you are dressed. Because of this, it would seem logical that the tone of your voice places an important role in telephone interview etiquette. Pay attention to the tone of your voice when you speak. Does it sound angry? Do you do have a tone that sounds friendly? Or do you speak with the tone of someone who is annoyed?

If you speak to the interviewer in a tone that is negative, you will automatically have a strike against you. Speaking to them in a friendly manner will tip the odds in your favor. It is always important to speak in a way that is easy for the interviewer to understand. This doesn't mean that you should talk them them like they are a child. Talk to them using a language which is clear and concise. Using slang words is the perfect example of bad telephone etiquette, and is a great example of something that will cause you to fail the interview. Again, while this may sound like common sense, you could do it by accident. Practice avoiding slang words before the telephone interview begins.

It is also important for you to think before you answer a question. The answers that the seem the most obvious may be wrong, it and may take you a moment to realize this. If you answer questions without taking a moment to think about the answer, you may not answer the question correctly. It is also important to make sure you answer the question directly. Avoid giving long answers or explanations. This can be a source of annoyance to the person who is interviewing you. After the interview is completed, take the time to write down the questions you were asked.

Telephone etiquette is important, especially when you are being interviewed for a job. The answers you give to questions and the way your answer them will determine if you are highered.
Note :

All background noises should be silenced during the telephone interview, and you should not eat any food while you are speaking with the interviewer. Speak at an average speed, and use a polite tone at all times. Be prepared for any questions that are asked. Research the company, and be prepared to give a good reason for why you want to work for them.

Jan 9, 2009

Tips for Hr Interview

BASIC TIPS FOR HR INTERVIEW



In a nutshell, an interview is method that is use to show an employer that you have what it takes to work for them. The answers that you give during the interview will play a factor in whether or not you're hired.



In order for you to handle the HR interview successfully, it is important to make sure you're prepared in advance. To be prepared, you must have a knowledge of the job, the industry, and yourself. It is essential for you to pay attention to important details, and some of these include your demeanor and appearance. One of the best tools you can have is knowledge. To begin, lets start with some simple things you will need to know about the interview process.

While it is important for you to research the company and the industry, the first thing that you will need to study is the HR interview process. You should have a good idea of the questions that will be asked during the interview, and you should practice answering them. Many people make the mistake of believing all interviews are the same. However, this is not correct, the interviews will fall under a number of different types. The first interview that you will want to become familiar with is called the screening interview. This is the interview that will often be held by the human resources department. While this interview may be conducted over the telephone, it may also be held in person as well.

The interviewer will have a copy of your resume once the meeting starts, and they will seek to the verify the information that is contained in it. Before they begin interviewing you, they must review your resume to find out if you meet the basic requirements for the job. If you don't the interview will be stopped as this point, and it will not go further. If you do meet the requirements, you will move on to the next step of the interview process. The next step of the hiring process is called the selection interview. This is the interview that can be stressful. Now that the company knows you have the skills to perform the job, they will use this interview to determine if you are better than the other applicants who have applied for the job.

While the screening interview shows that you have the basic job requirements, the selection interview will seek to determine if you have the personality that is required for the position. Even if you meet the requirements for the job, you will not pass this interview if you do not have the right personality. In most cases, the things you do in the first few minutes of the interview will determine if you pass or fail. During the selection interview, you will be up against other people that are qualified, and you may have to go through several meetings to determine if you're qualified. The next interview that is held will be called the group interview.

As the name suggests, the group interviewed is held with a group of applicants who have successfully passed the screening interview and the selection interview. All the applicants will be interviewed at the same time. For the employer, the goal of this interview is to seperate the followers from the leaders. The employers knows that within a group of people, the leaders will naturally become separate from the followers. They will use this situation to determine which applicant will be highered. In addition to this, the employer may also use a group interview to determine how well the applicants work together in a group.

The employer will be looking for a certain type of personality, and the applicant who displays it the most will move on to the next level. It is best to be yourself during the group interview.