When you know a thing, to hold that you know it, and when you do not know a thing, to allow that you do not know it - this is knowledge. -Confucius-

The gift of fantasy has meant more to me than my talent for absorbing positive knowledge. -Albert Einstein-

Science investigates religion interprets. Science gives man knowledge which is power religion gives man wisdom which is control. -Martin Luther King, Jr.-

Those who have knowledge, don't predict. Those who predict, don't have knowledge. -Lao Tzu-

Our treasure lies in the beehive of our knowledge. We are perpetually on the way thither, being by nature winged insects and honey gatherers of the mind. -Friedrich Nietzsche-

Wednesday, July 31, 2013

Test Driven Development example - Part 4 (Simple Unit Testing for Java with NetBeans)

Lets code the all tests in the to do list. (this should be done one by, for the tutorial i used it just to show how to do it)
The FibonacciTest.java file will be look like
 
 
package tdd;

import org.junit.Test;
import static org.junit.Assert.*;
 
public class FibonacciTest {

    @Test
    public void testGetFibonacci_0() {
        int x = 0;
        Fibonacci instance = new Fibonacci();
        int expResult = 0;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_1() {
        int x = 1;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_2() {
        int x = 2;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_3() {
        int x = 3;
        Fibonacci instance = new Fibonacci();
        int expResult = 2;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_4() {
        int x = 4;
        Fibonacci instance = new Fibonacci();
        int expResult = 3;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_5() {
        int x = 5;
        Fibonacci instance = new Fibonacci();
        int expResult = 5;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_6() {
        int x = 6;
        Fibonacci instance = new Fibonacci();
        int expResult = 8;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }
}


Just run the tests and see before progress. :)
we added 4 tests, they will fail.

lets pass the 4th test.
Edit the Fibonacci.java like below to produce the first 4 Fibonacci number correctly
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1 || x == 2) {
            result = 1;
        } else if (x==3) {
            result = 2;
        }
        return result;
    }
}

The result will be

Lets write in the typical way to pass all the test correctly.
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1 || x == 2) {
            result = 1;
        } else if (x == 3) {
            result = 2;
        } else if (x == 4) {
            result = 3;
        } else if (x == 5) {
            result = 5;
        } else if (x == 6) {
            result = 8;
        }
        return result;
    }
}


Then all the tests will be passed. We can do this type of code for every other input as well. But we know that it cannot be done manually :) so we have to seek for a pattern in this input outputs.
And there is a pattern. The nth Fibonacci number is equal to the
(n-1)th Fibonacci number + (n-2)th Fibonacci number
Lets modify the code to produce every Fibonacci number correctly
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int fibNumber = 1;
        if (x == 0) {
            fibNumber = 0;
        } else if (x <= 2) {
            fibNumber = 1;
        } else {
            fibNumber = getFibonacci(x - 1) + getFibonacci(x - 2);
        }
        return fibNumber;
    }
}


Lets check the correctness of the program by some random test cases. :)
Lets add this test to check some other known Fibonacci numbers.
 
 @Test
    public void testFibonacci() {
        Fibonacci fibonacci = new Fibonacci();

        int cases[][] = {{7, 13}, {8, 21}, {9, 34}, {10, 55}, {11, 89}, {18, 2584}, {19, 4181}};
        for (int i = 0; i < cases.length; i++) {
            assertEquals(cases[i][1], fibonacci.getFibonacci(cases[i][0]));
        }

    }


Looks like our code pass those random cases as well. ok now we can assume that our code is working :)

Test Driven Development example - Part 3 (Simple Unit Testing for Java with NetBeans)

Our 2nd task in the to do list is,
[2] getFibonacci(1) ==> 1
now we have a passing code.
we have to make it fail. to that we can ask it the 1st Fibonacci number.
change the FibonacciTest.java file as below.
Here i have introduced a new method for check the result for input 1. Then it will be easy to identify what is going on.
 
 
package tdd;

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

public class FibonacciTest {

    @Test
    public void testGetFibonacci_0() {
        int x = 0;
        Fibonacci instance = new Fibonacci();
        int expResult = 0;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }
    @Test
    public void testGetFibonacci_1() {
        int x = 1;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }
}


Then run the code and see the result. You will see that our first test will pass and the second one is failing. That is because the getFibonacci method only return value '0' for any input.
So our test is failing. And now we have a failing code. :)

Lets make it pass. To do that we have to edit the getFibonacci method to correctly return the first 2 Fibonacci numbers.
Do the following changes in Fibonacci.java file
 
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1) {
            result = 1;
        }
        return result;
    }
}

Run the test file and see the results.

seems it is working :)
our second task is done. lets look at our to do list :)

[1] getFibonacci(0) ==> 0
[2] getFibonacci(1) ==> 1
[3] getFibonacci(2) ==> 1
[4] getFibonacci(3) ==> 2
[5] getFibonacci(4) ==> 3
[6] getFibonacci(5) ==> 5
[7] getFibonacci(6) ==> 8


lets move to our next task
[3] getFibonacci(2) ==> 1
and again we have a passing code. we have to make it fail. when we pass the '2' as input it will fail. make another testing method to do it.
 
 
 @Test
    public void testGetFibonacci_2() {
        int x = 2;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }


result will be looks like

ok our 3rd test is failing. :) lets make it pass. we have to correctly produce first 3 Fibonacci numbers to that.
Edit the Fibonacci.java like below
 
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1 || x == 2) {
            result = 1;
        }
        return result;
    }
}


and the result will be

So we have completed our 3rd task also. :)
we can use if else and do that for any input. A brute force method. But after some time we may able to identify a pattern of the inputs and the out puts.

Test Driven Development example - Part 2 (Simple Unit Testing for Java with NetBeans)

After following the  previous work now we are good to code :)

First of all lets edit the Fibonacci.java file. lets add a new method.

package tdd;
 
public class Fibonacci {

    public void getFibonacci(int x) {
    }
}
Now edit the FibonacciTest.java file like below.
 
package tdd;

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

public class FibonacciTest {

    public FibonacciTest() {
    }

    @Test
    public void testGetFibonacci() {
        fail("The test case is a prototype.");
    }
}

now just right click on the FibonacciTest.java file and run it.
The result will be as below.

Ok now we have a failing code :) We have to make it pass now.
lets make a to do list.

[1] getFibonacci(0) ==> 0
[2] getFibonacci(1) ==> 1
[3] getFibonacci(2) ==> 1
[4] getFibonacci(3) ==> 2
[5] getFibonacci(4) ==> 3
[6] getFibonacci(5) ==> 5
[7] getFibonacci(6) ==> 8

case 1) we have to generate the first Fibonacci number. now we have a failing code. lets make it pass and return the correct answer (0) for input (0)
change the Fibonacci.java files getFibonacci method as follows. So that it return the correct answer to the input '0'. If you remember the 3rd point it says that "we are not allowed to write any more production code than is sufficient to pass the one failing unit test" . so we have a failing test case. We have to write the code only to pass that failing code.
 
 
package tdd;
 
public class Fibonacci {

    public int getFibonacci(int x) {
        return 0;
    }
}


Then change the FibonacciTest.java file as below.
 
 
package tdd;

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

public class FibonacciTest {

    public FibonacciTest() {
    }

    @Test
    public void testGetFibonacci() {
        //fail("The test case is a prototype.");
        
        // this is the xth fibonacci number
        int x = 0;
        //make an instance of the Fibonacci class to access
        //getFibonacci method
        Fibonacci instance = new Fibonacci();
        // this is our expected result
        int expResult = 0;
        // get the actual  result
        int result = instance.getFibonacci(x);
        // this will  check and compare the result and the 
        // expected result. If both match test will pass.
        assertEquals(expResult, result);

    }
}


The comments will help you to understand what is going on. :)
lets run the code and see

wow we have just made our failing test case passed. :)
Our code will correctly return the 0th Fibonacci number (lets use the 0th indexing)
our first task in the to do list is done :)
[1] getFibonacci(0) ==> 0
[2] getFibonacci(1) ==> 1
[3] getFibonacci(2) ==> 1
[4] getFibonacci(3) ==> 2
[5] getFibonacci(4) ==> 3
[6] getFibonacci(5) ==> 5
[7] getFibonacci(6) ==> 8

way to go :)

Saturday, July 20, 2013

Test Driven Development example (Getting started)

There was a workshop in our university to give us an introduction about TDD by OrangeHRM. The followings are based on those experience. 

You can read about TDD here .
Simply the TDD coding process has 3 rules.(for more details refer this)

 1) You are not allowed to write any production code unless it is to make a failing unit test pass.  
 2) You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures. 
 3) You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
 Here i used java and the net beans IDE to do the example.

We have to develop a program which give us the n-th Fibonacci number.

Let's create a new project called TDD first. Then create a new JUnit test. (right click the project and select JUnit test- If it is not there use other option to find it)

First create a class in Source Packages.(name it  Fibonacci )Then create a test class in the Test Packages.(name it FibonacciTest)(Don't worry if you haven't the Test Packages yet, just right click the project and create a new test, it will create a new Test Packages section ). (you can do it in 3 ways)

In the Test Packages ,
1) Create a normal java class and we can import the relevant Unit Test packages later.
2) Create a JUnit test and give the name "FibonacciTest" manually.(This will automatically call the relevant imports)

3) Create a JUnit test class by using Test for Existing class. (It will automatically set the name "FibonacciTest" and will  call  the imports as well)

Then add the JUnit library (here i used JUnit 4.10) to the Test Libraries.

The Project folder structure will  looks like this.


 

Tuesday, July 16, 2013

Create a Chrome extenstion to highlight paragraphs on user click event

I started to create a Google chrome extension to highlight the web content. As the first step i was able to create this extension which highlight the whole "p" tag when a user click on it. There are 4 file. (manifest.json, tabcolor.js ,color.js,popup.html (to call the js files,but not necessary,there are other ways )) the manifest.json file looks like
   
{
  "name": " page color 2.",
  "version": "1.0",
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "browser_action": {
      "default_title": "Set this page's color.",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "manifest_version": 2
}

the popup.html file will looks like
<!doctype html>
<html>
  <head>
    <title>Set Page Color Popup</title>
     <script src="color2.js"></script>
  </head>  
</html>
the color.js file looks like
   

function clickcolor(e) {
   chrome.tabs.executeScript(null,{file : "tabcolor.js"});
   window.close();
}

document.addEventListener('DOMContentLoaded', function () {
     clickcolor();
 
}); 

the tabcolor.js file looks like
  
var divs = document.getElementsByTagName("p");
  
    for(var d in divs) {
    divs[d].addEventListener('click',function(){this.style.background='yellow';}); 
     }
 
It will appears to be like this ,

Thursday, April 4, 2013

SQL TRIGGERs


When we were doing a database project we faced to a little problem when we try to check some constraints on a table on insert , update, delete operations.
There is a table called 'infos' and there is a column called age. The values of the age should be greater than 0. So to check that constraint we used SQL CHECK constrain. It appears to be accepted by mySQL as a valid one but when inserts happens we noticed that it is not working properly. (negative values can also be added as the age).
create table infos (
id        varchar(10) NOT NULL,
name      varchar(30) NOT NULL,
age       int ,
PRIMARY KEY (id),
CHECK (age > 0)
)
After some searching we found that CHECK constraint is not yet implemented in mySQL version that we have and we have to use SQL TRIGGERs for check those constraints.

Here are the things what we found . This is not all about SQL TRIGGERs but this was enough to accomplish our task.

Sometimes we need to control , check , monitor and manage a group of tables whenever an insert, update, or delete operation is performed.
The SQL CREATE TRIGGER statement provides a way for the database management system to actively do those things.
The statements specified in the SQL trigger are executed each time an SQL insert, update, delete operation is performed. These SQL triggers cannot be directly called from an application. They will automatically invoked by the database management system when a insert , update or delete operation take place in a relevant table.
the definition of the SQL trigger is stored in the data base management system and is invoked by the data base management system.

BEFORE SQL triggers
These triggers may not modify the tables. Using these triggers we can check for some constraints before add data to the data base table. And we can use them to modify other values based on the data to be inserted or updated or deleted.

AFTER SQL triggers
These triggers may modify the tables. After make the changes to the table we can check for some constraints or we can update some other tables or the same table values based on the new state of the table.

So let's see how we can use SQL triggers to accomplish that above task.

First we have to create the table.
create table infos (
id         varchar(10) NOT NULL,
name       varchar(30) NOT NULL,
age        int ,
PRIMARY KEY (id)  
)
The Trigger can be define as follows.
delimiter $$
create trigger infos_insert BEFORE insert on infos
for each row
begin
if(
   new.age <0
)then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Error: Invalid age';
end if;
end;
$$
delimiter ;
As the delimiter we define another new one. (the default one is the semicolon )
And this a BEFORE SQL trigger . So the constraints will be checked before the data is entered and data will be entered if and only if the age is greater than 0. (assuming other constraints are satisfied ).
If error occurs (age is not valid) message will be displayed. We can catch this in our application also.

Inside the 'if section' we can have complex SQL parts also.
Assume that we want to insert persons to infos table only such that no 4 persons can have the same age.
To check that constraint we can use the below trigger.
(Some versions of MySQL doesn't yet support 'multiple triggers with the same action time and event for one table')
delimiter $$
create trigger infos_insert BEFORE insert on infos
for each row
begin
if(
(select count(*) as counts   from infos
where age =new.age
group by age )+1 >3 
)then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Error: Maximum ageGroup limit reached';
end if;
end;
$$
delimiter ;

Friday, November 2, 2012

C# Socket Programming



As with Java we can use C# to handle Sockets in our computers. The Socket Basics are the same as described in here.

But there are some different key words which C# use to  play with Sockets. Some of them are described as below. (Found them on the internet). They will give some brief explanation about those words. (Actually those words represent C# classes and Methods)

GetStream returns a NetworkStream that you can use to send and receive data. The NetworkStream class inherits from the Stream class, which provides a rich collection of methods and properties used to facilitate network communications.

The NetworkStream class provides methods for sending and receiving data over Stream sockets in blocking mode.

You must call the Connect method first, or the GetStream method will throw an InvalidOperationException. After you have obtained the NetworkStream, call the Write method to send data to the remote host. Call the Read method to receive data arriving from the remote host. Both of these methods block until the specified operation is performed. You can avoid blocking on a read operation by checking the DataAvailable property. A true value means that data has arrived from the remote host and is available for reading. In this case, Read is guaranteed to complete immediately. If the remote host has shutdown its connection, Read will immediately return with zero bytes.
You must close the NetworkStream when you are through sending and receiving data. Closing TcpClient does not release the NetworkStream.

The TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode.

The TcpListener class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. You can use either a TcpClient or a Socket to connect with a TcpListener. Create a TcpListener using an IPEndPoint, a Local IP address and port number, or just a port number. Specify Any for the local IP address and 0 for the local port number if you want the underlying service provider to assign those values for you. If you choose to do this, you can use the LocalEndpoint to identify the assigned information.
Use the Start method to begin listening for incoming connection requests. Start will queue incoming connections until you either call the Stop method or it has queued MaxConnections. Use either AcceptSocket or AcceptTcpClient to pull a connection from the incoming connection request queue. These two methods will block. If you want to avoid blocking, you can use the Pending method first to determine if connection requests are available in the queue.
Call the Stop method to close the TcpListener.
The Stop method does not close any accepted connections. You are responsible for closing these separately.

 Before jump in to the code, we have to make sure that all the required  C# name spaces are inserted in to the project source files.

normally C# project  source file contains ( by default ) some name spaces. 
they are  : 

  • using System;
  • using System.Collections.Generic;
  • using System.Linq;
  • using System.Text; 

 We have to  add additional 3 name spaces to the file. They are :
  • using System.IO;
  • using System.Net;
  • using System.Net.Sockets;
 ========================================================================

Server Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Net;
using System.Net.Sockets;

namespace server
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient AcceptedClient;
            NetworkStream instream;
            TcpListener clientListner = new TcpListener(IPAddress.Parse("127.0.0.1"), 7000);
            clientListner.Stop();
            clientListner.Start();

            while (true)
            {
                if (clientListner.Pending())
                {
                    // when the client connected to the port, this will 
                    //return that client as the Accepted client
                    AcceptedClient = clientListner.AcceptTcpClient();
                    // get the Accepted client's NetworkStream, 
                    //we want that to read data, which client is sending                    
                    instream = AcceptedClient.GetStream();

                    // read the input data into a byte list.
                    //(lets read byte at a time)
                    BinaryReader reader = new BinaryReader(instream);
                    List inputStr = new List();
                    int a = 0;

                    while (a != -1)
                    {
                        try
                        {
                            a = reader.ReadByte();
                            inputStr.Add((Byte)a);
                        }
                        catch (Exception e)
                        {
                            break;
                        }
                    }

                   // make a full string and write  to  Console
                   string s = Encoding.ASCII.GetString(inputStr.ToArray());
                   Console.Write(s);
                }
            }          
          
        }
    }
}

Client Code

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Net;
using System.Net.Sockets;

namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            NetworkStream outStream;
            StreamWriter writer;

            TcpClient client = new TcpClient();             

            // client is trying to connect to the given ip address and port
            // so this client will be catched by the 
            //TcpLstner of server program
            client.Connect(IPAddress.Parse("127.0.0.1"),7000);

            // get the Network stream, we have to send data
            outStream = client.GetStream();

            // make the writer
            writer = new StreamWriter(outStream);

            Console.Write("Enter your name : ");
            string name = Console.ReadLine();
            writer.Write(name);

            // finally Flush and Close
            writer.Flush();
            writer.Close();
            outStream.Close();
            client.Close();
        }
    }
}