Wednesday, March 13, 2013

The Inner Software Model and the End User


When I build software I always do it aligned with a model. The model evolves with the  software and in many cases defines the boundaries of what can and can't be done (that is without modifying or breaking it). A good model is one which is simple to understand yet powerful enough to allow the introduction of new features.

A good model makes me happy. If it was developed by me then it will be the first thing I will show when presenting my work. If it is others it will be the first things that will make me appreciate their work. Actually I think so high on the importance of a good model that I have made the mistake of asking my users to learn it too.

Users obviously view the world through their eyes. In places you might recognize several use cases as the same one, your users might see them as completely different cases.
It seems I am not the only one taking this approach. Remember the first days of Android OS. One of the first things they were proud of was: "Everything is an application". Indeed as a Software Engineer the fact that every functionality on top of the operating system is modeled as an application is simple yet powerful. But as a user I always moved uncomfortably in my chair when pressing on the applications button and find the Phone application there. You see, as a user I have a phone device with phone related functions and I have the applications which is an extension to the phone. Finding the phone icon and contacts icon in the applications section confused me. Especially in the early days of Android where the phone application shortcuts was permanent. IPhone OS took a different approach where some of the device functionality was presented to the user as OS features (e.g. Siri,).

Another example is the JavaScript language and Object Oriented Paradigm. In this example the user is the JavaScript developer trying to use it as an Object Oriented language. Again you have a powerful simple model (everything is a function) which enables you to implement any Object Oriented principle. However, each concept requires a special usage of the model (Hint: want to define a class? use a function).
On the other hand Java takes a different approach. One example that comes to mind are the Enums introduced in Java 5. Although one can easily implement an Enum (see http://www.javacamp.org/designPattern/enum.html) they still decided to include it in the language.

What is the correct approach? Taking the first approach, in which the model is generic and it is also introduced to the user, is cheaper and easier to develop. Yet it will produce a less friendly software. So I believe the key consideration here is: Who is your user and will he be able to learn and adapt?

Recently I have started to adopt a hybrid approach. I expose both the general powerful model to the advanced user and a simple domain oriented interface for the average user.

To sum things up I highly recommend (especially for developers) to pay attention to the difference in the point of view of users vs. the model. Moreover, to decide on the correct approach consider both the user nature and your resources.

Monday, February 11, 2013

Solr and Lucene Fuzzy Search - A closer look

What is Fuzzy Search?
In a sentence, Fuzzy Search allows one to submit a query against an index, and get results that are close to the desired query, but not necessarily match the query exactly. Lucene (and as such Solr) offers a very effective way (from 4.0) for quickly evaluating such fuzzy queries.
Lucene Fuzzy Search
Lucene (and as such Solr) supports fuzzy searches based on the Levenshtein Distance, or Edit Distance algorithm. To do a fuzzy search use the tilde, "~", symbol at the end of a Single word Term. For example to search for a term similar in spelling to "roam" use the fuzzy search:
roam~
This search will find terms like foam and roams.
Starting with Lucene 1.9 an additional (optional) parameter can specify the required similarity. The value is between 0 and 1, with a value closer to 1 only terms with a higher similarity will be matched. For example:
roam~0.8
The default that is used if the parameter is not given is 0.5.
Under the Hood
The Levenshtein distance between two words is the minimal number of insertions, deletions or substitutions that are needed to transform one word into the other. Than given an unknown query, how does Lucene finds all the terms in the index that are at distance <= than the specified required similarity? Well... this depends on the Solr/Lucene version you are using.

You can take a look at the warning that appears at Lucene 3.2.0 Javadoc: 
Warning: this query is not very scalable with its default prefix length of 0 - in this case, *every* term will be enumerated and cause an edit score calculation.  
Moreover, prior to 4.0 release Lucene implementation to compute this distance was done for each query for EACH term in the index. You really don't want to use this. So my advice to you is to upgrade - the faster the better.

The Lucene 4.0 Fuzzy took a very different approach. The search now works with FuzzyQuery. The underlying implementation has changed in 4.0 drastically, which lead to significant complexity improvements. Current implementation uses the Levenshtein Automata. This automaton is based on the work of Klaus U. Schulz and Stoyan Mihov "Fast string correction with Levenshtein automata". To make a very long story short this paper shows how to recognize the set of all words V in an index where the Levenshtein distance between V and the query does not exceed a distance d, which is exactly what one wants with Fuzzy Search. For a deeper look see here and here.
Conclusion
So from 4.0 and above one can use Fuzzy Search on very large indexes and fill comfortable about it. Of course there are other ways we look for similar values in a query such as:

Tuesday, January 1, 2013

Executing a Command Line Executable From Java

In this post we'll deal with a common need for Java developers. Execute and manage an external process from within Java. Since this task is quite common we set out to find a Java library to help us accomplish it.
The requirements from such a library are:
  1. Execute the process asynchronously. 
  2. Ability to abort the process execution.
  3. Ability to wait for process completion.
  4. On process output notifications.
  5. Ability to kill the process in case it hung.
  6. Get the process exit code.
The native JDK does not help much. Fortunately, we have Apache Commons Exe. Indeed it is much easier but still not as straightforward as we hoped. We wrote a small wrapper on top of it.
Here is the method signature we expose:
public static Future<Long> runProcess(final CommandLine commandline, final ProcessExecutorHandler handler, final long watchdogTimeout) throws IOException;
  1. It returns a Future<Long>. This covers section 1,2,3,6. 
  2. Instance of ProcessExecutorHandler is passed to the function. This instance is actually a listener for any process output. This covers section 4 in our requirement.
  3. Last but not least you supply a timeout. If the process execution takes more than said timeout you assume the process hung and you will end it. In that case the error code returned by the process will be -999. 
That's it! Here is the method implantation. Enjoy.


import org.apache.commons.exec.*;
import org.apache.commons.exec.Executor;
import java.io.IOException;
import java.util.concurrent.*;


public class ProcessExecutor {
    public static final Long  WATCHDOG_EXIST_VALUE = -999L;

    public static Future<Long> runProcess(final CommandLine commandline, final ProcessExecutorHandler handler, final long watchdogTimeout) throws IOException{

        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Long> result =  executor.submit(new ProcessCallable(watchdogTimeout, handler, commandline));
        executor.shutdown();
        return result;


    }

    private static class ProcessCallable implements Callable<Long>{


        private long watchdogTimeout;
        private ProcessExecutorHandler handler;
        private CommandLine commandline;

        private ProcessCallable(long watchdogTimeout, ProcessExecutorHandler handler, CommandLine commandline) {
            this.watchdogTimeout = watchdogTimeout;
            this.handler = handler;
            this.commandline = commandline;
        }

        @Override
        public Long call() throws Exception {
            Executor executor = new DefaultExecutor();
            executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
            ExecuteWatchdog watchDog = new ExecuteWatchdog(watchdogTimeout);
            executor.setWatchdog(watchDog);
            executor.setStreamHandler(new PumpStreamHandler(new MyLogOutputStream(handler, true),new MyLogOutputStream(handler, false)));
            Long exitValue;
            try {
                exitValue =  new Long(executor.execute(commandline));

            } catch (ExecuteException e) {
                exitValue =  new Long(e.getExitValue());
            }
            if(watchDog.killedProcess()){
                exitValue =WATCHDOG_EXIST_VALUE;
            }

            return exitValue;


        }

    }

    private static class MyLogOutputStream extends  LogOutputStream{

        private ProcessExecutorHandler handler;
        private boolean forewordToStandardOutput;

        private MyLogOutputStream(ProcessExecutorHandler handler, boolean forewordToStandardOutput) {
            this.handler = handler;
            this.forewordToStandardOutput = forewordToStandardOutput;
        }

        @Override
        protected void processLine(String line, int level) {
            if (forewordToStandardOutput){
                handler.onStandardOutput(line);
            }
            else{
                handler.onStandardError(line);
            }
        }
    }


}
// interface.
public interface ProcessExecutorHandler {
    public void onStandardOutput(String msg);
    public void onStandardError(String msg);

}

Tuesday, October 23, 2012

Developer's wife - Or how do they stand us?


First of all we would like to begin with 2 apologies. The first one is sent to all women developers out there. The points are valid to your husband as well. The second apology is to all women out there. We are really not sociological experts or pretend to be. This post is written from the experience and view point of 2 male programmers.

So how does your work as a software developer affects your relationship? Developing requires a different set of skills from other professions and makes you adopt some unusual behaviors. This influences your relationship in strange ways.

Working together on the family PC - Or how do I always get into trouble?
Working together on the family PC...Well, you and your wife operate the PC a bit differently. I don't see my wife opening the command line to copy files. Surprisingly, I didn't receive any positive feedback when I brought up my fabulous idea to install a double boot on our family PC so WE can enjoy the new UNIX based media center. Things can get hairy, especially when we need to accomplish a very routine assignment. I remember the nightmare called "Picking up Photos from the Wedding". Filtering best wedding photos (300 out of 2000, WOW that photographer really overdid it), while my wife only used the mouse really killed me there. 

"How was your day honey?" - Or "You never tell me about what you actually do"
Communication. That's the key word in relationship, isn't it? Well, you come back home and your wife ask, "How was your day?"  A laconic answer will get you into trouble. On the other hand, I don't think she will be interested in the new search engine you recently integrated. So what's left to talk about? Office gossip. You really can't have enough of that.

Delving into the PC after work hours - Or why did I start with this media center?
Developers are technical fellows per-se. As such, they read tech blogs, install open source code on their family PC, adopt sophisticated media centers, and try to stretch out the limit of technology when possible. The problems with such assignments is that it takes a long time, you try them at home and not at work, and you are drawn into them with no warnings. You don't know what you are getting yourself into. You read a blog post telling you there is a new streamer for your PS3. You say - I'll give it a try. You find yourself configuring your router while you have guests sitting in your living room with your wife. How many times your wife suddenly woke you up with "Did you hear what I was saying? Can you stop with the computer? I am talking to you and you are stuck to the screen". Developers are capable of sitting 10-12 hours a day in front of a computer. A simple "Let me just check the latest headlines at WIRED", could lead to 3 hours of PC time at home, trying to hack to the neighbor's Wi-Fi with the new Mozilla plug-in, just for the fun of it.

Zombie mode - Or normal people are able to conduct a conversation at 20:00 o'clock
Our job requires tremendous brain effort and almost zero physical effort. After such a long day you go into what we call the "zombie mode". You come back home. You are in the "zombie mode". It is hard for you to...well, to communicate. Yes dear wife. This has nothing to do with us being distance or snobs. We simply processed too much information for one day and we need some time to reset. I am sure at some point in the future this phenomena will be more documented but until then... please be patient. 

Tech Support - Or Why can't you be more supportive?
It's true. Most people we know assume the years we spent at the University, the books we read and the software we developed must have prepared us to help them use Word. The problem is that when your wife is on the other side of the line you have to answer. So you find yourself wondering in the middle of the office trying to teach her to send a fax from your home computer.

Buying Gadgets - Or don't say I am not spoiling you enough...
"You know how much technology can improve our life. So why did you get upset when I go and buy the new laser directed, Bluetooth controlled, vacuum cleaner?" Yes. We love technology and sometimes we buy cool top of the line gadgets that we can live without. But at least you take comfort in the fact that we never spend money on clothes...

Cleaning house - Or why is there a new tool-bar here?
You open up the browser. There are three new shining tool-bars installed. How did they get there? When you install a new software you overcome all those annoying traps to install junk on your PC. However, your wife doesn't. She will tap the next button like crazy, leaving no tool-bar behind. Developers are usually pedant, control freaks when it comes to our machines. Cleaning up after your wife becomes a daily chore.
Small breaks - Or "I am really working here"
Anyone who ever worked from home knows it. You tell your wife you are really working. She takes a look at the screen and finds you in Reddit (again). "I thought you were working", she says. "I am", you answer (but you still get the long face). Developers need those small 30 seconds breaks. We are working, but we need to lift our head over the water to catch a breath.


To sum things up, we would like to dedicate this post to our beloved wives, and wish all you developers out there prosperous relationships.

Wednesday, September 5, 2012

Windows XP and Windows 2003 command-line string limitation

Came across a very weird phenomena that I'd like to share. It took me a while to pin point the problem, so I thought I might shed some light to save others the time. To make a long story short...In our company we use ant scripts in a continuous build process. If the process fails, people get really mad. So, last week I failed the build...a moment before a big delivery...

So, as I said, we use ant to compile our java projects, and have one project that compiles all the other java projects. Before my commit I checked that everything compiled fine on my machine, and then committed the code to our svn which triggers an automatic build process on our continuous build machines. Guess what? It failed. So, what went wrong? How can it compile on one platform and not on the other. I checked the Java revision, and update them to match. Would it then compile? No. I then checked the ant version and matched them (1.8). Would it then compile? No. However, I knew that the builder and my machine run different OS (2003 vs 7). The biggest problem was that the error message was quite ambiguous, and it failed in different locations at each build process. So, first an foremost, run ant -verbose to make life easier. I then got a stack trace which helped me to understand the error better. I then googled the stack-trace, and got a hint here, which referenced me to this support entry on Microsoft. To summarize:
On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters. On computers running Microsoft Windows 2000 or Windows NT 4.0, the maximum length of the string that you can use at the command prompt is 2047 characters. See here.
So what was the problem? We compiled the projects by using:
...
<path id="lib.class.path">
        <fileset dir="${deploy.dir}" includes="*.jar"/>

</path>
...
 <javac...>
            ...

            <classpath refid="lib.class.path"/>
            ...
</javac>
...
This will create a command line that will eventually include all jar files in the deploy directory concatenated as a string explicitly. As a result  we overloaded this command line and passed the string length limitation, which led to compilation errors.

How can this be solved? Simply by removing the fileset property and the using the pathelement property:
...
<path id="lib.class.path">
        <pathelement path="${deploy.dir}/*"/>

</path>
...
 <javac...>
            ...

            <classpath refid="lib.class.path"/>
            ...
</javac>
...
This will create a shorter command line with only the class-path variable and all jar files implicitly will be referenced. That's it - hope it will help



Wednesday, August 1, 2012

Save Time With Eclipse External Tools Configuration

You probably know the feeling. You are sitting next to your colleague in his working station, waiting for your question to be answered. However, he is in charge of the keyboard and you are only an observer. You simply can't comprehend why instead of creating a shortcut in the folder view, he is again navigating all the way from the Desktop to the ProgramData directory, without using auto-complete. 

This example illustrates how we often see people work inefficiently while performing small technical tasks dozens of times a day. This could be a simple thing, such as navigating to a specific location on the computer. However, if you consider the number of times this is performed a day (and the agony on the face of the person sitting next to you waiting for an answer)...well you get the idea. Performing this weary tasks daily can also lead to frustration and discontentment.

Since developers usually perform what can be considered small technical tasks dozens of times a day, this is especially critical. Since most of us use IDE's as our main tool, I would like you to consider the "External Tools Configuration" in Eclipse. This is an unappreciated and not widely used feature which provides a mechanism to run tools that are not part of the IDE. How can this be helpful? For example, let's say that you want to quickly open a file for edit specifically in Notepad++, or jump to the folder of the file you are currently editing, or even open a console directly in a specific directory.

Creating a new external tool 

The External Tools Configuration is located right next to the Run\Debug buttons (In red).

Click on the drop down menu -> External Tools Configuration. You can now create a new tool. Right click on the left Program menu, and click new. This will open the configuration screen for your new tool. Let's go over the 3 examples mentioned above:
  • Open a file for edit specifically in Notepad++
  • Open the folder of the file you are currently editing
  • Open a console directly in a specific directory

So...if you are seeing this mechanism for the first time, I hope this post will save you time. If you already use it - fill free to add here your created tools and shortcuts.