Saturday, November 03, 2007

Heuristics for Travelling Salesman Problem

I added matlab code for some heuristics of travelling salesman problem (TSP) to snipplr.

The code contains three different heuristics:
1. Nearest neighborhood
2. 2 opt (improvement algorithm)
3. Farthest and arbitrary insertion

I prepared these snippets for a graduate course called as Heuristic Methods in OR that I take in Bogazici University Industrial Engineering department.


Saturday, July 07, 2007

Automatic Backup of All Projects

I wrote a script in groovy that backups all my source code projects automatically. I know this is actually the job of a version control system. But for the time, this script works for me well. The nice thing in this script is that it excludes all the fat files like zip, jar etc. So the generated backup is very small.

Here is the source code of the script:

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharacterCodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
// Aşağıda belirtilen klasördeki tüm klasörleri zipler.
// Ancak arşiv dosyalarını (jar, ear gibi) hariç bırakır.
// klasorundenItıbaren klasörleri zipler

def zipIt = new File("D:/projects/groovy-deney-01")
def klasorundenItibaren = 'aaa'
def String arsivlenmeyecekDosyaUzantilari = /\S*\.(class|jar|ear|war|pdf|rar|7z|log|gz|swf|tld|index|psd|iws|ipr|pdb|dll|cab|obj|ocx|zip|ttf|log|mdb|bak|mat|aux)/
zipIt.listFiles().grep( { > klasorundenItibaren}).each{ folder ->
if(folder.file) return

def buf = new byte[1024]
def out = new ZipOutputStream(new FileOutputStream( + ".zip"))
if(eklenecekDosyaYok(folder, arsivlenmeyecekDosyaUzantilari)) return
folder.eachFileRecurse {
if( it.file && !( ==~ arsivlenmeyecekDosyaUzantilari)) {
println it.canonicalPath
input = new FileInputStream(it.absolutePath)

String s = it.canonicalPath.substring(folder.canonicalPath.size()+1)

out.putNextEntry(new ZipEntry(s))
while((len = > 0) {

def boolean eklenecekDosyaYok(File folder, String arsivlenmeyecekDosyaUzantilari){
println folder.listFiles().findAll{ !( ==~ arsivlenmeyecekDosyaUzantilari)}.empty
println folder.listFiles().findAll{ !( ==~ arsivlenmeyecekDosyaUzantilari)}
return folder.listFiles().findAll{ it.file && !( ==~ arsivlenmeyecekDosyaUzantilari)}.empty


Monday, July 02, 2007

Anket Verilerini Siniflandirma

Groovy ile anket sonuçlarını sınıflandıran bir program yazdım.

package com.shibi.util.text.ölçek

String KLASOR = 'resources/ölçek/Hareket ve Kuvvet 2/'
String[] cevapAnahtarı = new File(KLASOR + '00.txt')
println cevapAnahtarı.size()
StringBuffer out = new StringBuffer()
new File(KLASOR + '01.txt').eachLine { line ->
def cevaplar = line.split(/,/)
def soru = 1
for( cevap in cevaplar ) {
out << olumlulukDeğeri(cevap, soru, cevapAnahtarı) << virgul(soru)
def output = new File(KLASOR + '02.txt')

String olumlulukDeğeri(String cevap, int soru_no, String[] cevapAnahtarı) {
switch(cevap) {
case 'A' : return (cevapAnahtarı[soru_no-1] == '1') ? '1' : '-1'
case 'B' : return (cevapAnahtarı[soru_no-1] == '1') ? '-1' : '1'
case 'C' : return '0'
case 'D' : return 'D'
default : return 'D'

String virgul(int soru_no) {
(soru_no % 30) ? ',' : '\n'

3 tane dosya var: 00.txt, 01.txt ve 02.txt

00.txt dosyası cevap anahtarı. Bu anket tutum ölçmeye yönelik olduğundan, her bir sorunun olumlu mu, olumsuz mu tutum içerdiğini belirtir.

01.txt elimizdeki ham veriler. Bunlar anketlere verilen yanıtlardır.
02.txt verilerin sınıflandırılmış hali. Bu örnekte 3'lü Likert tipi ölçek kullanıldığından, veriler -1, 0 veya +1 olarak sınıflandırılmaktadır.


Thursday, May 24, 2007

Problem: cannot find symbol constructor TestCase()

I was struggling with a strange problem for a few days. Now I found partially the reason of the problem. A very simple test class didn't compile in my project:

import junit.framework.TestCase;

public class MyTest extends TestCase {
public void testMe() {

The IDE (intellij) didn't compile it by saying:

cannot find symbol constructor TestCase()

This was very strange at first. After lots of trials and errors I found out that the reason for this compile error was that there was a conflict between the dependencies. Specifically the conflict was between junit.jar and repast.jar.

When repast.jar has a higher order than junit.jar then the test class doesn't compile. I didn't understand exactly why it occurred but it seems that it has a relation to the classpath declaration in the file of repast.jar, which states:

Class-Path: lib/junit.jar lib/log4j-1.2.8.jar lib/openmap.jar lib/plot.jar

Moreover repast's own junit has a smaller version than 3.8.


Saturday, May 19, 2007

Introduction to AspectJ 5 with Spring and JavaConfig

Using the articles about JavaConfig in Guice vs. Spring JavaConfig: A comparison of DI styles and Simplifying Enterprise Applications with Spring 2.0 and AspectJ I managed to use aspectj configured with spring in java code only, that is without using xml files.

Here is the annotated aspectj class:

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

public class HelloFromAspectJ {
@Pointcut("execution(* main(..))")
public void mainMethod() {}

public void sayHello() {
System.out.println("Hello from AspectJ!");

Here is the ordinary java class which is adviced by the above aspect:

public class HelloService {
public void main() {
System.out.println("Hello World!");

And here is the configuration class, which replaced the spring's configuration xml file:

import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.context.ApplicationContext;

public class SpringConfig {
public HelloService helloService() {
return new HelloService();
public HelloFromAspectJ helloFromAspectJ() {
return new HelloFromAspectJ();
public AnnotationAwareAspectJAutoProxyCreator annotationAwareAspectJAutoProxyCreator() {
return new AnnotationAwareAspectJAutoProxyCreator();

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationApplicationContext(SpringConfig.class);
HelloService helloService = (HelloService) ctx.getBean("helloService");

Note that the bean AnnotationAwareAspectJAutoProxyCreator is the enabler of annotated aspects in spring. It has the same function as the
element in the spring's xml configuration.


Saturday, April 21, 2007

Keyboard for LaTeX

I prepared a new keyboard layout that is partially optimized for LaTeX editing. I made some statistical analysis on sample LaTeX documents. And then put the most frequent keys such that they are easy to type.

The rules laying out the keys are these:
1. The load on both hands should be balanced.
2. Mostly used characters should be arranged according to these rules in the order of priority:
a) Index finger > Middle finger > Ring finger
b) Middle row of the keyboard > Upper row > Lower row
c) Little finger

So I determined the following layout for the symbols that are widely used in LaTeX documents:

` @ < [ = ' _ ] > ! . . .
% $ ( { * + \ } ) ? .
. . / ^ & # " - | ~ .

The above layout is in the order of the keys in a standard keyboard like:

q w e r t y u i o p . . .
a s d f g h j k l ; .
. z x c v b n m , . /

To make the LaTeX keyboard effective, the user presses any key in combination with Space key. Space key is under the thumb finger. So it is the easiest key to press very frequently. To do this I wrote a script in AutoHotkey.
Note that to make the layout easy to remember, I made a convention for parantheses characters "< [ ( {". The opening parantheses are all put in the left side and their counter pairs are put in the same key location in the right side.
You can get the script file from the following links:
English Q-Keyboard
Turkish F-Keyboard
To exit the script, press Ctrl-Esc.


Wednesday, March 28, 2007

Generate RTF in Java

I was googling for an open source library to generate RTF text in java. After navigating through lots of forums, I couldn't find a satisfactory result. Then I searched in Google Blogs and voila :)

Here is the link to the rtf generator in java.

It is a very small jar file of 5 KB size, but it depends on Freemarker.


Parsing JMemorize Documents with Groovy

Groovy makes a lot of things absolutely very easy. One of them is xml parsing.

I use JMemorize for learning new programming libraries like Wicket and Groovy. But I want to import my flash cards into Keynote. So I needed to parse xml documents that JMemorize uses for storing the cards.

It is not a big deal parsing xml documents. But Groovy makes it much easier. I put my code here to show Groovy's easiness and maybe some JMemorize users may benefit.

def lesson = new XmlParser().parse(new File('resources/Java.jml'))
def cards = lesson.Category.Category.grep{it.'@name' == 'Groovy'}.Deck.Card
output = new File('resources/jmemorize.txt')
def counter = 0
for(card in cards) {
output << "Soru $counter:\n\n" << card.'@Backside' << '\n----\nYanıtı:\n' << card.'@Frontside' << '\n====\n'


Monday, March 26, 2007

Ergonomic Keyboard Layout for LaTeX Authoring

Inspired by Lasse Kliemann, I am trying to build a new keyboard layout for LaTeX authoring. Lasse Kliemann has produced a very easy to use keyboard layout for LaTeX symbols.

If you have written some LaTeX code, you certainly know that LaTeX requires lots of symbols like {\}([]$. These characters are hard to type because firstly they reside in far places on the keyboard, secondly they usually require modifier keys in combination. Lasse's solution is to set space-bar as a modifier. The symbols are bound to usual alphabetic characters on the keyboard. So using a key combination like space-s produces {. Both keys "space" and "s" are very easy to type in combination.

I wondered whether Lasse's keyboard layout is the optimum layout for LaTeX authoring. He actually designed the layout for other programming tasks as well like HTML and C authoring. So I wrote a program in Groovy that measures the character statistics in a given tex file. Here is the code:

map = [:]
new File('poisson01.tex').getText('utf-8').each {
if(map[it] == null)
map[it] = 0
map[it] = map[it] + 1
def keys = map.keySet().findAll{ !(('a'..'z').contains(it) || ('A'..'Z').contains(it)) }
def frequencies = map.subMap(keys)
def characterList = frequencies.keySet().toList()
characterList.sort { frequencies[it] }

characterList.reverse().each {
println it + ' ' + frequencies[it]

Here is the output of a run:

\ 893

{ 388
} 387
( 222
) 220
= 207
$ 155
_ 112
[ 110
] 110
. 99
1 90
ı 81
^ 80

So the various parentheses are the mostly used characters. But this is just one latex file. For better design optimization, one should use a randomly selected set of LaTeX files.


Friday, March 16, 2007

Groovy: Automatic Text Replacement Script

I have been doing graduate studies in Industrial Engineering at Bogazici University for a few months. Normally I use a notebook to take my notes. But in the last few weeks I try to take my notes in the laptop. But this has some difficulties. I use abbreviations for the frequently used terms. Then I change them with find/replace in word. This is a manual repetitive task. So it is a very good case for automation. Since I have been learning Groovy these weeks, it was a good opportunity to try my knowledge.

This is the code. It reads two files. One file "sd.txt" contains my lecture notes. The other file "kelimeler.txt" contains the abbreviations together with their replacements.

map = [:]
new File('kelimeler.txt').eachLine {
map[it.tokenize()[0]] = it.tokenize()[1]

output = new File('out.txt')
new File('SD.txt').newReader('ISO-8859-9').eachLine { line ->
output.append(convert(line) + '\n','ISO-8859-9')

def String convert(line) {
matcher = line =~ /\w+/
list = matcher.collect { it }

map.keySet().grep(list).each {
line = line.replaceAll(/\b$it\b/,map[it])
return line

Note that, I am using ISO-8859-9 encoding, which is the standard, non-unicode encoding for turkish characters.


Return Statement Inside The Closures In The Functions

Regarding Groovy Categories:
Return statements inside the functions don't return anything if used in the "use" closures:

class TokenCategory3 {
static String g(String self) {
return 'hello'
String f() {
use(TokenCategory3) {
assert 'a'.g() == 'hello'
return 'a'.g()
use(TokenCategory3) {
assert 'a'.g() == 'hello'
assert f() == null

Note that the last line returns null, although there is a return statement in f().
To make f() return some value, the return statement should be outside the "use" closure:

String h() {
String result
use(TokenCategory3) {
result = 'a'.g()
return result
assert h() == 'hello'