Ignoring Java Generics Safety

Java Generics (something like List <String>) provides a very nice way to group similar operation on different types of objects.

There is a way around it though.

In C++ the template invocation actually causes a new instance of the underlying type to be created and compiled. Java only creates the one type instance and then uses the generics as a variable when performing the type checks. Generics allow the compiler to enforce more type safety checks.

More type safety is a brilliant idea and I really like generics, so I have no practical use for this work around to fool the compiler safety checks. Let me know if you find one.

import java.util.ArrayList;
import java.util.Collection;

public class Q1{

	public static void main( String[] args ) {
		ArrayList<Integer> is = new ArrayList<Integer>();
		// list is [  ]
		// list is [ 2 ]
		Collection<?> ac = is;
		ac.add( null );
		// null is the only value that can be added to the ac list.
		// list is [ 2, null ]		
		(( ArrayList<String> ) ac).add("andrejserafim");
		// the above will give you an unchecked cast warning, 
		// but will compile and work
		// list is [ 2, null, "andrejserafim" ]


Initially the list is tagged with ArrayList<Integer>.

The cast to Collection<?> wipes off that tag.

Then ArrayList<String> cast writes a new tag onto the list now stating it’s a list of strings.


IEEETran page margins

This post has nothing to do with getting papers ready for IEEE, it is just using the template they provide for something else, like a University coursework.

IEEEtran_HOWTO says:

Authors should not attempt to manually alter the margins, paper size …

But sometimes one just has to. And then using packages like ‘geometry’ does not help – they confilict with IEEE settings and mess up the entire layout.

I use a4paper option. IEEETran was designed for Letter paper. To make things compatible the desginers made it so the layout will look exactly the same if one used A4 or Letter.

This is great, unless you want only A4 – then the paper has a huge bottom page margin. Which is not birlliant if you have a page limit and is already over it.

Fixing this appeared to be quite easy. Just add:

\documentclass[journal, a4paper]{IEEEtran}

Inspired by this FAQ

Web (PHP, Javascript)

Javascript arguments by value

Let us consider the following situation: one has several widgets, which have to be loaded onto the page dynamically, but each can take a while to load. A solution is to do the loading asynchronously for each component with a nice progress bar displayed to the user.

For example, SIMILE Timeline uses the asynchronous approach to load the data for historical timelines.

After the timelines have been configured, one has to load the data into them using loadXML function.

var eventSource = new Timeline.DefaultEventSource( 0 );
var timeline = Timeline.create(td, bands, Timeline.HORIZONTAL);
timeline.loadXML( eventSourceURL, function( xml, url ) { 
  eventSource.loadXML( xml, url );
} );

The setup seen above works perfectly for a single timeline. But what if we have a loop to create a few timeline widgets?

var dataSources = [ 
  "" ];

for( var ds in dataSources ) {
  var eventSourceURL = dataSources[ ds ];
  var eventSource = new Timeline.DefaultEventSource( 0 );
  // associate eventSource with timeline through _bands_ configuration
  var timeline = Timeline.create(td, bands, Timeline.HORIZONTAL);
  timeline.loadXML( eventSourceURL, function( xml, url ) { 
    eventSource.loadXML( xml, url );
  } );

The result is not anything one could predict, all 3 timelines will have the data from the 3rd data source or no data at all. This happens because the data is loaded at some point after the execution of the code presented has finished. When the anonymous function is created it remembers the reference to the eventSource variable in this loop.

For some reason the context of execution in terms of that one variable is the same for all three timelines.

Fortunately, one can supply a default value to function arguments in Javascript. So we could freeze the reference to eventSource in an array and pass a key as a parameter to the function. Let me show you what I mean:

var dataSources = [ 
  "" ];

// we are going to distinguish each eventSource
var eventSources = [];

for( var ds in dataSources ) {
  var eventSourceURL = dataSources[ ds ];
  // storing all eventSource values for future asynchronous use.
  eventSources[ ds ] = new Timeline.DefaultEventSource( 0 );
  // associate eventSources[ ds ] with timeline through _bands_ configuration
  var timeline = Timeline.create(td, bands, Timeline.HORIZONTAL);
  // notice the three arguments and the defaults.
  timeline.loadXML( eventSourceURL, function( xml, url, ds ) { 
    eventSources[ ds ].loadXML( xml, url );
  }.defaults( ds ) );

Now each anonymous function is associated with its own eventSource. And we get three distinct timelines.

One might notice that the defaults construct is not standard Javascript. It is described in more detail here. And can be added by inserting this code somewhere in the loading section of your page:

Function.prototype.defaults = function()
  var _f = this;
  var _a = Array(_f.length-arguments.length).concat(
  return function()
    return _f.apply(_f, Array.prototype.slice.apply(arguments).concat(
      _a.slice(arguments.length, _a.length)));

Web (PHP, Javascript)

Ontology visualisation: jOWL

jOWL is a JQuery based framework visualising .owl files. It is extremely easy to use. And because it is JQuery-based the syntax is very concise.

This is an example of initialising the Javascript side of things:

    $(document).ready(function() {
      if ($.browser.msie) console = { log : function(msg, rest){$('body').append($('<div/>').text(msg+'  '));}};
      // gdp code
      jOWL.load( "MyFile.owl", function() {
        var tree = $('#onttree').owl_treeview({addChildren: true, isStatic: true });
        var navbar = $('#ontnav').owl_navbar();

      var cc = jOWL.permalink() || jOWL("Entity"); 
      //switch between treeview & navbar

      function toggleView(id){
        switch (id)
        case 'ontnav': $('#ontnav').show(); $('#onttree').hide(); break;
        case 'onttree': $('#ontnav').hide(); $('#onttree').show(); break;     

      }, {} );

All we are doing here loading the MyFile.owl and creating 2 interchangeable views for it: ‘onttree’ and ‘ontnav’. These views will be connected through the listeners. So a change in one is reflected in the other.

Then you need to actually add the HTML elements:

<div id="ontologyPane" class="ontologyPane">
        <form id="viewcontrol" action="">
        <input type="radio" checked="checked" value="onttree" name="visualisation"/>
          Navigation Bar:
        <input type="radio" value="ontnav" name="visualisation"/>
        <div id="onttree" class="ontologyTree">
        <div id="ontnav" class="ontologyNav" style="display:none">

And you have 2 interchangeable panes displaying the structure of your ontology. There is much more to the jOWL framework. But even this simple demonstration gives a taste of its possibilities.

This example is based on the source of


Strategy and Tactics

I often hear the two words in the same sentence, but never actually took the time to find out what the two mean.

From the general usage you could say that tactics is something short term and based on particular cases and actions with them.

On the other hand a strategy faces types of problems and the general guidelines how to deal with them.

I found a very nice definition of the two at:

Military strategy and tactics are essential to the conduct of warfare. Broadly stated, strategy is the planning, coordination, and general direction of military operations to meet overall political and military objectives. Tactics implement strategy by short-term decisions on the movement of troops and employment of weapons on the field of battle.

The great military theorist Carl von Clausewitz put it another way: “Tactics is the art of using troops in battle; strategy is the art of using battles to win the war.” Strategy and tactics, however, have been viewed differently in almost every era of history. The change in the meaning of these terms over time has been basically one of scope as the nature of war and society has changed and as technology has changed. Strategy, for example, literally means “the art of the general” (from the Greek strategos) and originally signified the purely military planning of a campaign. Thus until the 17th and 18th centuries strategy included to varying degrees such problems as fortification, maneuver, and supply. In the 19th and 20th centuries, however, with the rise of mass ideologies, vast conscript armies, global alliances, and rapid technological change, military strategy became difficult to distinguish from national policy or “grand strategy,” that is, the proper planning and utilization of the entire resources of a society–military, technological, economic, and political. The change in the scope and meaning of tactics over time has been largely due to enormous changes in technology. Tactics have always been difficult–and have become increasingly difficult–to distinguish in reality from strategy because the two are so interdependent. (Indeed, in the 20th century, tactics have been termed operational strategy.) Strategy is limited by what tactics are possible; given the size, training, and morale of forces, type and number of weapons available, terrain, weather, and quality and location of enemy forces, the tactics to be used are dependent on strategic considerations.

An application of this to a business environment can be seen at:


KDE Shutdown, Logout, Restart

Inspired by this post.

It is interesting how simple specialised devices cope with their functions much better than a all-in-one PC. Sometimes, I wish to fall asleep with some music on. But how annoying it becomes, when you have to get up in the middle of the night to turn off your PC, which has been playing something all this time. Digital radios have mastered the trick decades ago. Of course there is a way to make a PC do it.

Running linux, I thought that it should be fairly straightforward to shut it down after say half an hour automatically.

Something like shutdown (below) will kill the X. The KDE then will just exit without saving the session. Next time you log on, you will see some session from a distant past. If you do this often, it gets really annoying. Also this requires superuser privileges on some distributions.

/sbin/shutdown -h now "Power button pressed"
# or

Then how to make KDE quit without calling any dialogs (I am sound asleep by this time and I can’t afford to wake up and press ‘OK’)? There is a way.

dcop ksmserver ksmserver logout 0 2 2

The three numbers are explained below (see source):

First parameter: confirm
Obey the user’s confirmation setting: -1
Don’t confirm, shutdown without asking: 0
Always confirm, ask even if the user turned it off: 1
Second parameter: type
Select previous action or the default if it’s the first time: -1
Only log out: 0
Log out and reboot the machine: 1
Log out and halt the machine: 2
Third parameter: mode
Select previous mode or the default if it’s the first time: -1
Schedule a shutdown (halt or reboot) for the time all active sessions have
exited: 0
Shut down, if no sessions are active. Otherwise do nothing: 1
Force shutdown. Kill any possibly active sessions: 2
Pop up a dialog asking the user what to do if sessions are still active: 3


MP3 Tags to Unicode

If you have some old mp3 files, where the tag information is not in english and years ago you have used an encoding your current music player does not understand? The answer is easy – covert to Unicode. First I tried doing it manually, and it works if you have less than 10 tracks. Let’s just say I had more…

I have tried several approaches (all on linux): id3iconv-0.2.1, EasyTag, etc.

It is possible I was missing something, but I could accomplish my task and change the encoding. id3iconv-0.2.1 just removed foreign characters, so that no recovery would have helped (good I had a backup).

And then I found a set of python tools: python-mutagen-1.11.

It was enough to one script (below) and all my tracks had Unicode tags:

mid3iconv -e CP1251 *.mp3

You have to specify the incoming encoding, mine was CP1251 (Windows – Cyrillic).

After trying lots of these tools, I was kind of skeptic about this one as well. If you run it in verbose dry run mode, it will say what it would normally just do. This way you can get full confidence that you specified the initial encoding correctly and that the tool will work at all without changing anything.

mid3iconv -e CP1251 -p -d *.mp3