Monday, July 11, 2011

A usefull Postscript Trick

In this blog post I will share a Postscript trick which I use a lot.

Postscript is best known as a page description language. It is a very powerful language, in fact, Postscript is Turing-complete. The language is stack-oriented so you will see a lot of stack operators like dup, exch and roll. These operators can be used to perform all necessary (and possible) stack operations. But it can be very tasking for a programmer to use them correctly.

For example, the following code draws a rectangle perpendicular to the coordinate axis with its lower left vertex at (x,y) and a width of w and height of h. In the comments an impression of the stack is given.

/rectangle {     % stack: h w x y
  moveto         % stack: h w
  dup            % stack: h w w
  3 -1 roll      % stack: w h w
  0 rlineto      % stack: w h
  0 exch rlineto % stack: w
  neg 0 rlineto  % stack:
  closepath      % stack:
  stroke         % stack:
} def
You can easily get lost in all these stack manipulations. Make one mistake and it is likely that your expectations are not met.

Luckily you can solve this problem within postscript. If you look at the above code again, you may notice that a definition is made. The symbol "/rectangle" is associated with the code-block by the def operation. One can associated other values with this operator. You can use it to simplify the above code.

/rectangle {      % stack: h w x y
  /y exch def     % stack: h w x
  /x exch def     % stack: h w
  /w exch def     % stack: h
  /h exch def     % stack: 
  x y moveto      % stack: 
  w 0 rlineto     % stack:
  0 h rlineto     % stack:
  w neg 0 rlineto % stack:
  closepath       % stack:
  stroke          % stack:
} def
There is one problem with this solution. It defines, and possibly overrides, associations for the symbols "/x", "/y", "/w" and "/h". This method leaks its variable in to the context in which it is called. Again, postscript can solve this problem. Initially the associations are made in the dictionary userdict. By using an other dictionary and throwing the dictionary away after it's service, we avoid polluting the userdict. (In the following code examples I will omit the impression of the stack.)
/rectangle {
  4 dict begin
    /y exch def
    /x exch def
    /w exch def
    /h exch def
    x y moveto 
    w 0 rlineto
    0 h rlineto
    w neg 0 rlineto
    closepath
    stroke
  end
} def
Here we first define a dictionary for four keys with 4 dict. Start using it with begin. When we are done we discard it with end. This nicely allows the usage a variable with out polluting the userdict. Because I used this trick so often I polished it up a little. I left out the "body" of this method so you can concentrate an the scaffolding.

/rectangle {
  [/y /x /w /h] dup length 0 add dict begin {exch def} forall
     ...
  end
} def
That one-liner signals the variable names used in this method, creates a dictionary and initialises it with values from the stack. The 0 add is there to easily add local variable. I the body of the method is using a local variable add one the the integer to ensure the size of the dictionary.

This wraps up this Postscript type. I explained how you can use variable in methods without polluting the userdict.

Postscript Brush SyntaxHighlighter

I found myself working with Postscript again and I wanted to share some tips and tricks. Syntax highlighting is a great clue in communications about software. I set out to provide syntax highlighting for Postscript.

I have some experience with Alex Gorbatchev's SyntaxHighlighter. It is a javascript based syntax highlighter with customizable brushes. I created a Smalltalk brush for my Smalltalk Galore blog account. I took that experience and used it to provide a Postscript brush for SyntaxHighlighter. It can be found in the git repository at SyntaxHighlighter-Postscript-Brush.

So you can expect some syntax highlighted Postscript code on this blog soon.

Sunday, July 10, 2011

Postscript Syntax Highlighting

In this blog post I will outline the GtkSourceView language definition for Postscript.

Postscript is best know as a page description language. I found myself using it to produce a set of pictures, but was disappointed that no syntax highlighting was available. Luckily I had prior experience

Just like the the blog post about MAGMA syntax highlighting I used GtkSourceView to create a language definition file for Postscript. The language definition file can be found on github. For instructions about installing the language definition file I refer to the post about MAGMA. (Or you can find instructions in the README file.)

Have fun with Postscript!

Tuesday, June 21, 2011

Graphviz: dot

In this blog post I will discuss the programming language dot.

Dot is a graph description language. I will dive right in and show you an example. The following code:

graph example {
    a [label="root"]
    b [shape="box"]
    c [color="red"]
 
    a -- b -- d
    a -- c -- e
    c -- f [label="indirect"]
}
produces this output:

This clearly shows the capabilities of dot. For more information about dot, and it companion programs visit the Graphviz website.

Thursday, June 16, 2011

MathJax: the gory details

In this blog post I will outline the steps needed to display LaTeX on blogger via MathJax.

In this post I announced the use of a new LaTeX rendering engine that I started to use. A comment asked for more information how I achieved this. Unfortunately it took me a while before I noticed the comment. In this blog post I will provide the steps I performed to start using MathJax in blogger.

Step 1: Hosting
This is by far the hardest step in the configuration of MathJax. MathJax relies on a server which provides all the resources MathJax needs. So you need a host which you can control. I looked around for a hosting service and picked a local hosting service.

Step 2: Installing MathJax
There are various ways of installing MathJax depending on your host. For various reason I opted for a local installation.
Get a copy of the latest MathJax distribution of the download page of MathJax. Place the distribution on the host and follow the installation instructions. Other options are described as well.

Step 3: Add reference to your MathJax in blogger
In order to use MathJax in blogger you have to refer to the MathJax installation. Go to the design section of blogger and edit the html. In the head section of the html add the following section of code.

<html>
  <head>
     ...
     <script src='http://[yourhost/your-installation/]MathJax.js' type='text/javascript'/>
     ...
  </head>
  <body>
    ...
  </body>
</html>

Step 4: Start using LaTeX
Now you can use LaTeX in blogger.
\[
e^{i\pi} + 1 = 0
\]

Above I outlined the steps I performed to start using MathJax in blogger. Since the time that I started using MathJax some things changed. For example, It is now possible to use MathJax directly from their Content Distribution Network (CDN). In effect making steps 1 and 2 unnecessary.

Before you can use the CDN you will have to read the terms of service. After that use the alternate step 3 to reference Mathjax in blogger as outlined below and on the documentation page.

Step 3': Add reference to the CDN Mathjax in blogger
Go to the design section of blogger and edit the html. In the head section of the html add the following section of code.

<html>
  <head>
     ...
     <script src='http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' type='text/javascript'/>
     ...
  </head>
  <body>
    ...
  </body>
</html>

This wraps up the explanation of the use of MathJax in Blogger.

Friday, June 3, 2011

MAGMA Syntax Highlighting

This blog post points out how to add syntax highlighting for MAGMA in gedit.

MAGMA is a very good computer algebra system, but not very well known outside a select mathematical circle. So it is not very surprising that gedit does not know how to syntax highlight MAGMA code out of the box.

Gedit uses GtkSourceView as its syntax highlighting engine. GtkSourceView can be extended by providing a language definition file.

So I set out to create a language definition file for MAGMA. The results can be found at github. In order to use is, you have to place the magma.lang file in the following directory:


~/.local/share/gtksourceview-2.0/language-specs

Below you can find a screenshot of a snippet of MAGMA code highlighted by gedit.

Tuesday, May 10, 2011

Unity: adding items to the dock

In this blog post I will outline a way to add new items to the dock in Unity.

Unity is a new graphic shell for the latest Ubuntu; Nauty Narwal. One of the more prominent features is a docking area.

In this docking area icons for running applications appear. You can decide to keep the icon as a launcher for the application. This feature is nicely integrated with the software center. Whenever new software is installed it will write a desktop file to /usr/share/applications/. This file describes how the menu-item will appear on the dock.

The only downside is that not all software is installed via the software center. One of the reasons is that the software center repositories hold older versions. For example the version of eclipse found in the repository is 3.5.2 (Galileo). At this moment the latest version of eclipse is 3.6 (Helios).
Software which is not installed via the software center does not readily appear on the dock. The reason is the missing desktop file. The rest of the blog post describes how to provide a custom desktop file.

I found the following site helpful. There is a more formal specification of the Desktop Entry Specification. A quick overview is given at anatomy-of-a-desktop-file.

The following steps create a launcher for an application which is not installed via the software center.

  1. Create a desktop file for the application
  2. Place the desktop file in ~/.local/share/applications/
  3. [Optionally] Drag the desktop file onto the dock

Create a desktop file for the application
There are various routes to creating a desktop file. One can create a desktop file from scratch, or copy and modify an existing one. A great place for inspiration are the desktop files in /usr/share/applications.
Below is an example of a desktop file. I created it to launch Eclipse. Paths mentioned are specific for my system and can be changed. The shortcut groups defined at lines 13, 15 and 20 appear when you right-click the icon.

[Desktop Entry]
Name=Eclipse Helios
GenericName=Eclipse
Comment=Start the awesome Eclipse IDE
Exec=/home/dvberkel/bin/eclipse/eclipse
Terminal=false
Type=Application
Icon=/home/dvberkel/bin/eclipse/icon.xpm
Categories=IDE;
StartupNotify=true
OnlyShowIn=GNOME;Unity;

X-Ayatana-Desktop-Shortcuts=Choose;Workspace;

[Choose Shortcut Group]
Name=Choose workspace
Exec=/home/dvberkel/bin/eclipse/eclipse
TargetEnvironment=Unity

[Workspace Shortcut Group]
Name=Workspace
Exec=/home/dvberkel/bin/eclipse/eclipse -data /home/dvberkel/workspace
TargetEnvironment=Unity

Place the desktop file in ~/.local/share/applications/
Unity is looking for custom desktop files in the ~/.local/share.applications directory. It could be that Unity should be restarted before changes are picked up. This can be accomplished by issuing the following command: unity --replace.

[Optionally] Drag the desktop file onto the dock
By dragging the desktop file onto the dock it immediately can be used as a launcher. This option really worked well for me.

This concludes this blog post. In it I explained a means to provide a custom desktop file which gets picked up by Unity.

Monday, May 2, 2011

Learning Language Categories

In this blog post I will advocate to learn new language categories instead of new languages.

Every once in a while you find a post on a forum addressing the question which new language should one learn. Notable examples can be found by googling. Here is a sample:

In my opinion, growing as a developer is not about specific languages. If this was the case then why does nobody suggest C# if one knows Java or vice versa? Seldom is such an advice given. But if it is all about learning languages then this advice should surface as often as any other advice.

I think that language categories are more important then languages. One reason to learn a new language is to broaden your horizon. By seeing new solution to old problems your problem solving toolbox grows. Even if it is not possible to apply the language directly it often is possible to adopt the idea. By going beyond a language category barrier, the novelty and creativity with which problems can be solved grow enormously.

So the next time the question "Which language should I learn next" is asked, go ahead and advice to learn a new language category.

Using proper tags

while reviewing all my old posts in order to use the new Mathjax rendering engine (as mentioned here), I noticed that these posts do not always use proper html tags. I would rather rely on the basic blog layout to work for me.

Frankly it is unreliable. So I went back and redid them using proper tags. The most prominent change was the introduction of the humble <p> tag.

So you can expect a more consistent look and feel for my blog post of way back.

Saturday, April 30, 2011

Having an opinion

In this blog post I will explain why having an opinion is important.

At my first job as a software developer there was a legendary senior developer. Hey called himself a technocrati. He had a vast amount of experience, a no-nonsense way of communicating and openness towards the inexperienced. although he could program circles around me while being blindfolded and with one arm tied behind his back, he always took the time to explain things to me if I had a question.

Although I learned a lot from him, he gave me one pivotal piece of advice: "Have an opinion".

Like all sayings of masters, one should reflect on the meaning.

I am certain that having a opinion, means have a well founded opinion. Having an opinion without a clear reason is void of meaning. It could come around with the sleightest amount of suggestion.

If the advice "Have an opinion" actually means "Have a well founded opinion" the meaning becomes clear to me. Study relentlessly. So I did, and I am still doing that.

An other interpretation of the advice I gleaned from the behavior of "the master" is this. "Have an opinion, and voice it".

It is nice to have a well founded opinion, but it is a waste if you hold it back. By giving your opinion on a certain topic, you are effectively spreading knowledge. For me this was enticing. It was not uncommon to have to following thoughts after a meeting with the master. Why does someone have this "outrageous" opinion? He seems a knowledgeable person, maybe his ideas have merit. Let's just look into them just to be sure.

I would like to conclude this blog post with my narrated version of his advice. Have a well founded opinion, and voice it.

Thursday, April 7, 2011

Launch Configurations in Eclipse

In this post I point out where Eclipse is storing the launch configurations.

After a fresh install of my laptop I wanted to restore the launch configurations of Eclipse. After some searching I finally found the location. I am reporting it here for future reference.

The eclipse launch configurations can be found in your workspace at


.metadata/.plugins/org.eclipse.debug.core/.launches

Sunday, February 6, 2011

Parametrized Junit Tests: Postscript

In two earlier blog posts I commented on parametrized junit tests. This blog post will complement these post with an example of a piece of code.

Because all the important points are made in the other posts I will only present the Junit runner I created. A Maven project demonstrating this technique can be found code at my minimal examples repository

Without further ado: the Junit runner.

package org.junit.runners;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;

public class ParameterizedWithBuilder extends Suite
{
        private class TestClassRunnerForParametersWithBuilder extends BlockJUnit4ClassRunner
        {
                private final int fParameterSetNumber;

                private final List<Object> fParameterList;

                TestClassRunnerForParametersWithBuilder(Class<?> type, List<Object> parametersList, int i)
                        throws InitializationError
                {
                        super(type);
                        fParameterList = parametersList;
                        fParameterSetNumber = i;
                }

                @Override
                public Object createTest() throws Exception
                {
                        return getTestClass().getOnlyConstructor().newInstance(computeParams());
                }

                private Object computeParams() throws Exception
                {
                        try
                        {
                                return fParameterList.get(fParameterSetNumber);
                        }
                        catch (ClassCastException e)
                        {
                                throw new Exception(String.format("%s.%s() must return a Collection of objects.", getTestClass()
                                        .getName(), getParametersMethod(getTestClass()).getName()));
                        }
                }

                @Override
                protected String getName()
                {
                        return String.format("[%s]", fParameterSetNumber);
                }

                @Override
                protected String testName(final FrameworkMethod method)
                {
                        return String.format("%s[%s]", method.getName(), fParameterSetNumber);
                }

                @Override
                protected void validateConstructor(List<Throwable> errors)
                {
                        validateOnlyOneConstructor(errors);
                }

                @Override
                protected Statement classBlock(RunNotifier notifier)
                {
                        return childrenInvoker(notifier);
                }
        }

        private List<Runner> runners = new ArrayList<Runner>();

        public ParameterizedWithBuilder(Class<?> klass) throws Throwable
        {
                super(klass, Collections.<Runner> emptyList());
                List<Object> parametersList = getParametersList(getTestClass());
                for (int i = 0; i < parametersList.size(); i++)
                        runners.add(new TestClassRunnerForParametersWithBuilder(getTestClass().getJavaClass(), parametersList, i));

        }

        @Override
        protected List<Runner> getChildren()
        {
                return runners;
        }

        @SuppressWarnings("unchecked")
        private List<Object> getParametersList(TestClass testClass) throws Throwable
        {
                return (List<Object>) getParametersMethod(testClass).invokeExplosively(null);
        }

        private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception
        {
                List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Parameters.class);
                for (FrameworkMethod each : methods)
                {
                        int modifiers = each.getMethod().getModifiers();
                        if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
                                return each;
                }

                throw new Exception("No public static parameters method on class " + testClass.getName());
        }

}

Tuesday, February 1, 2011

Sexism in Language

In this blog I will point out a an examples of sexism in language.

As I pointed out in an earlier post I adapted my wife's name after we married. Although this is legally possible since the year 1998, not everybody adapted accordingly.

There are a lot of forms in which you have to fill out your name. It is often the case that the name should be the same name as found in your passport i.e. your birth name. But the forms ask to fill in your maiden name. Well the last time I checked, I never was a maiden. Furthermore, I have no intention of ever becoming one. So I regard this as a strange question.

The origins of the use of this language are clear to me. A long time ago only women could take on an other name. So if someone wanted to know your birth name she could reason as follows:

  1. Males can be asked for their name, regardless of their marital status.
  2. Females can be asked for their name, unless they are married. Then they should be asked for their maiden name.

But since the 1998 this rule does not apply any more. And if you want to know my birth name ask for it. It is been twelve years, everybody had enough time change their forms. I regard this as a very sexist use of language.

Sunday, January 30, 2011

Parametrized JUnit Tests Revisited

In the Parametrized JUnit Tests blog post I explained how to create a parametrized junit test. In this blog post I will discuss the reaction of one of my colleagues.

After reading my blog post about parametrized junit tests a colleague expressed his objections with this way of testing. He was a bit disappointed with one thing in particular. The signature of the public static method that is used to construct the test.

@Parameters
public static Collection<Object[]> data()

Is returns a collection of Object arrays. One Object array for each set of parameters. The reason this should be an Object array becomes clear from it's usage.

List<Object[]> data = new ArrayList<Object[]>();
data.add(new Object[] { 2, new Integer[] { 2 } });
return data;

Because the parameters used are of different type, in this case an Integer and an Integer array, they only super-type they have in common is Object.

The objection of my colleague was that is berefts the compiler of the oppertunity to detect type errors at compile time. The compiler would happily compile the following code. But it would blow up at run time.

List<Object[]> data = new ArrayList<Object[]>();
data.add(new Object[] { 2, new Integer[] { 2 } });
data.add(new Object[] { 2, new Double[] { 2.0 } });
return data;

After some discussion with my colleague we came up with the following solution. Instead of using a lot of parameters in the constructor, use only one. By using the builder pattern one retains the type information. Furthermore because now only one parameter is needed, the nearest super-type of all the parameters is the type of the parameter itself.

The code that follows show the same test as in the previous blog post. The change is reflected in the use of the builder pattern. Note that a fluent interface is used to easily construct a builder for the test.
One could still object that the array is now superfluous. They are correct. One way to deal with their objections is to write an custom runner.

@RunWith(Parameterized.class)
public class FactorizationTest
{
    private int number;

    private List<Integer> expectedResult;

    public FactorizationTest(FactorizationTestBuilder builder)
    {
        this.number = builder.getNumber();
        this.expectedResult = builder.getExpectedResult();
    }

    @Test
    public void factorize()
    {
        assertEquals(expectedResult, Factorization.factor(number));
    }

    @Parameters
    public static Collection<FactorizationTestBuilder[]> data()
    {
        List<FactorizationTestBuilder[]> data = new ArrayList<FactorizationTestBuilder[]>();
        data.add(new FactorizationTestBuilder[] { FactorizationTestBuilder.withNumber(2).expect(2) });
        data.add(new FactorizationTestBuilder[] { FactorizationTestBuilder.withNumber(8).expect(2, 2, 2) });
        data.add(new FactorizationTestBuilder[] { FactorizationTestBuilder.withNumber(9).expect(3, 3) });
        data.add(new FactorizationTestBuilder[] { FactorizationTestBuilder.withNumber(72).expect(2, 2, 2, 3, 3) });
        return data;
      }
}

class FactorizationTestBuilder
{
    private int number;

    private List<Integer> expectedResult = new ArrayList<Integer>();

    public static FactorizationTestBuilder withNumber(int number)
    {
        return new FactorizationTestBuilder(number);
    }

    private FactorizationTestBuilder(int number)
    {
        this.number = number;
    }

    public FactorizationTestBuilder expect(Integer... expectedResult)
    {
        this.expectedResult = Arrays.asList(expectedResult);
        return this;
    }

    public int getNumber()
    {
        return number;
    }

    public List<Integer> getExpectedResult()
    {
        return expectedResult;
    }
}

In this blog post I described the objections of a colleague on the previous Parametrized Junit Test blog. I have shown had to meet these objections by using the builder pattern.

Wednesday, January 26, 2011

Updated old post

In this blog post I announced that I switched to using Mathjax. But I hadn't got to the point of rewriting my old post, with this new interface.

Coming this spring I set out to rectify this point and now all posts are using Mathjax as Latex rendering engine.

The only thing I noticed that not every post is using proper html. So probably I have to go back and change that to.

Saturday, January 15, 2011

Parametrized JUnit tests

In this post I will examine parametrized JUnit tests.

With the introduction of Junit 4, a lot has changed for testing Java software with Junit. One of the more esoteric additions are parametrized tests. It allows a developer to run a great deal of test which differ only in a set of parameters. Without further ado I will show you a parametrized test.

@RunWith(Parameterized.class)
public class FactorizationTest
{
    private int number;

    private List expectedResult;

    public FactorizationTest(int number, Integer[] result)
    {
        this.number = number;
        this.expectedResult = Arrays.asList(result);
    }

    @Test
    public void factorize()
    {
        assertEquals(expectedResult, Factorization.factor(number));
    }

    @Parameters
    public static Collection<Object[]> data()  
    {   
        List<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { 2, new Integer[] { 2 } });
        data.add(new Object[] { 8, new Integer[] { 2, 2, 2 } });
        data.add(new Object[] { 9, new Integer[] { 3, 3 } });
        data.add(new Object[] { 72, new Integer[] { 2, 2, 2, 3, 3 } });   
        return data;
    }
} 

Lets focus on line 17 of the method annotated with @Test. This method asserts that the expectedResult is returned by the static method Factorization.factor(int) which is called with parameter number. Both expectedResult and number are private fields of the class FactorizationTest. The fields are assigned in the constructor.

By annotating the class with the @RunWith(Parameterized.class) we are telling Junit to run this class with the Parameterized Runner. By implementing a Runner you can specify how to run the tests.

For the Parameterized this means the following. (The following section is paraphrased. See https://github.com/KentBeck/junit for the details.)

  1. Get an Collection of Object-arrays.
  2. Repeat for every Object-array in the collection:
    1. Construct an instance of FactorizationTest passing as parameters the various elements in the Object-array.
    2. Run all methods annotated with @Test.

The collection mentioned in step 1 is obtained by calling a method annotated with @Parameters. So in this example the following facts will be asserted.

numberfactors
22
82, 2, 2
93, 3
722, 2, 2, 3, 3

In this blog post I made clear how to use parameterized test in the Junit test framework.