Saturday 24 May 2014

The school principal has received complaints from parents about bullying in the school yard during recess. He wants to investigate and end this situation as soon as possible, so he has asked the recess aides to watch closely. Which situation should the recess aides report to the principal?


Seeing four girls surrounding another girl, while in possession of her backpack, is the most suspicious of the incidents described.

Mr. Johnson was to earn £ 300 and a free holiday for seven weeks' work. He worked for only 4 weeks and earned £ 30 and a free holiday. What was the value of the holiday?




What is the smallest number of ducks that could swim in this formation - two ducks in front of a duck, two ducks behind a duck and a duck between two ducks ?

Clearly, the smallest such number is 3.




Three ducks can be arranged as shown above to satisfy all the three given 




Three friends had dinner at a restaurant. When the bill was received, Amita paid 2/3 as much as Veena paid and Veena paid 1/2 as much as Tanya paid. What faction of the bill did Veena pay ?





The film director wants an actress for the lead role of Lucy who perfectly fits the description that appears in the original screenplay. He is not willing to consider actresses who do not resemble the character as she is described in the screenplay, no matter how talented they are. The screenplay describes Lucy as an average-sized, forty something redhead, with deep brown eyes, very fair skin, and a brilliant smile. The casting agent has four actresses in mind.

Actress #1 is a stunning red-haired beauty who is 5'9" and in her mid-twenties. Her eyes are brown and she has an olive complexion.

Actress #2 has red hair, big brown eyes, and a fair complexion. She is in her mid-forties and is 5'5".

Actress #3 is 5'4" and of medium build. She has red hair, brown eyes, and is in her early forties.

Actress #4 is a blue-eyed redhead in her early thirties. She's of very slight build and stands at 5'.

Actresses #2 and #3 possess most of the required traits. They both have red hair and brown eyes, are average-sized, and are in their forties. Actress #1 is very tall and is only in her mid-twenties. She also has an olive complexion. Actress #4 is of very slight build and is in her early thirties. She also has blue eyes.






A farmer built a fence around his square plot. He used 27 fence poles on each side of the square. How many poles did he need altogether ?

Since each pole at the corner of the plot is common to its two sides, so we have :
Total number of poles needed = 27 x 4 - 4 = 108 - 4 = 104.


In a city, 40% of the adults are illiterate while 85% of the children are literate. If the ratio of the adults to that of the children is 2 : 3, then what percent of the population is literate ?

Ans :


Today is Varun's birthday. One year, from today he will be twice as old as he was 12 years ago. How old is Varun today ?

Let Varan's age today = x years.

Then, Varan's age after 1 year = (x + 1) years.

Therefore x + 1 = 2 (x - 12)  x + 1 = 2x - 24  x = 25.


A waiter's salary consists of his salary and tips. During one week his tips were 5/4 of his salary. What fraction of his income came from tips ?




If you write down all the numbers from 1 to 100, then how many times do you write 3 ?

Clearly, from 1 to 100, there are ten numbers with 3 as the unit's digit- 3, 13, 23, 33, 43, 53, 63, 73, 83, 93; and ten numbers with 3 as the ten's digit - 30, 31, 32, 33, 34, 35, 36, 37, 38, 39.

So, required number = 10 + 10 = 20.

If 100 cats kill 100 mice in 100 days, then 4 cats would kill 4 mice in how many days ?




The 30 members of a club decided to play a badminton singles tournament. Every time a member loses a game he is out of the tournament. There are no ties. What is the minimum number of matches that must be played to determine the winner ?


Clearly, every member except one (i.e. the winner) must lose one game to decide the winner. Thus, minimum number of matches to be played = 30 - 1 = 29.

A tailor had a number of shirt pieces to cut from a roll of fabric. He cut each roll of equal length into 10 pieces. He cut at the rate of 45 cuts a minute. How many rolls would be cut in 24 minutes ?

Ans: Number of cuts made to cut a roll into 10 pieces = 9.

        Therefore Required number of rolls = (45 x 24)/9 = 120.

In a garden, there are 10 rows and 12 columns of mango trees. The distance between the two trees is 2 metres and a distance of one metre is left from all sides of the boundary of the garden. The length of the garden is ?

Ans:

Each row contains 12 plants.

There are 11 gapes between the two corner trees (11 x 2) metres and 1 metre on each side is left.

Therefore Length = (22 + 2) m = 24 m.

In a class of 60 students, the number of boys and girls participating in the annual sports is in the ratio 3 : 2 respectively. The number of girls not participating in the sports is 5 more than the number of boys not participating in the sports. If the number of boys participating in the sports is 15, then how many girls are there in the class ?

Ans: 

 Let the number of boys and girls participating in sports be 3x and 2x respectively.

Then, 3x = 15 or x = 5.

So, number of girls participating in sports = 2x = 10.

Number of students not participating in sports = 60 - (15 + 10) = 35.

Let number of boys not participating in sports be y.

Then, number of girls not participating in sports = (35 -y).

Therefore (35 - y) = y + 5   2y  30   y = 15.

So, number of girls not participating in sports = (35 - 15) = 20.

Hence, total number of girls in the class = (10 + 20) = 30.

There are deer and peacocks in a zoo. By counting heads they are 80. The number of their legs is 200. How many peacocks are there ?

Ans: 

Let x and y be the number of deer and peacocks in the zoo respectively. Then,

x + y = 80 ...(i) and

4x + 2y = 200 or 2x + y = 100 ...(ii)

Solving (i) and (ii), we get) x = 20, y = 60.

A man wears socks of two colours - Black and brown. He has altogether 20 black socks and 20 brown socks in a drawer. Supposing he has to take out the socks in the dark, how many must he take out to be sure that he has a matching pair ?

Ans:
         Since there are socks of only two colours, so two out of any three socks must always be of the same color.

Mac has £ 3 more than Ken, but then Ken wins on the horses and trebles his money, so that he now has £ 2 more than the original amount of money that the two boys had between them. How much money did Mac and Ken have between them before Ken's win ?

Ans :

Let money with Ken = x. Then, money with Mac = x + £ 3.

Now, 3x = (x + x + £ 3) + £ 2   x = £ 5.

Therefore Total money with Mac and Ken = 2x + £ 3 = £ 13.

In a class, there are 18 boys who are over 160 cm tall. If these constitute three-fourths of the boys and the total number of boys is two-thirds of the total number of students in the class, what is the number of girls in the class ?

Ans:  

Let the number of boys be x. Then, (3/4)x = 18 or x = 18 x(4/3) = 24.

If total number of students is y, then (2/3) y = 24 or y = 24 x (3/2) = 36.

Therefore Number of girls in the class = (36 - 24) = 12.


A man has Rs. 480 in the denominations of one-rupee notes, five-rupee notes and ten-rupee notes. The number of notes of each denomination is equal. What is the total number of notes that he has ?

Let number of notes of each denomination be x.

Then, x + 5x + 10x = 480  16x = 480   x = 30.

Hence, total number of notes = 3x = 90.

What is the product of all the numbers in the dial of a telephone ?

Since one of the numbers on the dial of a telephone is zero, so the product of all the numbers on it is 0.

Friday 23 May 2014

For boys, the average number of absences in the first grade is 15 with a standard deviation of 7; for girls, the average number of absences is 10 with a standard deviation of 6. In a nationwide survey, suppose 100 boys and 50 girls are sampled. What is the probability that the male sample will have at most three more days of absences than the female sample?

The correct answer is B. The solution involves four steps.

Find the mean difference (male absences minus female absences) in the population.
μd = μ1 - μ2 = 15 - 10 = 5

Find the standard deviation of the difference.
σd = sqrt( σ12 / n1 + σ22 / n2 )
σd = sqrt(72/100 + 62/50) = sqrt(49/100 + 36/50) = sqrt(0.49 + .72) = sqrt(1.21) = 1.1

Find the z-score that produced when boys have three more days of absences than girls. When boys have three more days of absences, the number of male absences minus female absences is three. And the associated z-score is
z = (x - μ)/σ = (3 - 5)/1.1 = -2/1.1 = -1.818

Find the probability. This problem requires us to find the probability that the average number of absences in the boy sample minus the average number of absences in the girl sample is less than 3. To find this probability, we enter the z-score (-1.818) into Stat Trek's Normal Distribution Calculator. We find that the probability of a z-score being -1.818 or less is about 0.035.

A girl counted in the following way on the fingers of her left hand : She started by calling the thumb 1, the index finger 2, middle finger 3, ring finger 4, little finger 5 and then reversed direction calling the ring finger 6, middle finger 7 and so on. She counted upto 1994. She ended counting on which finger ?

Clearly, while counting, the numbers associated to the thumb will be : 1, 9,17, 25,.....
i.e. numbers of the form (8n + 1).
Since 1994 = 249 x 8 + 2, so 1993 shall correspond to the thumb and 1994 to the index finger.

A woman says, "If you reverse my own age, the figures represent my husband's age. He is, of course, senior to me and the difference between our ages is one-eleventh of their sum." The woman's age is

Let x and y be the ten's and unit's digits respectively of the numeral denoting the woman's age.
Then, woman's age = (10X + y) years; husband's age = (10y + x) years.
Therefore (10y + x)- (10X + y) = (1/11) (10y + x + 10x + y)
 (9y-9x) = (1/11)(11y + 11x) = (x + y)  10x = 8y  x = (4/5)y
Clearly, y should be a single-digit multiple of 5, which is 5.
So, x = 4, y = 5.
Hence, woman's age = 10x + y = 45 years.

A pineapple costs Rs. 7 each. A watermelon costs Rs. 5 each. X spends Rs. 38 on these fruits. The number of pineapples purchased is

A, B, C, D and E play a game of cards. A says to B, "If you give me three cards, you will have as many as E has and if I give you three cards, you will have as many as D has." A and B together have 10 cards more than what D and E together have. If B has two cards more than what C has and the total number of cards be 133, how many cards does B have ?

Clearly, we have :
B-3 = E ...(i)
B + 3 = D ...(ii)
A+B = D + E+10 ...(iii)
B = C + 2 ...(iv)
A+B + C + D + E= 133 ...(v)
From (i) and (ii), we have : 2 B = D + E ...(vi)
From (iii) and (vi), we have : A = B + 10 ...(vii)
Using (iv), (vi) and (vii) in (v), we get:
(B + 10) + B + (B - 2) + 2B = 133  5B = 125  B = 25.

Two bus tickets from city A to B and three tickets from city A to C cost Rs. 77 but three tickets from city A to B and two tickets from city A to C cost Rs. 73. What are the fares for cities B and C from A ?

Let Rs. x be the fare of city B from city A and Rs. y be the fare of city C from city A.
Then, 2x + 3y = 77 ...(i) and
3x + 2y = 73 ...(ii)
Multiplying (i) by 3 and (ii) by 2 and subtracting, we get: 5y = 85 or y = 17.
Putting y = 17 in (i), we get: x = 13.

How to take complete backup of mysql database using mysqldump command line utility

mysqldump -u username -p db1 > backup.sql

Thursday 22 May 2014

How can i fetch data from database in php using mysql ?

<?php
// 1. Enter Database details
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'database name';

// 2. Create a database connection
$connection = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$connection) {
    die("Database connection failed: " . mysql_error());
}

// 3. Select a database to use 
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
    die("Database selection failed: " . mysql_error());
}

$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ");

while ($rows = mysql_fetch_array($query)) { 
   $name = $rows['Name'];
   $address = $rows['Address'];
   $email = $rows['Email'];
   $subject = $rows['Subject'];
   $comment = $rows['Comment']

   echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";      


?>

How to retrieve data from Database ? and Display to JTable

write this code in below constructor :

DefaultTableModel model;
model = new DefaultTableModel(null,col);

        jTable1.setModel(model);

        int l2 = jTable1.getRowCount();
        while(l2>=1)
        {
            model.removeRow(0);
            l2 = l2-1;
        }

What are the new features added to Servlet 2.5?

  • A new dependency on J2SE 5.0
  • Support for annotations
  • Loading the class
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications

What are the uses of Servlet?

     Typical uses for HTTP Servlets include:
  • Processing and/or storing data submitted by an HTML form.
  • Providing dynamic content, e.g. returning the results of a database query to the client.
  • A Servlet can handle multiple request concurrently and be used to develop high performance system
  • Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

What are the advantages of Servlet over CGI ?

       Servlets have several advantages over CGI:
  • A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
  • A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications



   What is CGI ?

                  The Common Gateway Interface (CGI) is a standard for writing programs that can interact through a Web server with a client running a Web browser. These programs allow a Web developer to deliver dynamic information (usually in the form of HTML) via the browser. A CGI program can be written in any language, including Java, that can be executed by your Web server. CGI programs are commonly used to add search engines, guest-book applications, database-query engines, interactive-user forums, and other interactive applications to Web sites.

      In very basic terms, a CGI program must interpret the information sent to it, process the information in some way, and generate a response that will be sent back to the client.
     
       Most of the input to a CGI program is passed into it through environment variables. This article will demonstrate how to send these environment variables to a Java CGI program. The rest of the input (if any) is passed into a CGI program as standard input that can be read directly by your program.
    The processing can be as simple as appending information to a file or as complex as requesting data from a database.

Since a CGI program can return a myriad of document types, a CGI program must place a short header (ASCII text) on its output so that the client will know how to interpret the information it generates. Most commonly, CGI programs generate HTML. Below, you will find a library of functions including one that generates the appropriate header for HTML. Following the header, a CGI program simply generates the body of the output in its native form.

Passing the CGI environment into the Java program..

     Writing a CGI program in Java is fairly easy to do once you understand the issues. First and foremost, you need to wrap the execution of the Java program inside another script. So, the actual script invoked on your Web server will be a Unix shell script or a Windows batch file (or equivalent) that simply passes the CGI environment variables into your Java program.

Since Java no longer provides a method to access environment variables directly (theSystem.getenv() method has been disabled in the latest release of the JDK), I propose passing each CGI environment variable into the Java program using the -D command-line parameter on the Java interpreter. I will show you how to use the -D parameter below.

The library of functions I provide below assumes that you have used the approach described above; it uses theSystem.getProperty() method to access those command-line parameters. If your program needs to use any of the CGI environment variables, you can access them the same way. For example, if you want to access the SERVER_NAME environment variable, you could do so as follows:
                                      
                              String server_name =  
System.getProperty("cgi.server_name");  
 

Be aware that I am not passing all of the CGI environment variables into my Java program. I'm only passing the major ones. I'll leave the inclusion of the others as an exercise for the reader.  
 
The following example shows a Unix script file called hello.cgi invoking a Java program called hello. Note that the -D command-line parameter passes the CGI environment variables into the Java program:


#!/bin/sh
java     -Dcgi.content_type=$CONTENT_TYPE     -Dcgi.content_length=$CONTENT_LENGTH     -Dcgi.request_method=$REQUEST_METHOD     -Dcgi.query_string=$QUERY_STRING     -Dcgi.server_name=$SERVER_NAME     -Dcgi.server_port=$SERVER_PORT     -Dcgi.script_name=$SCRIPT_NAME     -Dcgi.path_info=$PATH_INFO   hello


Difference between get and load in Hibernate?

              get vs load is one of the most frequently asked Hibernate Interview question, since correct understanding of both get() and load() is require to effectively using Hibernate. Main difference between get and load is that, get will hit the database if object is not found in the cache and returned completely initialized object, which may involve several database call while load() method can return proxy, if object is not found in cache and only hit database if any method other than getId() is called. This can save lot of performance in some cases

Wednesday 21 May 2014

Thread Methods:

public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.

public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.

public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.

public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.

public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.

public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.

public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.

public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

Create Thread by Implementing Runnable Interface:

If your class is intended to be executed as a thread then you can achieve this by implementingRunnable interface. You will need to follow three basic steps:

STEP 1:

As a first step you need to implement a run() method provided by Runnable interface. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method:
public void run( )

STEP 2:

At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.

STEP 3

Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method:
void start( );

Example:

Here is an example that creates a new thread and starts it running:
class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;
   
   RunnableDemo( String name){
       threadName = name;
       System.out.println("Creating " +  threadName );
   }
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
     }
     System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start ()
   {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread (this, threadName);
         t.start ();
      }
   }

}

public class TestThread {
   public static void main(String args[]) {
   
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   }   
}
This would produce the following result:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Life Cycle of a Thread :

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.




Above-mentioned stages are explained here:
  • New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
  • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
  • Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
  • Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
  • Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities:

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.



What is the use of finally keyword in exception handling?

• In a program where exception is handled using try catch block after this finally keyword is used.
• Finally creates a block that will be executed even after a exception is thrown or not
• If no catch statement matches the exception even then finally block will be executed
• It is executed just before the method return




Example :

class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}

Which is better from Extending Thread class and implementing Runnable Interface?

 Implementing runnable interface is more advantageous because when you are going for multiple inheritance, then only interface can help.
• If you are already inheriting a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread class. 
• Also, if you are implementing interface, it means you have to implement all methods in the interface.
• If we implement runnable interface it will provide better object oriented design
• Implementing also gives consistency
• By using runnable interface we can run the class several times whereas thread have start() method that can be called only once.