Oct 12, 2010

clojure looping

There are many ways of creating loops in clojure. In this  I will give some of them.

The first way is,

user=>(loop [i 1]
                 (when (< i 20)
                 (println i)
                 (recur (+ 2 i))

This will create a loop like 1, 3, 5 ... . There are some other ways  which  gives the  same output.

         (for [i (range 1 20 2)]
         (println i)))

user=>(doseq [i (range 1 20 2)]
           (println i))

Mutual Recursion
In clojure mutual recursion is little bit harder than the other languages.
This is a simple coding to check a given number is an even or an odd number.

(def even)
(defn odd [n]
  (if (zero? n)
      (even (dec n))))
(defn even [n]
  (if (zero? n)
      (odd (dec n))))

So try this by typing,
(even 13)
It will give tho output as false.

(ns example.otherns
  (:require example.mylib))
(defn check-size
  (if (too-small x)
    (example.my)flib/add1 x)
We can defined our own libraries and can use in many programs without retyping it again and again. As a test library lets try this. Write this coding in a directory called example with the name of mylib.clj. In that file you can write like this.
(ns example.mylib)
(defn add1
  (add x 1))

And in your program you can try by this coding
(ns example.otherns
  (:require example.mylib))
(defn check-size
  (if (too-small x)
    (example.mylib)flib/add1 x)

or else you can use like this also
(ns example.mylib
  (:load "mylib/add1"
This will add more lib files to the mylib library file. Those shoulb be plased in a director called mylib in exsample directory.

HTML output from a haskell

Haskell is a programming language which is capabler of creating dynamic and static web pages. Now I will explain how to create a static web page by using haskell.
First of all you may install these modules to run your program. Install these things by using cabal module installer. Module is Html. If you get errors, read those error messages and try to install other needed modules.

In the program you should
import Text.Html

This will load all the relevant html things to the program.
So now we try to write a basic html codes.

page = [
   body<< [
     p<< "First paragraph",
     p<< "First Paragraph"
main = putStrLn  $ renderHtml page

Then you must run it like this,
runhaskell filename.hs
This will print some things with html tags.

So we can modify this as we need. We can insert a title, background colour like this.

      = header
        << thetitle
           << "My Haskell Home Page"
   +++ body ! [bgcolor "#aaff88"] << " "

main = putStrLn $ renderHtml htmlPage

Now we can add details to this program in order  to add content into the web page. For that only you shoula modify the line "+++ body ..." to some thing like this.
+++ bopdy ![bycolor "#aaaaaa"] << bodyCon
Now this will search for "body" key word. We must add the content to that like;

bodyCon = p ! [align "center"] << "This is the content of body tag"

You can add more thing to the body of your html page. So we can try,

bodyCon = p ! [align "center"] << "This is the body of the html page"
          +++ p << "second p tag"
          +++ table ! [border 2]<< tableCon

tableCon = (col1_r1 `above` col1_r2) `beside` (col2_r1 `above`col2_r2)
        col1_r1 = td << "col1 r1"
        col1_r2 = td << "col1 r2"
        col2_r1 = td << "col2_r1"
        col2_r2 = td << "col2_r2"

You can see in this coding I had use two p tags and one table. Likewise we can create hole html page from this.

Up to this point we can get a html output to the screen. But we need to create a html page without printing this to the stdout.
So to do that we must modify the main in the coding to this.

main = writeFile "haskell.htm" (renderHtml htmlPage)

Now this will create a html file in the working directory. You can view  it by using a web browser.
You can make this page dynamic by adding more functions to create dynamic content.

Oct 11, 2010

Infinite data source - Clojure

As the other programming languages we can get number sequences in clojure too.
We can get a list of sequence numbers from a function like;
user=>(def num (iterate inc 0))
This will create an infinite list starts from 0. We can get a list of sequence numbers by;
user=>(take 10 num )
This will give a list from 0 to 9, 10 incriments.
If i need a list from 10 to some amount, it is like;
user=>(def num_2 (iterate inc 10 ))
user=>(take 5 num_2)

List comprehension

Think if I need to get a list of numbers which can be devide by 4 and I need to add 1 to that number.

user=>(def num_1(iterate inc 0))
user=>(def num_4p1 (for [x num_1 :when(zero? (rem x 4))](inc x)))
Then to get 5 of these things,
user=>(take 5 num_4p1)
This will give an output;
This is not the only way of creating sequences. We can use maps and filters to do this type of task and get the sane output.
user=>(def x (map inc (filter (fn [x] (zero? (rem x 4))) num_1)))

Sequence functions

function - (first coll)

This gives the first element of a list like,
user=>(first (list 12 43 546 75))
If the function is empty it will return nil as the result,
user=> (first (list))

Function - (rest coll)

This gives the result without the first element. It is like;
user=> (rest (list 12 23 35)
(23 35)

Function - (map x  coll*)

Apply x laizy to each item in the sequence.
user=> (map (fn [x] true) (range 4))
(true true true true)

Not only the true but alsom we can do other calculations as well.
So it may like this;
(map (fn [x] (* 5 x))(range 10))
In this function it will multiply all the numbers fron 0 to 9 by 5, and give the output as,
(0 5 10 15 20 25 30 35 40 45)

We can use this to get a x*x kind of list, like;
user=>(map (fn [a b] (* a b)) (range 5) (range 5))
This gives the out put as,
(0 1 4 9 16)

function - (every? pred coll)
This will return true is the "pred" value is always true in a sequence.
Try this out,
user=>(every? pos? (range 10))
This will give the output as "false"
The "pos?" will return true if the value is greater than 0, so in this range the first element is 0. The output is like first one is false and others are true.
You can modify this like;
user=>(every? pos? (range 1 10))
Now the result will be true, becouse of, all values are more than 0.

In this it will get the values from 1 to 10, try to devide it from 2 and check wether there remaining parts are  equal to 0.
(every? (fn [x] (= 0 (rem x 2))) (range 1 10))
This will give the result as "False " because of some elements remaining parts are not equal to 0. So we can modify this function like this.
(every? (fn [x] (= 0 (rem x 2))) (range 2 10 2))
This function will get a list like (2 4 6...). So these all numbers will give its remainder as 0 when it devides by 2. Thats why this value is "true"

 function - (not-every? pred coll)
This is like same as the (every? ) function, the only difference is when "every?" is giving true "not-every" will give the output as "false". It gives the complement of the "every?" function.

Oct 6, 2010

Clojure Namespace

This is required to load clojure libraries, use to reffer curent namespaces and
to import java classes. We can use these pre defined source codes in our progrms. These are for commen need in most of programs.
Load a clojure library you can use,
(require 'clojure.contrib.math)
and to print all the loaded namespaces,
If you need to load and reffer all at onec, you can use this command,
(use 'clojure.something.something)
And if you only need to reffer to a singl thing you can use
(use '[clojure.some.some :only (thingYouNeed)])

Importing Java libraries and classes

Think if you need to import java IO file in you clojure program you can do it by writing;
(import java.io.File)
If you need to import classes from a java package you can use;
(import [java.util Date Random])
This will import both Date and Random in util package.

Writing clojure programs

We can write a clojure program and store it in a seperate file and we can use it by calling that file. So to do that we can use java namespaces. If the namespace is like com.my-app.util, your clojure file should be placed in file structure
like com/my-app/util.clj. So we must begin the file with namespace as ;
(ns com.my-app.util)

So let's do a test program.
First create a folder called student in the directory where the clojure.jar placed. Then write this coding to a file called name.clj .
(ns student.name)
(defn my_name [sentence] (str "Welcome " sentence "...!"))

Now run the clojure.jar file and import this clojure file to the interpreter by;(use 'student.name)
Then try this;
(my_name "Thilina")
It will give the output as;
Welcome Thilina...!

Oct 5, 2010

Automating a svn project by using hudson

Hudson is a continues integration system. It can monitor executions of a job continuously.
Hudson can use to monitor SVN projects and CVS projects. It can build a project at a given time and in a given frequency. User can setup it to build a project when some one commit the project.
The build can be done by invoking Mavan, Ant, Windows batch command or even a shell script. And also user can get a feedback to his/her e-mail.
The best thing is a it got very user friendly web interface where the all configurations take part.

Now we are going to setup hudson, to execute svn project with the help of Mavan. As I sad before, this is a web based thing we need to install apache tomcat server. So download it from the apache website and install it. Also you may need to install JDK in order to work properly. Now you may need to install mavan too. Download mavan from the apache site and install it. Make sure that you  are installing the stable versions of all these software.
While installing, check that you are make path variables as in the software installation document.
If javac, mvn and apache tomcat things are working properly, you can download the hudson. Go to hudson website and download a .WAR file. Stop the tomcat server and move the .WAR file into webapps folder in the tomcat server. Then start the web server. Server will execute the .WAR file and it will put hudson live. You will be able to use hudson by visiting http://localhost:8080/hudson URL. So up to this point we had setup the hudson. Now we should configure hudson to build a project.
To do that, go to new job and select "Build a free-style software project". Then it will give a form like thing to fill. That is the place you can configure the build. Give a name and fill other relevant fields as you need. Then in the source code management section choose subversion and give the URL where the svn project is located. Then you can move to build triggers. If you only need to build if someone commit the svn, you should use "pool scm". We will use mavan to build our project so, we invoke Mavan. In the goals field write the mavan commands without "mvn" word. Finally in the post build action section you can set E-mail notifications too.
Now when ever you commit that project it will automatically build the project. And if there any build fail, it will send a e-mail notification.

Installing Windows XP in Linux installed disk

The best way to install linux and windows in a same disk is, first install windosws in a seperate partition and then install the Linux OS. This way is the most shortest  way to make a dual boot machine.
But in some cases we may need to install a windows OS where a linux OS is running. If there is no free space to install windows it makes this tark much harder. In a case of that we muts use a tool like GParted to edit an excisting partition and make free space to windows. After editing the partition we must update the grub, which is the boot loader of the linux OS.
Then we can install the windows partition. But keep in mind, the windows partition needs extra 8Mb space also. So when you are making the partitions make sure to keep some free space. This instillation will deactivate the Linux partition when it installing its boot loader.
Now you will load only the windows OS. YOu may not see the linux partitions in when you are in windows, and also do not change or delete any of these partition.
Then reboot the system and insert linux cd, the bootable cd which you use to install the Linux OS. Boot the system by recovery option and login to your local machine. In fedora it may cay to use chroot /mnt/sysimage. Then change the user to root by typing su. Then check the disk partitions by typing "fdisk -l" command. It will list down the partitions and "*" will show what is the bootable partition. Now you should activate the linux partition by the help of fdisk command. Now we must get a backup of the boot details by doing "dd" like this;
dd if=/dev/sda1 of=/fedora.bin bs=512 count=1
For "if", you must give the partition where the linux partitions are located in. Then mount the windows partition and mv the fedora.bin file to the root "c:\ drive" of the windows partition. Then edit the boot.ini file in the root of windows to;
c:\fedora.bin="Linux Fedora"
And make sure you change the time of the boot menu display. Then reboot the system. Now you can see there are two boot options in the windows bootloder. Select one of it and use it.
If the linux options gives errors you can use grub as the bootloder which is the default bootloder of the fedora. To do that you should again reboot and boot the system with the linux cd in recovery mode. Then update the grub by typing these commands;
root (hd0,0)
setup (hd0)
In this "hd0" means the hard disk which the linux is installed and the (partition number-1) is 0. Likewise you should setup the root (hd#,#) to Linux and reboot the machine. Then after reboot again it will not show the windows and directly boot the Linux. So login as root and add these to the menu.lst file like this.
title Windows
    rootnoverify (hd0,1)
    chainloader +1

As previous you should say where the windows boot files are located in.
Now after restarting the machine you may able to use both operating systems.