Friday, May 11, 2012

5 minute intro to parsing command line arguments with jopts simple


Maven:


net.sf.jopt-simple jopt-simple 2.4-rc2          

First you create an OptionParser object 

For example:

OptionParser parser = new OptionParser() {
{
accepts("file").withRequiredArg().ofType(File.class)
.describedAs("nput file");
accepts("date")
.withRequiredArg()
.ofType(Date.class)
.withValuesConvertedBy(
DateConverter
.datePattern("yyyy-MM-dd HH:mm:ss"))
};
    
As you can see, the option argument can be any object that has a string constructor. 

You can print a handy usage via the method

parser.printHelpOn(System.out);

(annoyingly, it throws an IOException). 

Once initialized, you can invoke your OptionsParser on a list of arguments thus:
OptionSet options = parser.parse(args);
Beware, this throws a  runtime exception if unrecognized arguments are passed - you should wrap it in a try catch block.

You can then check if your options are present by invoking

options.has("file")
if this returns true, go ahead and get the argument:
(File) options.valueOf("file")); 
As you specified the argument as a file, it will be retrieved as a file object, the only caveat being that you need to cast it to the right type.

Very useful overall. One thing to note is that the project requires absolutely no dependencies whatsoever (except for those scoped as test). So unlike the bloaty apache type of "utilities" which pull in 5 dozen other dependencies with them, this library is super lightweight.

Link to project page here



Wednesday, April 18, 2012

Of chickens and pigs

Can I just say how much agile sucks? Our starting point was a team of developers (all developers, mind you, not a single non-coder in sight - even our QA could code) who would meet for 2 minutes in the morning by rolling their chairs over in a common direction and know what they had to do for the rest of the day. The more we worked together, the better we got at it. Apparently this is known as "cowboy coding" and is frowned upon.

Somebody thought we weren't high performing enough so they combined us with another team and now we are doing agile. That means we spend 20% of our time in meetings where we are speculating about the complexity of issues that we aren't allowed to work on yet. The rest of the time we are explaining what we are doing with every hour of our day while scrambling to compensate for our earlier erroneous estimates.

We don't have time to think, let alone think out of the box. There is always the looming deadline of the next morning when you will have to explain how far along you are on a task and cross out some hours on a post it note.

See, to the me the biggest issue is that the gods of agile believe that estimation is a skill that most developers suck at because they haven't practiced enough. They don't realize that estimation is always a crapshoot because you can't know in advance how long a task is going to take and certainly not to the hour the way that we are expected to. Programming is an art, it's not data entry.

Thursday, September 9, 2010

Evaluating expressions with JEXL

JEXL is a useful library for implementing scripting features in Java programs - specifically it is useful if you require scripts to be evaluated like boolean expressions.

The first thing is to set up a JEXL engine,

import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;

.....

JexlEngine jexl = new JexlEngine();

Then you initialize an jexl context

JexlContext context = new MapContext();

After that you add variables to your jexl context which can be used within your expressions.

e.g.

Integer x = new Integer(11);
context.set("x", x);

Now your jexl expressions can refer to x - e.g.
String expr = "x > 12"
Expression e = jexl.createExpression( expr );

Finally you can evaluate your expression, casting the result to the approproriate type:

Boolean result = (Boolean)e.evaluate(context);

You can see how this would be useful for any sort of user inputted expressions, etc.

Wednesday, July 14, 2010

Setting up Glassfish on Ubuntu Linux

from this site:

java -version // Check java version. It must be either Java 1.5 or Java 1.6. If not install Java by typing sudo apt-get install sun-java6-jdk. It asks your password, after you enter it, it will install Java 6.
wget http://java.net/download/javaee5/v2ur2/promoted/Linux/glassfish-installer-v2ur2-b04-linux.jar // get the link of latest glassfish server jar for linux from https://glassfish.dev.java.net/public/downloadsindex.html
java -Xmx256m -jar glassfish-installer-v2ur2-b04-linux.jar // Click Accept in the license window that opens
cd glassfish
sudo chmod -R +x lib/ant/bin // Enter password
lib/ant/bin/ant -f setup.xml //Run ant script
cd bin //Go to the directory (usually bin) where asadmin command is available. You can find this by simple ls command or through GUI file xplorer
./asadmin //Run asadmin
asadmin> start-database
asadmin> start-domain domain1
Type http://localhost:4848/ in browser and login as username: admin and password: adminadmin
asadmin> exit // To shutdown the server, type this in the terminal window

Thursday, June 19, 2008

Yesterday I learned four things.

1. How to use a void pointer in c (void * my_ptr). How to access its value (it can't be directly dereferenced so you have to cast it to another pointer like and dereference that: *(int *) my_ptr

2. How to write functions that take a variable number of arguments. You declare the function by first listing the fixed parameters, then an ellipsis at the end to indicate zero or more additional arguments are to be passed to the function. Since C does not provide a way to access the number of variable arguments passed directly, you must generally have a way of knowing this, either directly (by having one of your fixed arguments be the number of arguments) or indirectly (such as in printf,)

To access the variable arguments in your function definition, you must use the macros defined in the header file stdarg.h. The first thing is to declare a pointer variable of type va_list generally called arg_ptr. Then you call va_start() passing it arg_ptr and the name of the last fixed argument. To retrieve each variable argument, call va_arg() passing it the pointer arg_ptr and the data type of the next argument. The return value of va_arg is the value of the next argument. Then call va_end(arg_ptr).

The next thing I learned was how to write a simple makefile. In its very simplest form a makefile is just one rule of the form:

target: prereq1, prereq2
       :command


So a very simple example:

hello: hello.c
       :gcc hello.c -o hello


It gets more complicated because of the concept of dependencies. The make utility looks at the last modified date of the various files and recompiles a target if its last modified date is earlier than that of any of its prerequisites.

Finally, I learned a bit about posix threads. I learned about an interesting race condition that can occur if condition variables are not used carefully. Condition variables are used to wait and signal but if a thread is not waiting on a condition variable before another thread signals, that signal will be lost and a race condition occurs if the thread that is supposed to wait for the signal is delayed in its execution. In such a case, if the first thread signals and then waits for action to be taken by the waiting thread and the waiting thread begins its waiting state slightly too late, a deadlock is likely to occur. One really common and clever solution to this problem is to create a global variable that the signalling thread increments before it signals. So when the waiting thread begins execution, before putting itself in the waiting state, it first checks the value of the global variable. Finally, a mutex is required so that the signalling thread locks the mutex, increases the global variable, then signals, then releases the mutex. Similarly, the waiting thread locks the mutex, checks the global variable, calls wait and unlocks the mutex. wait takes the mutex as one of its arguments so that it can unlock the mutex before putting the thread on the wait queue.

Saturday, June 7, 2008

linux system administration

Some basic commands:

pstree -- shows the processes running in the form of a tree
/usr/bin/time -v yourprocess -- Show system page size, page faults, etc of a process during execution. Note you must fully qualify the command as "/usr/bin/time" to avoid using the bash shell command "time".
df -k shows disk usage statistics in kilobytes

Friday, June 6, 2008

I wrote simple strcmp in c


int strcmp (const char *str1, const char *str2) {
while ((*str1 != 0) && (*str2 != 0)) {
if (*str1 != *str2) return (*str1 - *str2);
else {
str1++;
str2++;
}
}
return *str1 - *str2;
}