Tuesday, January 06, 2009

Navigation features of IntelliJ Python Plugin

I think one of best uses of IntelliJ for the developer is its easy navigation features. Here are some of screenshots about the navigation features of the Python plugin of IntelliJ:

Find usages (Alt-F7) of any python object, class etc.




















Structure of a python file and classes inside it:


Go to definition (Ctrl-B) of a python class, function etc.







Find a class (Ctrl-N):

Read More...

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.

Read More...

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.util.zip.*
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( {it.name > klasorundenItibaren}).each{ folder ->
if(folder.file) return
println(folder.name)

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

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

out.putNextEntry(new ZipEntry(s))
while((len = input.read(buf)) > 0) {
out.write(buf,0,len)
}
out.closeEntry();
input.close()
}
}
out.close()
}

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

Read More...

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

int ANAHTAR_SATIR_NO = 1
String KLASOR = 'resources/ölçek/Hareket ve Kuvvet 2/'
String[] cevapAnahtarı = new File(KLASOR + '00.txt')
.readLines()[ANAHTAR_SATIR_NO]
.split(/,/)
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)
soru++
}
}
def output = new File(KLASOR + '02.txt')
output.write(out.toString())


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.

Read More...

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() {
assertTrue(true);
}
}


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 manifest.mf 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.

Read More...

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;

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

@AfterReturning("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.config.java.annotation.Configuration;
import org.springframework.config.java.annotation.Bean;
import org.springframework.config.java.context.AnnotationApplicationContext;
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.context.ApplicationContext;

@Configuration
public class SpringConfig {
@Bean
public HelloService helloService() {
return new HelloService();
}
@Bean
public HelloFromAspectJ helloFromAspectJ() {
return new HelloFromAspectJ();
}
@Bean
public AnnotationAwareAspectJAutoProxyCreator annotationAwareAspectJAutoProxyCreator() {
return new AnnotationAwareAspectJAutoProxyCreator();
}

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

Note that the bean AnnotationAwareAspectJAutoProxyCreator is the enabler of annotated aspects in spring. It has the same function as the
<aop:aspectj-autoproxy/>
element in the spring's xml configuration.

Read More...

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.

Read More...

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.

http://it.newinstance.it/2007/03/23/msword-generation-made-easyer/

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

Read More...

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')
output.write('')
def counter = 0
for(card in cards) {
output << "Soru $counter:\n\n" << card.'@Backside' << '\n----\nYanıtı:\n' << card.'@Frontside' << '\n====\n'
counter++
}

Read More...

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
else
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

489
446
{ 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.

Read More...