rulururu

post Java Scanner Class

February 29th, 2008

Filed under: Java — Kai @ 12:56 pm

Today I’d like to introduce to you the Scanner Class which can be used in Java 1.5 and later.

It is a very useful new class that can parse text for primitive types and substrings using regular expressions. Before arguing round and round the subject I’m gonna give you an example:

import java.util.Scanner;
import java.io.*;
 
public class Test {
 
 public static void main(String[] args) {
 
   int n;
   double d;
   String foo;
 
   System.out.print("Enter an integer,  a floating-point number, and a word: ");
   String line = Console.In.ReadLine(); 
 
   Scanner in = new Scanner(line);
 
   n = in.nextInt();
   d = in.nextDouble();
   foo = in.next();    
 
   System.out.println("integer: " + n + ", float: " + d + ", word: " + word); 
 }
 
}

For each of the primitive types there is a corresponding nextXxx() method that returns a value of that type. If the string cannot be interpreted as that type, then an InputMismatchException is thrown.

There are a number of other useful methods in the Scanner class such as skip() to jump over input, useDelimiter() defines a delimiter in place of the default white space, and findInLine() to search for substrings.

You can also give an input direcly to the scanner:

//from the keyboard:
Scanner keyboardScan = new Scanner(System.in);   
 
//from a file:
Scanner fileScan = new Scanner(new FileReader("file.txt");

A common way, from a stream, can be done very short:

int n = new Scanner( getResourceAsStream("file.txt") ).nextInt();

For detecting EOF (End of File) this is important (methods return boolean):

fileScan.hasNext();
fileScan.hasNextLine();

When with floading point numbers you’d note that for example in Germany floading point numbers are written with comma instead of dot.

Scanner scanner = new Scanner( "1,3" );
double d = scanner.nextDouble();

Won’t detect that “1,3″ is a double and return an java.util.InputMismatchException, the reason why is very logical:

The default Locale-Object for the Scanner is what Locale.getDefault() returns - on an English computer it will return Locale.English or something similar. If you like to set it to another language you can simply to that as follows:

Scanner scanner = new Scanner( "1,3" ).useLocale( Locale.GERMAN );

A detailed overview can be found in J2se 1.5 docs: Class Scanner

post Metasyntactic variable foo

February 29th, 2008

Filed under: General Programming — Kai @ 8:18 am

As you know the term foobar or foo and bar separately are very often used in programming examples.

const Object* foo();
void bar(Object *);
 
void blah() {
   bar(foo());         // Error: bar discards const
};

You might have known that spam and eggs are variables most commonly used by Python programmers.

The majority of programmers might be aware of those variables being called metasyntactic variables but I think just a few do exactly know where they come from, what can be attributed to the fact that this question may is not be answered conclusively.

A very historic example of foobar being used in a famous program is its use as a variable name in the fortran code of Colossal Cave Adventure (1977). The variable FOOBAR was used to contain the players progress in saying the magic phrase “Fee Fie Foe Foo”.

Foo

The first appearance of FOO can be found in 1930 in a comic strip called “Smokey Stover” (www.smokey-stover.com). In this connection, the autor makes BAR a word for the military abbreviation “FUBAR”, which stands for “Fucked Up Beyond All Repair” or “All Recognition” - in other words “irreparable”.

Earlier versions of this entry suggested the possibility that hacker usage actually sprang from “FOO, Lampoons and Parody”, the title of a comic book first issued in September 1958, a joint project of Charles and Robert Crumb. Though Robert Crumb (then in his mid-teens) later became one of the most important and influential artists in underground comics, this venture was hardly a success; indeed, the brothers later burned most of the existing copies in disgust. The title FOO was featured in large letters on the front cover.

Other sources confirm that FOO was a semi-legendary subject of British-army in World War II graffiti more-or-less equivalent to the American Kilroy. Where British troops went, the graffiti “FOO was here” or something similar showed up. Several slang dictionaries aver that FOO probably came from Forward Observation Officer.

The question is if foo is used just in any case you just like to or if there are some kinda rules or unified standards when it should be used and when not.

The first usage is simply the one mentioned above in source code. Additionally in filenames, a common convention is that any filename beginning with a metasyntactic-variable name to mark it as a file that is crap and may be deleted at any time.

The etymology of hackish foo is obscure. In RFC (Request for Comments) documents yuo can find comprehensive information about the Etymology of “Foo” (RFC 3092). The document is 99% fun and shouldn’t be taken too seriously. It’s awesome that people put in so much effort for a really unimportant variable that’s not really more than a placeholder in code.

For me the the only sense in foo is to have a variable that doesn’t prescind from the major thing in the example. Besides you don’t have to think every time again of a variable name that is elevant to contribute. Even thought I can’t remeber of having used foo or bar lots of times.

post Worldclock Application

February 27th, 2008

Filed under: .NET — Kai @ 1:12 am

Due the fact that I sometimes chat in IRC channels (like #cpp, #wxWidgets or #xlib) I have to deal with people located almost everywhere in the world. I mentioned that no just my time of day hanging around in IRC are curious also their times are often kinda strange.
For better understanding when they’re available I needed a worldclock.
There are dozens of worldclock implementations on the Internet but most of them were contrary to my expectations.

That’s the reason why I on the spot decited to code my own. I mean the solution I coded is worth looking at ’cause it is without any complexity and has just as little numbers of code as possible.

Of course if I would have done a console application I used needed two or three lines of code.

For example in Perl this would have been very easy:

#!/usr/local/bin/perl
@timeData = localtime(time);

and then pass add/subtract the gmt difference and convert it to date again. Finally you just have to print it.

It was my intention to create at least a tiny graphical user interface for some user friendliness. I decited to do a WinForms GUI, I also could have done it with MFC or WxWidgets but maybe I’ll port it sometimes to WPF.

This is what it looks like:

WorldClock

Let’s have a look behind.

I created a window, a groupBox, two labels and a combobox for the selection of the country.
All timeszones are stored in an xml file:

<?xml version="1.0" standalone="yes" ?>
<Countries>
	<Country NAME="AbuDhabi" GMT="4" />
	<Country NAME="Adelaide" GMT="9.5" />
	<Country NAME="Alaska" GMT="-9" />
        ...
</Countries>

All data is hold in a class named Country:

private double _dGmt;
private String _sName;
private System.Drawing.Bitmap _imgFlag;
 
public Country(String name, double diff)
{
     Name = name;
     Gmt = diff;
}
 
public Country(String name, double diff, System.Drawing.Bitmap flag)
{
     Name = name;
     Gmt = diff;
     _imgFlag = flag;
}
 
public System.Drawing.Bitmap ImgFlag
{
     get { return _imgFlag; }
     set { _imgFlag = value; }
}
//the rest of the get/set properties follows here.

I provide two constructers, one for name and timezone and the second additionally with bitmap ’cause I maybe will someday add a country flag to each timezone.

After loading the form a typed list for Country objects is created.
I could have counted the lines of the xml and in depency to that created a typed array with a fix size but for about 50 elements it doesn’t really matter.

List<Country> lcountries = new List<Country>();

Now the xml file gets read into Country class:

private void ReadFromXml(List<Country> countries)
{        
    String name = String.Empty;
    double gmt = 0;
    String tmpGmt = String.Empty;
 
    String filename = @".\countries.xml";
    if (!File.Exists(filename))
      MessageBox.Show(filename + " can't be accessed.", 
                                "Error", 
                                MessageBoxButtons.OK, 
                                MessageBoxIcon.Error);
    else
    {
       XmlDocument doc = new XmlDocument();
       doc.Load();
       XmlElement root = doc.DocumentElement;
       foreach (XmlNode @daten in root.ChildNodes)
       {
           name = @daten.Attributes["NAME"].InnerText;
 
           tmpGmt = @daten.Attributes["GMT"].InnerText;
           tmpGmt = tmpGmt.Replace('.',',');
           Double.TryParse(tmpGmt, out gmt);
 
           countries.Add(new Country(name, gmt));
       } 
    }
}

The most important thing, that saves a lot of lines, is the binding between combobox and List.

this.cbCountries.DataSource = lcountries;
this.cbCountries.DisplayMember = "Name";
this.cbCountries.DataBindings.Add("Text", lcountries, "Name");

The only think we have to do know is when the selected item of cbCountries is changed:

private void cbCountries_SelectedIndexChanged(object sender, EventArgs e)
{
    Country selCountry = (Country)this.cbCountries.SelectedItem;
    _dDiff = selCountry.Gmt;
}

Every second a timer (interval 1000ms) refreshes the label that shows the current date and time.

private void timer1_Tick(object sender, EventArgs e)
{
    this.lblDate.Text = GetDate().ToShortDateString();
    this.lblTime.Text = GetDate().ToLongTimeString();
}
 
private DateTime GetDate()
{
     DateTime t = DateTime.Now.ToUniversalTime();
     t = t.AddHours(_dDiff);
     return t;
}

Totally simple, written within 15 minutes and easy to comprend everybody else.
If you can also benefit from a worldclock application you can download it here.

It also works will with Linux using mono (>= 1.0). The only thing I had to take into account was the relative path of the xml file. There might be clearer solutions but to me this is the shortest way to archive my aim.

String filename = @".\countries.xml";
 
System.OperatingSystem osInfo = System.Environment.OSVersion;
 
if (!osInfo.Platform.ToString().Contains("Win"))
     filename = @"./countries.xml";

For further information you can have a look at Nameing a File (Windows) on msdn.

post Some rumors about the future of VBA

February 27th, 2008

Filed under: Windows — Kai @ 12:02 am

Some time ago Microsoft announced that VBA is not, in fact, dead yet.
They assured not having plans to remove VBA from future versions of Office for Windows. To this time the next version was 11 better known as Office 2003.
Microsoft also tried to clarify that they think that VBA is a critical capability for large numbers of our customers; accordingly, there is no plan to remove VBA from future versions of Access/Excel.

This announcement isn’t really up to date. In the next release of Office (Office 2007) they didn’t commit to either drop it or continue it.
Although Microsoft Office 2008 for Mac does not include Visual Basic for Applications support, Microsoft has no plans to remove it from future PC versions.

VBA was a great solution for MS Access “applications” and reports. MS Access is great for whipping up simple reporting apps but it’s too hard to maintain for larger apps.

Tons of applications are built on MS Access. What will happen to Access and VBA?

Some people assume that some changes might happen to it, such as rebranding JET and/or increasing the 2GB limitation of the MDB filesize.
Others long ago already have dated the death of both caused by the leadership role of .NET languages and the way how they are getting boosted by Microsoft.

At begin of development of Windows Vista there were plans to use MS SQL Server for the filesystem. This would have made Access become redundant.
Status quo is that Office 2007 still has Access and VBA on board and MS SQL Server is not used for a filesystem.

Classic VB developers are spooked because Microsoft is ending support for VB 6.0. This is a gradual process, some level of support is promised until March 2008 and possibly longer if you unravel the threads of how VB relates to VBA, and the fact that the runtime ships with Windows XP which will be supported for seven years after Windows Vista is released.

All those information arouses my suspicion that sooner or later Access will be obsolete and VBA will get replaced by a .NET language.

Even thougth I personally didn’t ever like VBA, much less because programming skills in VB(A) are not that good, I think that VBA and also Access have played a big role in development history, not only because almost everybody who learned programming some years ago gained experience with it.
Also most Windows boxes already have the VB runtime, whereas deploying the huge .NET runtime can be a major hassle. If this is really important nowadays remains to be seen.

On VBA’s MSDN helppage I found following:

As of July 1, 2007, Microsoft will no longer offer VBA distribution licenses to new customers. Existing VBA customers can still purchase additional VBA licenses from Summit Software and Microsoft for existing solutions.

One of the frustrations of this decision is that moving to .NET is not all gain.

post String vs. StringBuilder / StringBuffer

February 26th, 2008

Filed under: .NET, Java — Kai @ 6:22 pm

Some time ago I learned when to use StringBuilder instead of String. Now I want to know the differences and advantages exactly.

As a C++ developer when working with .NET I soon notices the difference about the data types in .NET, especially the standard string object.
A standard .NET string object is immutable.

According to that this is pretty inefficient:

String s;
for (.;.;.) s += "something";

For each +=, the String’s content needs to be copied into a new instance that has a bit more space at the end for “something”.

A better solution is StringBuilder which is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations.

Also in Java String objects are constant strings. Once they are initialized and populated, the value and memory allocation is set. If the value changes in any way, a new object is created for the new value.

But there’s a difference in Java:
StringBuilder was added in Java 5. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.

StringBuffer should be used for multi-threaded applications.
But you have to be careful the StringBuffer class is only available in Java not in .NET languages, here it’s just StringBuilder for single- and multi-threaded applications.

The usage of a .NET StringBuilder is as simple as expected:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
for(int i=0; i<1000; i++)
{
    sb.Append("something");
    sb.Append(12);
    sb.Append(DateTime.Today);
    sb.AppendFormat("{0}: {1} ", i, "times passed the loop");
}
 
String out = sb.ToString();

Append() is overriden for lots of types.

Using Java it’s about the same:

String sum = new StringBuffer().append(40.00).append(" Dollar").toString();

Every time you add two strings using + operator, a new string allocation is reserverd in memory and used for this new string. So let’s say, you are adding strings 100 times using + operator, there will be 100 new memory allocations. In case of StringBuilder, there will only be one memory allocation.

StringBuilder provies a lenght() and a capaitiy() method:

When creating a new StringBuilder

StringBuilder sb = new StringBuilder();

the length is is 0 but the capacity is 16.

When creating a StringBuilder with a String in constructor

StringBuilder sb = new StringBuilder("something");

now length is the length of “something” (8) and the capacity is 16 + 8

If you expect that your buffer will need a capatity of 1000 you can initalize the StringBuilder with a buffersize:

StringBuffer sb = new StringBuffer(1000);
      System.out.println(sb.length());         // prints 0
      System.out.println(sb.capacity());       // prints: 1000

The length() always returns the number of chars in the builder, the number returned by capacity() is the same or bigger than length and tells you how many chars are left in the buffer. If no buffer is left the Builder has to reallocated new memory space, which takes time.
The StringBuffer should be initalized with the expected buffersize to avoid time-consuming reallocation.

You’d always be aware of the fact that the first time creating a StringBuilder costs time - if you just add three String together it will definetely be slower to use a Builder than concatenating them the common way.

Finally I got a visualized comparison of both:

compare SB and String

The numbers at the x-axis represent the quantity of iterates.

The blue line is the performance of the pure String approach. The red line is StringBuilder at its basic settings.
The green line represents a StringBuilder initialized to the size of the final string.

StringBuilder performance can sometimes be a bit tricky because there’s kinda “break-even-point” you always keep in mind.

A simple rule of tumb is:
If you have to concatenate a string more than 10 times, it’s better to use StringBuilder.

post Rock yourself to sleep

February 25th, 2008

Filed under: Linux, Music — Kai @ 7:00 am

When going to bed I usually listen to some good melotic rock rhythms until falling asleep. Most times my computer is supposed to play music for half an hour and then switch off.
I simply shutdown after thirty minutes:

shutdown -h 30

But what can you do if you just wanna stop the music after half an hour but the pc should keep on working all night. That’s what I asked myself yesterday night. I sorted out the problem by using DCOP which stands for Desktop COmmunication Protocol.

Essentially, DCOP is a “remote control” system, which allows an application or a script to be controlled from outside. I use this software for years for my remote control with LIRC (Linux Infrared Remote Control) to gives impulses to Amarok player.

The model is simple. Each application using DCOP is a client. They communicate to each other through a DCOP server, which functions like a traffic director, dispatching messages/calls to the proper destinations. All clients are peers of each other.

For example you can tell xmms to pause playing music:

dcop xmms player pause

To wait for thirty minutes and then stop Amarok is as simple as the previous example:

sleep 30m; dcop amarok player stop

If you have further interest in DCOP here’s a simple guide howto implement a DCOP interface yourself:
Creating a DCOP Interface

It’s interesting to know that in modern KDE systems, every KDE application supports a basic set of DCOP interfaces, even if the programmer of the application did not explicitly code in such support.

KDE API Reference:
The DCOP Desktop COmmunication Protocol library

ruldrurd
Next Page »
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)