Random Number Generator

You might have wondered how predictable machines like computers can generate randomness. In reality, most random numbers used in computer programs are pseudo-random, which means they are generated in a predictable fashion using a mathematical formula. This is fine for many purposes, but it may not be random in the way you expect if you’re used to dice rolls, roulette wheels and lottery draws.

A list of random number is a numerical sequence as defined in Wiki – “A numeric sequence is said to be statistically random when it contains no recognizable patterns or regularities; sequences such as the results of an ideal die roll, or the digits of π (as far as we can tell) exhibit statistical randomness…

We can write a random number generator to generate a list of random numbers in a given range. A random number generator (often abbreviated as RNG) is a computational or physical device designed to generate a sequence of numbers or symbols that lack any pattern, i.e. appear random. Computer-based systems for random number generation are widely used, but often fall short of this goal, though they may meet some statistical tests for randomness intended to ensure that they do not have any easily discernible patterns. Methods for generating random results have existed since ancient times, including dice, coin flipping, the shuffling of playing cards, the use of yarrow stalks in the I Ching, and many other techniques.

Intuitively, an algorithmically random sequence (or random sequence) is an infinite sequence of binary digits that appears random to any algorithm. The definition applies equally well to sequences on any finite set of characters. Random sequences are key objects of study in algorithmic information theory.

I had written a small program in Java to generate a sequence of unique random numbers within 20.

The program is here: Random Number Generator

I am creating a List in which I intend to store unique number between 1 and 20 (inclusive). Firstly, I have to get hold of the object of class Random In order to store only unique numbers, first I check after generating the random number by

rd.nextInt(20);

whether that number already exists in the list. And, thats it. You have got a list of unique random numbers between 1 and 20.

Blogged with Flock

Tags: , , , ,

Advertisements

JDBC Prepared Statements

A Prepared Statement forces a SQL statement to be set to the database immediately where it will be precompiled. This means that for subsequent calls, the SQL statement can just run the Prepared Statements’ SQL statement without having to compile it with every call. A Prepared Statement is most useful when using a SQL statement that accepts parameters that may change with every call. I’ll demonstrate this technique using a MySQL database.

Below is a method that sends a Prepared Statement to the database with two parameters: “userId” and “password”. Notice that it calls the getConnection () method from a class instance called dataUtil. We’ll talk about this class in a second for completeness.


    public ResultSet viewItem (int journalId, int userId) throws SQLException {
        ResultSet rs = null;
        String sql = "SELECT journal_id, date_added, journal_text FROM journal" +
                                                                 "WHERE journal_id = ? AND user_id = ?";

        Connection conn = dataUtil.getConnection();

        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1, journalId);
        preparedStatement.setInt(2, userId);

        rs = preparedStatement.executeQuery();

        return rs;
    }


As I mentioned above, I wanted to show you how to use the getConnection method, because after all, if you can’t connect to a database you can’t execute a Prepared Statement. It will return an open Connection object for our Prepared Statement to use. The SERVER and DATABASE constants you would replace with your server address and database name, and the USER and PASS constants would obviously be your database username and password. This method requires the MySQL Connector/J JDBC driver. You can grab this at http://www.mysql.com


    public Connection getConnection() {
        try {
            Class.forName("org.gjt.mm.mysql.Driver");

            Properties connProp = new Properties();
            connProp.put ("user", USER);
            connProp.put ("password", PASS);
            connProp.put ("useUnicode", "false");

            Connection con = DriverManager.getConnection("jdbc:mysql://" + SERVER + "/" + DATABASE, connProp);
            return con;

        }catch (ClassNotFoundException cnf){
            return null;
        }catch (SQLException ex) {
            return null;
        }
    }

Notice that we first declare a variable to represent the SQL statement, and assign the SQL to it:

                    String sql = "SELECT journal_id, date_added, journal_text 

						FROM journal WHERE journal_id = ? AND user_id = ?";
The values that we will be sending to the database are represented by "?". Next we call our

getConnection () method to get our connection object and then define our Prepared Statement,

and then append our parameters to the Prepared Statement with these lines.
			preparedStatement.setInt(1, journalId);

 		preparedStatement.setInt(2, userId);
Notice that you should use the correct set method depending on the data type of the field you are

assigning the value to (see References below). All that's left to do is to execute the Prepared Statement

and to return the result set.

Reference: java.sun.com


Blogged with Flock

Comet: Reverse Ajax for streaming data from the server

Daniel Rubio has written an article called “Comet: Reverse Ajax for streaming data from the server,” describing ‘Comet,’ a technology to push events from the server side to a browser client. Comet manages to avoid the issues related to having a browser poll a server to check for new events.

Ajax, or Asynchronous JavaScript and XML, has become a household name in the area of Web applications, this mechanism by which a browser accesses a RESTful Web service and updates its GUI without a screen refresh, has spread from its pioneering roots in on-line maps and calendars to pretty much a standard feature in most new Web applications. However, it was not until recently that a new term was coined to complement this approach, one which is now often dubbed reverse-Ajax, its name: Comet.

The first thing you need to realize is that the data service on the server side needs to be designed to hold state on behalf of browsers clients, a process that can either be very difficult or very easy, depending on the platform and language you are using. Once again, this takes us to the stateless nature of Web applications and the way a browser needs to identify itself constantly either via cookies or session IDs, or what some characterize as the Hollywood principle – “don’t call us we’ll call you” – referring that only a browser is equipped to make calls and never vice-versa.


This last issue takes us down the road of building an asynchronous server application, or if you prefer a fancier name, an HTTP-based event routing bus, or in other words, a latent application on the serverside able to keep track of clients wishing to receive updates, a design very much in line with the messaging systems used in enterprise systems that are based on publish/subscribe channels.


However, since this last mechanism represents a departure from the “bread and butter” approach used in most Web platforms, it is a big reason why most Comet applications today rely on either custom adapted application-servers or embeddable versions that can tackle these issues. In the particular case of Java, Jetty and Grizzly are two servers that currently have out-of-the box support for Comet-type designs, with varying support in other languages like Python and other popular Java servers like Tomcat, for what is technically known as “continuation support,” a paradigm by which applications are shielded from the stateless nature of the Web. Continuation support also is a touted feature of higher-level language Web frameworks written in Smalltalk and Lisp that have this capability.


Turning our attention to the client side of things, a browser can take various routes to stay in contact with these type of server applications. Among these approaches are long-polling, dynamic script tags and inclusively a workaround using IFrames, none are standard approaches by any means, which is yet another reason why many client side Comet designs rely on the use of frameworks to abstract away incompatibilities between browser implementations – similar to Ajax – with one such framework being Dojo, which in itself now serves as both an Ajax/Comet framework.

Of course, the term Comet itself is something to wonder about. AJAX’ meaning is fairly well-known, as “Asynchronous Javascript and XML,” but what about Comet?

As far as the actual term is concerned, Comet emerged as a pun to Ajax’s meaning outside IT circles as a household cleaner. But quirky name or not, Comet is serving the purpose of an umbrella name for delivering data onto browsers as it becomes available on the serverside, a technique that will surely be of the same impact and go hand in hand with what we know today as Ajax.

and I am back!!

It was the loveliest holiday I ever had (in fact, I can say this was the first). Enjoyed the whole thing… took some photographs, really loved that part… realized my interest… photography… thinking of doing some course in it… some of the pics are here…

dscn1112.jpg
PGR-SKY
dscn1102.jpg

Ant – an introduction

Ant is a Java based build tool developed as part of the Apache Jakarta project. You can get it from the Ant home site: ant.apache.org. At first the usefulness of Ant may not be readily apparent, but after using it for awhile on even small projects you may be surprised at how much you come to rely on it. For example, the ability to build files into specific directories, generate JavaDoc and package classes into JAR files for deployment all in one keystroke is extremely powerful. Here is a non-exhaustive list of what Ant can do:

  • Extract source from a version control system
  • Create directories
  • Delete directories
  • Compile code
  • Generate JavaDoc
  • Jar files
  • Copy files
  • Generate e-mail
  • FTP files
  • Execute SQL statements
  • Run unit tests

After downloading and unzipping the download contents, copy the Ant directory to the root of your C:\ drive, so the path is “C:\Ant”. You can install it anywhere you want, but this is most convenient. We also have to set up some environment variables so that the system can find Ant when we need it. You need to add System Variable called ANT_HOME, set this to the directory where you put Ant, in this case “C: \Ant”. Make sure there is also a System Variable called JAVA_HOME that point to your Java SDK directory.

We’re almost done. Now all you have to do is add the above variables to your path. Look for the “PATH” environment variable under System Variables and click “Edit”. Add this to the end of the path:

;%JAVA_HOME%\bin;%ANT_HOME%\bin

Notice that entries in the path on Windows are delimited by “;”. Now restart your machine to make sure the environment variables stick. We’re almost ready to test our installation. Open up a command window and type: ant. If the above steps went well, then you should see your first Ant error message:

D:\>ant

Buildfile: build.xml does not exist!
Build failed

This means that the installation worked. If you got anything other than this, then more than likely one of the above installation steps weren’t performed.

Ant requires a couple of things to run: Java source files (obviously), and a build file. First we’re going to create a really simple Java program for Ant to build.

public class AntTest{
public AntTest(){
System.out.println(“Isn’t Ant cool?”);
}

public static void main(String[] args){
new AntTest();
}
}

Don’t try to compile it yet, we’re gonna let Ant do that. The next thing we need is the build file.

<project name=”AntExamplel” default=”dist” basedir=”.”>
<!– set global properties for this build –>
<property name=”src” value=”.”/>
<property name=”build” value=”build”/>
<property name=”dist” value=”dist”/>

<target name=”init”>
<!– Create the time stamp –>
<tstamp/>

<!– Create the build directory structure used by compile –>
<mkdir dir=”${build}”/>
</target>

<target name=”compile” depends=”init”>
<!– Compile the java code from ${src} into ${build} –>
<javac srcdir=”${src}” destdir=”${build}”/>
</target>

<target name=”dist” depends=”compile”>
<!– Create the ${dist}/lib directory –>
<mkdir dir=”${dist}/lib”/>

<!– Put everything in ${build} into the AntTutorial-${DSTAMP}.jar file –>
<jar jarfile=”${dist}/lib/AntExample-${DSTAMP}.jar” basedir=”${build}”/>
</target>

<target name=”clean”>
<!– Delete the ${build} and ${dist} directory trees –>
<delete dir=”${build}”/>

<delete dir=”${dist}”/>
</target>
</project>

Make sure that you saved the build.xml file in the same directory as the Java source file. We’re not going to get into what the build file is actually doing yet, so just trust me…

Now, in your command window, cd to the directory where the Java source and the build file are saved (a lot of tutorials leave this step out, strangely enough) and type “ant“. Hopefully you will see the BUILD SUCCESSFUL message at the bottom. Now check out the directory. You’ll notice that there are two new directories: “build“, and “dist“. These directories were built by Ant. The “build” directory will include the compiled Java class file(s) and the “dist” directory will contain a .jar file with our project name and a timestamp.

Reference: http://ant.apache.org/manual/index.html

Tags: , ,