Sunday Apr 13, 2008

India wins Kanpur test in style

Finally after following Indian SA test series every night (PST), I got something to cheer about which will make my time worth it. Kudos to Team India, the stand-in captain MS Dhoni and former Indian captain Sourav Ganguly for bringing cheers among Indian fans all over the world by wrapping up the third test inside three days, the crafty spinners being the architects of the win.

As I mentioned in my previous entry, spin is always going to be India's strength and the South Africans should be grateful to the curators of the first two tests (not taking any credit from their performance in this series though). The way in which wickets fell like ninepins yesterday was a treat to watch and after a long time one could witness classical Indian spin bowling similar to those of mid 90's where India were invincible at home.

Not sure whether Dhoni is a magician or tactician, right from the word go he puzzled both SA batsmen and Indian fans by opening the attack with Harbhajan, keeping run flow in check, bringing Ishant sharma briefly and surprising Mark Boucher, the next over replacing him again with a spinner, etc, etc, one really needs to know how his mind works, but after seeing the results its just a case of intuitive thinking towards the shortest path to victory :)

Sourav Ganguly played an innings of his lifetime and his innings is comparable to Dravid's effort in the final test in Jamaica in the Carribean series in 2006, both resulting in victories, hope the former captain brings more accolades to himself and the team in future. Harbhajan is back to his best on home soil and the way he shouldered responsibility in the absence of Anil is commendable.

In concluding, this is a hard fought series, both teams got a chance to know about their strengths and weaknesses, as mentioned by commentators about pitches in India, have green surface for domestic matches and a turning track for making Team India win!

Thursday Apr 10, 2008

Cricket: The Importance of Spin and Turning tracks for Team India

Today, just like any other sleepless Indian fan after the capitulation in Ahmedabad, I was reading what the curator has for Kanpur test. I was taken aback by this comment in Cricinfo .

"A genuine sporting track, as Ahmedabad was, will definitely not suit India, given the form their pace bowlers are in. Being 1-0 down in the series, they can't afford a Chennai-like sleeping beauty either. As a result they have put all their eggs in the spin basket, perhaps the only basket they had."

It's very hard to understand why the eggs were not in spin basket in Chennai and Ahmedabad and it's not that we can't win on sporting wickets, the Perth test against Australia would have answered that convincingly with India being the First Asian team to win in Australia's favorite backyard, especially after the Sydney test row, what more, the series win in England after 21 years is also a sufficient proof.

But the real question to be answered is: What Kind of Wickets should India produce for any home series?

Have turning tracks before it gets too late, the real test of skill for any visiting team is to win matches in conditions familiar to the home team and that's what will make the series interesting for them and I am sure that quality teams like SA and Australia would be embracing such challenges rather than complaining about turning tracks.

There is nothing wrong in producing favorable tracks if you want to attract crowd who expect the home team to prevail over the opposition, also its the same case for India when they visit SA or Australia or England where a seaming, bouncy or swinging track always greets them and they should be upto the challenge.

Wednesday Apr 02, 2008

Managing Daily tasks

This can be cumbersome at times because we plan to do many things a day but execute only a few (or even nothing gets done the way we expect). The problem was due to the way the tasks were kept track of (using notepads or text editors make things worse as tasks keep on piling and sometimes gets lost after months), therefore in trying to find a software solution I came across this free tool TaskPrompt .

The tool is a customized one where we can prioritize daily tasks and everytime you open the program, all incomplete tasks pop up and will trouble you every five minutes typically like an alarm snooze. If you are honest, you won't delete the task, neither mark it complete, so the best thing one can do is to keep fingers crossed with heads down and focus on the task till it goes out of the away, or else more tasks pop up which may be embarrassing at times, but its a powerful motivation in that one can focus on the to do list just for the sake of getting rid of them.

Though this may not be the complete solution (execution is what matters of course), it may be a step in the right direction if you are serious about executing what you plan to.

Sunday Mar 16, 2008

Shell script: Matching the first occurrence of a string or a pattern in a file and exit

I was looking to solve the above problem, as lazy as ever googled for a solution, but couldn't find what I was looking for (though there were while loop solutions). If you need a single line shell script which matches the first occurrence of a string (or a pattern) from the input and exit, the following code could be useful.

Input file: input.txt

Start
Line: 1
Line: 2
Line: 3
Line: 4
Line: 5
End

To get output 1 (second string in second line Line: 1) from the above file and exit, use the below grep and awk combination, although this may not be the efficient solution.

cat input.txt | grep "Line:" | awk '{ print $2; exit }'

Wednesday Mar 05, 2008

Dhoni: The inspirational captain

Finally India won something in Australia thanks to the young and energetic side led by MS Dhoni, as before every series there were lot of critics questioning the controversial sacking of former Indian captains Rahul Dravid and Sourav Ganguly, but Dhoni's men vindicated everything by lifting the trophy against all odds. The pensive mood of the Australian camp says it all!

There were lots of gains for India from this series which would do a world of good for the team, the greatest finds being the talented youngster Rohit Sharma, rookie (can we call them anymore?) pacers Ishant Sharma and Pravin Kumar, more than anything is the maturing captain in MS Dhoni. What more inspired by youngsters, sachin started to play as if he is still 17 years old, giving India an explosive start only he is capable of. These things coupled with the fact that the Under 19 team lifted the World Cup means Indian Cricket is really in Cloud Nine.

Now it remains to be seen whether the former captains would ever get a recall in the ODI squad as players (BTW there were lot of Under 19 players in queue as well), therefore the best thing for them is to learn the fact that their only stronghold is their test place, which nobody can replace for the time being (atleast as long our test captain is Anil Kumble :)).

Wednesday Sep 19, 2007

OpenOffice Parser: Extracting text from OpenOffice documents

With OpenDocument formats getting widespread acceptance, a lack of simple text extractor from OpenOffice documents is the main motivation for me in developing this one.  The below code will extract text from Open Office documents (like odt, odp, etc). I have used the JDOM XML APIs for easier processing of OpenOffice XMLs. Hope this will make life a bit easier.

/\*
 \* OpenOfficeParser.java
 \*
 \* Created on September 12, 2007, 4:24 PM
 \*
 \* To change this template, choose Tools | Template Manager
 \* and open the template in the editor.
 \*/

/\*\*
 \*
 \* @author prasanna
 \*/

import java.io.InputStream;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

public class OpenOfficeParser {
   
    StringBuffer TextBuffer;
   
    /\*\* Creates a new instance of OpenOfficeParser \*/
   
    public OpenOfficeParser() {}
   
    //Process text elements recursively
    public void processElement(Object o) {
        
        if (o instanceof Element) {
           
            Element e = (Element) o;
            String elementName = e.getQualifiedName();
           
            if (elementName.startsWith("text")) {
               
                if (elementName.equals("text:tab")) // add tab for text:tab
                    TextBuffer.append("\\t");
                else if (elementName.equals("text:s"))  // add space for text:s
                    TextBuffer.append(" ");
                else {
                    List children = e.getContent();
                    Iterator iterator = children.iterator();
                   
                    while (iterator.hasNext()) {
                       
                        Object child = iterator.next();
                        //If Child is a Text Node, then append the text
                        if (child instanceof Text) { 
                            Text t = (Text) child;
                            TextBuffer.append(t.getValue());
                        }
                        else
                        processElement(child); // Recursively process the child element                   
                    }                   
                }
                if (elementName.equals("text:p"))
                    TextBuffer.append("\\n");                   
            }
            else {
                List non_text_list = e.getContent();
                Iterator it = non_text_list.iterator();
                while (it.hasNext()) {
                    Object non_text_child = it.next();
                    processElement(non_text_child);                   
                }
            }               
        }
    }
   
    public String getText(String fileName) throws Exception {
        TextBuffer = new StringBuffer();
       
        //Unzip the openOffice Document
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration entries = zipFile.entries();
        ZipEntry entry;
       
        while(entries.hasMoreElements()) {
            entry = (ZipEntry) entries.nextElement();
                                  
            if (entry.getName().equals("content.xml")) {
               
                TextBuffer = new StringBuffer();               
                SAXBuilder sax = new SAXBuilder();
                Document doc = sax.build(zipFile.getInputStream(entry));
                Element rootElement = doc.getRootElement();
                processElement(rootElement);
                break;
            }
        }                 
        System.out.println("The text extracted from the OpenOffice document = " + TextBuffer.toString());
        return TextBuffer.toString();       
    }     
   
   
    public static void main(String args[]) throws Exception
    {
        new OpenOfficeParser().getText("OpenDocumentFile.odt");
    }
}

Sunday Sep 09, 2007

Division of two numbers without using division operator

I was trying an efficient solution for this problem for sometime and came up with this.

The logic is simple, just left shift (multiply by 2) the divisor till it reaches dividend/2, then continue this routine with the the difference between dividend and divisor and divisor till the point when dividend is less than divisor or the difference is zero. Its similar to the way binary search is used to find an element in a sorted list. Confused! go through the below recursive procedure in python.

#Division of two numbers without using division operator

dividend = int(raw_input("Enter the dividend:"))
divisor  = int(raw_input("Enter the divisor:"))
tempdivisor = divisor
remainder = 0

def division (dividend, divisor):

    global remainder

    quotient = 1
      
    if divisor == dividend:
        remainder = 0
        return 1
    elif dividend < divisor:
        remainder = dividend
        return 0
   
    while divisor <= dividend:
       
        #Here divisor < dividend, therefore left shift (multiply by 2) divisor and quotient
        divisor = divisor << 1
        quotient = quotient << 1        

    #We have reached the point where divisor > dividend, therefore divide divisor and quotient by two
    divisor = divisor >> 1
    quotient = quotient >> 1
   
    #Call division recursively for the difference to get the exact quotient
    quotient = quotient + division(dividend - divisor, tempdivisor)
            
    return quotient

print "%s / %s: quotient = %s" % (dividend, tempdivisor, division(dividend, divisor))
print "%s / %s: remainder = %s" % (dividend, tempdivisor, remainder)

Monday Sep 03, 2007

Test Driven Design

People may have heard about Test Driven Development, but I just reaped the full benefits of introducing test cases during design itself, but in a sligtly different way.

Assume that you are developing a module and have completed some form of pseudo-code for it and it worked fine (like the way it worked for me). Then coding starts and the cycle goes like this.

Develop code according to the design specs -> Write unit tests, test rigorously -> Release the code -> Apply Patches as and when necessary.

But when you start writing test cases during design phase, it simplifies things so much that one never needs to undergo the pain of fixing several hard to determine bugs and modify the code (which makes it worse of course). Last week when I was developing a pseudo code for my module, it worked fine, but after introducing some 15 - 20 test cases this is what I experienced.

Test case              Result                   Action          

Test case 1             PASS                     N/A
Test case 2             FAIL                   Added an if condition in the pseudo code
Test case 2             PASS                     N/A
Test case 3             FAIL                   Failed to handle exception in code, therefore added exception handling
Test case 3             PASS                      N/A
Test case 4             FAIL                   Introduced a new method to handle this functionality
Test case 4             PASS                      N/A   
Test case 5             FAIL                  Added a check to sanitize the input
........
........
........
........
Test case 20          PASS  

All tests Passed finally.

Now after this phase, when I looked back my initial pseudo-code and the way it has changed after all these tests passed, there were lot of differences in my pseudo-code in terms of readability, robustness, security, etc (add other qualities of good code). BTW each time I did a code walkthrough to make sure my tests passed.

How did this approach made the difference? When I did the actual coding, things worked fine the FIRST time the module was executed and I just ensured that all the tests passed during execution without any major changes in code (of course there were minor issues, but those were due to coding errors and not due to design).

Now assume the case when these tests were not there during the design phase. Probably there would have been 15 - 20 patches which may have incurred painful changes to code each time, at the worst would have killed several hours of productive time.

Therefore, sooner the test cases are introduced, the better the life will be for developers and all it requires is some extra hours spent during design, thinking from an end user's perspective.

Monday Aug 27, 2007

Java Regular Expressions: Validating HTTP GET URIs, fetching GET Paramaters and values

I was wondering if there is a way to check the validity of HTTP GET URI using Java regular expressions and if its valid, it should fetch all the GET Parameters and their values. Fortunately after some time hacking around Java REs, I discovered an easy solution to accomplish the same, though I am not sure if its efficient.

class URIMatcher {
public static void main (String args[]) {
   
    String query = "Param1=1&Param2=23&Param3=3335&Param4=hello&Param5=&Param6=world";
   
    Pattern ValidURI = Pattern.compile("(?:([a-zA-Z0-9]+)=([\^=&]\*)&)\*([a-zA-Z0-9]+)=([\^=&]\*)");
    Pattern getValues = Pattern.compile("([a-zA-Z0-9]+)=([\^=&]\*)&\*");
    Matcher ValidURIMatch = ValidURI.matcher(query);
    Matcher getParams = getValues.matcher(query);
   
    if (ValidURIMatch.matches()) {
        while(getParams.find())
            System.out.println("Name = " + getParams.group(1) + " Value = " + getParams.group(2));       
    } else {
        System.out.println("URI is not valid");
    }   
 }
}

The first pattern accepts a valid URI (URIs like Param1=&, Param1=hello&Param2, etc are invalid and are filtered out). From the valid URI, the second pattern fetches all GET Parameters and their values, for the above example it will be

Name = Param1 Value = 1
Name = Param2 Value = 23
Name = Param3 Value = 3335
Name = Param4 Value = hello
Name = Param5 Value =
Name = Param6 Value = world

Regular Expressions are really powerful indeed!

Thursday Jul 19, 2007

Write, write, write.........

I am back after a long gap of nearly a month, but I don't want to give any lame excuses for not blogging like too much work, no time, personal commitments, no interesting topic, etc, but I would rather say that I am a bit lazy these days to put out my thoughts in writing which neatly brings me to a rather interesting but often neglected topic, the art of writing, which will do wonders.

One should write not because of trivial reasons like it will improve their writing skills, enforce clarity etc, but for the reasons mentioned below.

1. Planning the day: What you write is what you should do and what you should do is what you should write. Unfortunately it requires writing daily about your next day plans and thats why most people fail do this as a habit, but the moment it stops, it just slips away and its not too easy to get back to writing ways again. The same holds true for blogging too.

2. Write out your new ideas: People generally speak or gossip till they get tired, but when asked to write, to the surprise they run out of interest too quickly because of the thinking involved (even bloggers) and this is where writing helps. As a blogger its easy to get stuck may be due to lack of ideas or thoughts, opinions, etc, but once you decide to blog, the ideas will flow automatically from your mind, similar to water flow from falls. But everything should start from one point, the desire to write, therefore keep writing, which will stimulate new ideas and thoughts.

3. Enough, do add your own benefits of writing after you experience it. (Remember the number of exams and assignments we wrote till 21 from school to university levels). The good news now is there is no one to force us to write about what we may or may not wished to write at that stage (especially deriving results from equations), therefore we are free to write without any limits or rather sky is the limit.

Therefore everyone SHOULD write and the best way to share your thoughts so that all others enjoy reading your stuff is to BLOG.

Thursday May 31, 2007

Creativity and Technology

I had this doubt on which way to go, to become a technology expert and solve problems or develop problem solving ability at the first place, then focus on technology for implementation models. But people respect great thinkers and those with creative skills irrespective of their technical accomplishments and I realized why they are right.

Even in one of the hoardings displayed by Sun in Bangalore for recruiting great engineers it was mentioned

"Thinkers needed to work with James Gosling"
and not
"Experts needed to work with James Gosling"

Ok, to the next question, How to develop creative thinking skills? Probably this small tip may help.

As the saying goes Great people don't do different things but they do things differently, consider the example of Larry Page and Sergey Brin, at a stage where no one realized how search can influence people and it was considered a boring problem, Larry and Sergey made the difference and the rest is history. Therefore the first step towards creativity is to focus on a problem where we think we can make a difference.

But one can only succeed if they stick to the problem till the end. This is where most people gets lost and this separates the winners from the rest.

But from my experience, to be creative, one need not start tackling mind-boggling problems, but if we show difference in the little things we do, that will definitely propel our creative thinking to a level we would have never imagined! The best thing is Creativity can never be replaced by Technology.

Wednesday May 30, 2007

The problem in Software testing

The easiest part is writing a piece of code, the toughest part as obvious is testing it. Code in a day and it takes the rest of life to test it. There are no limits in testing an enterprise software as it starts with sanity tests, followed by black box testing, white box testing, regression testing, load testing, performance testing, I don't want to write the rest, please visit here .

The question is will any software truly pass these tests as and when applicable or is there a proper process and procedure to carry out these tests. The obvious answer if NO. The reason why all these tests are never carried out is that it will so badly expose the serious flaws in the software and as we dig deep into testing, we can only get hands dirty similar to digging deep in a soil. And as a result no product can ever be released successfully in time (it's a fact).

But what can be done systematically to overcome these so called bugs? The easiest way is to make them as Known issues in case the bug is so complex, therefore fixing it may cause a break in functionality. The second simple way is called Hot fix, in which you simply comment that part of the code. But these things don't solve the issue in first place. They say prevention is better than cure. Therefore one needs to prevent bugs right from day one. With techniques like Test first development coming to the rescue of developers, the question is whether these techniques are followed during development in these days where a product has hard and fast deadline? Again the simple answer is it's often not possible.

Therefore the best solution as far as bugs are concerned is fix bugs for sometime and call it a day. Then take the bugs as and when it comes in the form of escalations and update the software with a clearly documented list of fixed bugs , because after a period of time, bugs has to come to us and it's nearly impossible for the us to go behind identifying it.

Saturday May 05, 2007

When you get stuck in work

I believe many times people ask these questions themselves

What to do when I don't know how to do it?
Who will help me?...., etc

Remember I am talking about technical problems.

1. The first thing one should do is Google search to find the solution. (Yes, there won't be accurate solutions, but for every problem you face, the likelihood of you getting a solution or a tip which will take you in the right direction to solve the problem is nearly 100%).

2. For specific problems, it's better to visit appropriate forums straightaway (for example in case of java related issues visit http://forum.java.sun.com/index.jspa and search there, so that all the responses will be java specific).

Repeat steps 1 and 2 till you get the solution (Don't try on your own at the first place, you will be wasting time when there is a solution available for your problem already).

In a highly unlikely scenario where you don't make any progress from steps 1 and 2, go through the related documentation, if you are still stuck, finally ask help from experts.

The reason why you should not approach others at the first place is when you do that you will become dependent on others at the first place, which inculcates a bad practice in you, also if one can find solutions by his/her own effort, it will last in memory forever and will induce the habit of problem solving in you. Now I realize why experts always advice others to solve problems by themselves. At the best case, if you don't depend on anyone, then you are an expert!

I apply the above steps for any of my technical issues, but the bad habit it creates is a total dependency on search and user forums, occasionally if I don't have connectivity to net, it's a pain to sort out things.

Thursday Apr 26, 2007

Swing: The problem with JFrame.toFront

I was trying to make a JFrame active after it was minimized. The code snippet is as follows

JFrame frame = new JFrame(.....);
....
....
if (frame.isVisible() == true)
{
   frame.toFront();
   frame.setState(Frame.NORMAL);
}

The above code works, but fails to make the frame active and one needs to click the frame window again to make it active. There were other alternatives like

frame.requestFocus() and frame.requestFocusInWwindow(), but they didn't produce the desired results I expected. I am not sure about the sequence of APIs which would accomplish the task.

Interestingly, there were lot of discussions about the behavior of JFrame.toFront() , but the question is can we make a minimized JFrame active.

Cricket: World Cup Failure and Academy Exchange

I was reading the column Majola hits out at South Africa's 'mental strength'. One of the valuable takeaways was the proposal for academy exchange program between India, Pakistan and SA.

"This will enable us to send a squad of spinners to the subcontinent for specialist coaching and for selected batsmen to learn to play spin in those conditions. Pakistan and India will then be able to use their bowlers and batsmen to train in our quicker conditions."

I believe in one way the defeat of India, Pakistan and South Africa is a blessing in disguise, otherwise the thinktank would not have got a chance to dig deep into the problem and come up with creative solutions like this. These ideas when implemented sincerely will definitely help these nations to build a better side not only for the next World cup, but can also improve their abysmal overseas record in non-friendly pitches.

About

prasanna

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today