Clojure Game Of Life App on Heroku

A while ago I created a heroku account to try it out. They allow you to host clojure web apps in the cloud. One worker is for free and there are also quite more languages supported.

In order to practice some clojure I implemented game of life and packaged it into a lib. Here does leiningen help you a lot, it is the maven of the clojure world and also creates maven compatible jar files.

My app was originally printing out the game of life world to the CLI but now outputs it as text/plain.

I won’t repeat the steps to setup heroku since they are explained very well on heroku: http://devcenter.heroku.com/articles/clojure

The result can be accessed here: http://gentle-journey-9851.herokuapp.com/

The state is globally shared through all requests. So don’t be surprised if there are some generations missing.

The code and library is available on github. The game of life source code is included in the jar, in case some is interested. I might have a different post about this later.

https://github.com/dedeibel/herokus_game_of_clojure_life

To start the app:

Prerequisites: leiningen

To run locally, simple run

$ lein run -m herokutest.web 5000

or

$ foreman start

And visit http://localhost:5000

(ns herokutest.web
  (:use [game_of_life.cell :only (new_cell)])
  (:use [game_of_life.world_printer :only (to_string)])
  (:use [game_of_life.world_builder :only (from_string)])
  (:use [game_of_life.game :only (next_generation)])
  (:use ring.adapter.jetty)
)

(def twentyfour_and_more
"xx
,xx
,
,
,
,                                   x x  xxx
,                                   x x    x
,                                   xxx  xxx
,                                     x  x
,                                     x  xxx
,                                                                                                   xx  
,                                                                                                  x  x
,                                                                                                 x    x
,                                                                                                x      x
,                                                                                                x      x
,                                                                                                 x    x
,                                                                                                  x  x
,                                                                                                   xx"
)

(def counter (atom 0))
(def world (atom (from_string twentyfour_and_more new_cell)))

(defn app [req]
  (let [current @world]
    (swap! counter inc)
    (swap! world next_generation)
    {:status 200
     :headers {"Content-Type" "text/plain"}
     :body 
       (str "Game Of Life (Step " @counter "):\n" (to_string current))
    }
  )
)

(defn -main [port]
  (run-jetty app {:port (Integer. port)}))

Short review: Zoe’s Tale from John Scalzi (Old Man’s War)

This a short review I wrote about Zoe’s Tale, the fourth book in the Old Man’s War universe. A great, easy to read and modern series for sci-fi fans.

When I started reading I was just happy there was something more about the Old Man’s War universe and it would be interesting to hear the same story from a different perspective.

But it was more than just another perspective it extends it by tells a new story at the same time – not boring you with a lot of things you already heard. But you kind of see where the Scalzi tries to catch up with history.

At the beginning, the book does not read so fluently I must admit. Seeing the world from the eyes of a sixteen year old girl can be annoying – even if authentic. I kind of got the feeling even Scalzi had to get into writing from this point of view, assuming he even started with the beginning of the book. ;-)

After a while all of this vanishes and you build up a lot of sympathy with Zoe and resolving in a pleasing ending. I am usually disappointed by book’s endings – being unspectacular – in this book there are no world ending battles to expect and the end is known anyway but there was kind of a showdown for me.

This book is a valuable part of Old Man’s War with place for topics that might have come a bit short in the other books. Thank you John Scalzi.

Android phone as webcam to capture binary clock patterns

A while ago I got a binary clock for my birthday by some college friends (thank you again at this point). When you watch it from the sofa, you can sometimes see it creating some interesting or funny shapes and I wondered how many of them are there.

Sure, you could write a program to generate all combinations but I wanted to make a photo for each of the clock’s states. Since I don’t have a webcam or something more advanced – the idea was to use my android phone.

Searching for an app, I found this really great and easy one IP Webcam which allows you to take shots via HTTP or and directly grab an image from the video buffer. Luckily this was fast enough to make a picture every second. This was not the case when I tried using the auto focus and normal photo mode.

I wrote a little C program to print out seconds and microseconds to analyze the camera’s delay by taking a shot of the screen. The result surprised me a little since the picture was actually from before it was triggered and not after.
The explanation is at hand, the picture from the camera is buffered on the phone or the app and you simple get a snapshot of what is ready at that time.

I’ll just dump the source code of the program to take a shot every second here and with some interesting pictures I found after recording about ten hours. one to ten o’clock.

/* makeshots.c */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

#define MSSLEEP "./mssleep"
#define CAMERA_LATENCY "350000"
#define CAMERA_URL "\"http://192.168.1.112:8080/shot.jpg\""
// printf
#define TIMEFORMAT "%010ld,%06ld"
// strftime
#define OUTTIMEFORMAT "%H_%M_%S"

#define MINUTE 60l
#define HOUR (60l * MINUTE)
// 86_400 pictures per 24 hours
#define RUNTIME (10l * HOUR + MINUTE)
#define LOOPWAIT_MS 2000

void shoot() {
  char shoot_cmd[256];
  char timestamp[128];
  struct tm tmine;
  time_t rawtime;

  time (&rawtime);
  localtime_r(&rawtime, &tmine);

  strftime(timestamp, 128, OUTTIMEFORMAT, &tmine);
  snprintf(
    shoot_cmd,
    256,
    "("MSSLEEP" "CAMERA_LATENCY"; curl -s -S "CAMERA_URL" -o out/%s.jpg 2>> curl.log) &",
    timestamp
  );
  system(shoot_cmd); // returns immediately
}

int main(int argc, char **argv) {
  struct timeval t;
  struct timezone tz;

  // init
  if (gettimeofday(&t, &tz)) {
    perror("gettimeofday in init failed");
  }
  time_t start_sec = t.tv_sec;
  time_t lastsec   = t.tv_sec;

  while (t.tv_sec - start_sec < RUNTIME) {
    if (gettimeofday(&t, &tz)) {
      perror("gettimeofday in loop failed");
    }
    printf(TIMEFORMAT, (long) t.tv_sec, (long) t.tv_usec);

    // Shoot every second
    if (t.tv_sec - lastsec > 0) {
      lastsec = t.tv_sec;
      shoot();
    }

    usleep(LOOPWAIT_MS);
    // Must be as long as TIMEFORMAT
    printf("\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r");
  }
  printf("\n");
  return EXIT_SUCCESS;
}
/* mssleep.c */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
  if (argc != 2) {
    fprintf(stderr, "%s: <milliseconds>\n", argv[0]);
    return EXIT_FAILURE;
  }

  long ms = atol(argv[1]);
  usleep((useconds_t) ms);
  return EXIT_SUCCESS;
}

I was using C to get a good performance but mostly since it has been a while and I wanted to get my hands on it again. The code runs on mac osx leopard using gcc. curl must be installed.

clojure lein gives error „Exception in thread „main“ java.lang.RuntimeException: java.lang.NoSuchMethodError: clojure.lang.KeywordLookupSite …“

For all of you searching for this problem when running lein (1.6) and clojure (1.3). You have to add the clojure directory to your classpath. Simple as that. :-\

$ lein help
Exception in thread "main" java.lang.RuntimeException: java.lang.NoSuchMethodError: clojure.lang.KeywordLookupSite.(ILclojure/lang/Keyword;)V
at clojure.lang.Util.runtimeException(Util.java:165)
at clojure.lang.Compiler.eval(Compiler.java:6476)
at clojure.lang.Compiler.eval(Compiler.java:6431)
at clojure.core$eval.invoke(core.clj:2795)
at clojure.main$eval_opt.invoke(main.clj:296)
at clojure.main$initialize.invoke(main.clj:315)
at clojure.main$script_opt.invoke(main.clj:339)
at clojure.main$main.doInvoke(main.clj:426)
at clojure.lang.RestFn.invoke(RestFn.java:457)
at clojure.lang.Var.invoke(Var.java:413)
at clojure.lang.AFn.applyToHelper(AFn.java:172)
at clojure.lang.Var.applyTo(Var.java:518)
at clojure.main.main(main.java:37)
Caused by: java.lang.NoSuchMethodError: clojure.lang.KeywordLookupSite.(ILclojure/lang/Keyword;)V
at leiningen.util.paths$native_arch_path.(paths.clj:32)
at leiningen.util.paths__init.load(Unknown Source)
at leiningen.util.paths__init.(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at clojure.lang.RT.loadClassForName(RT.java:2030)
at clojure.lang.RT.load(RT.java:417)
at clojure.lang.RT.load(RT.java:398)
at clojure.core$load$fn__4610.invoke(core.clj:5386)
at clojure.core$load.doInvoke(core.clj:5385)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at clojure.core$load_one.invoke(core.clj:5200)
at clojure.core$load_lib.doInvoke(core.clj:5237)
at clojure.lang.RestFn.applyTo(RestFn.java:142)
at clojure.core$apply.invoke(core.clj:602)
at clojure.core$load_libs.doInvoke(core.clj:5271)
at clojure.lang.RestFn.applyTo(RestFn.java:137)
at clojure.core$apply.invoke(core.clj:602)
at clojure.core$require.doInvoke(core.clj:5352)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at leiningen.core$loading__4414__auto__.invoke(core.clj:1)
at leiningen.core__init.load(Unknown Source)
at leiningen.core__init.(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at clojure.lang.RT.loadClassForName(RT.java:2030)
at clojure.lang.RT.load(RT.java:417)
at clojure.lang.RT.load(RT.java:398)
at clojure.core$load$fn__4610.invoke(core.clj:5386)
at clojure.core$load.doInvoke(core.clj:5385)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at clojure.core$load_one.invoke(core.clj:5200)
at clojure.core$load_lib.doInvoke(core.clj:5237)
at clojure.lang.RestFn.applyTo(RestFn.java:142)
at clojure.core$apply.invoke(core.clj:602)
at clojure.core$load_libs.doInvoke(core.clj:5271)
at clojure.lang.RestFn.applyTo(RestFn.java:137)
at clojure.core$apply.invoke(core.clj:604)
at clojure.core$use.doInvoke(core.clj:5363)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at user$eval1.invoke(NO_SOURCE_FILE:1)
at clojure.lang.Compiler.eval(Compiler.java:6465)
... 11 more

Setting the paths:


echo "export CLOJURE_HOME=$HOME/Opt/clojure
export CLASSPATH=$CLASSPATH:$CLOJURE_HOME" >> $HOME/.profile

lein works, tadaaa:

$ lein help
Leiningen is a tool for working with Clojure projects.

Several tasks are available:
classpath Print the classpath of the current project.

Clojure example from „The Joy Of Clojure“ parallelized

I am currently reading „The Joy Of Clojure“ by Michael Fogus and Chris Houser – a great book to see the „why“ behind the clojure way. You should have had a look into clojure before and be willing to read a lot of docs besides the book.

In the book there is a simple example program to display a nice graphic, created by applying xor to the pixel coordinates and using them as grayscale color value. The chapter is „Using the REPL to experiment“.
While reading this part, I thought it would be nice to have that algorithm for parallel processing and experimented a little bit.

The following listing is the result, it modified the original and uses simple threading and the „locking“ macro. It is also interesting to see what happens if you leave out the synchronizing between setting the color and drawing the pixel, as you can see in the screenshots. I hope the original author is okay with using his examples.

Simply paste it to your REPL and try it out.

(defn
  ^{:doc "Calculate the color for a coordinate x and y by applying the given
function. Offset and max values can be specified as input." }
  f-valueso [f xoffset xmax yoffset ymax]
  (for [x (range xoffset xmax) y (range yoffset ymax)
          :let [v (rem (f x y) 256)]]
    [x y (if (< v 0) (* -1 v) v)]
  )
)

(defn
  ^{:doc "Devides the given value in 'parts' equal parts. For
example 200 2 will become [[0 100] [100 200]]"}
  from-to-parts [value parts]
  (loop [
    steps (conj (vec (range 0 value (int (/ value parts)))) value)
    result []
    ]
    (if (seq (rest steps))
      (recur (rest steps) (conj result [(first steps) (second steps)]))
      result
    )
  )
)

; Initialize the frame
(def frame (java.awt.Frame.))
(.setVisible frame true)
(.setSize frame (java.awt.Dimension. 256 256))
(.setLocation frame 300 300)
; Graphics size is only as big as the frame was at getGraphics times
; (that had cost me some time ...)
(def gfx (.getGraphics frame))

(defn clear
  ([g] (.clearRect g 0 0 256 256))
  ([g x y] (.clearRect g 0 0 x y))
)

(defn
  ^{:doc "Draw the picture in a specified area using the color function."}
  draw-part [gfx f xoffset xmax yoffset ymax]
  (doseq [[x y v] (f-valueso f xoffset xmax yoffset ymax)]
;    (Thread/sleep 1) Uncomment this if it draws too fast
    (locking gfx
      (.setColor gfx (java.awt.Color. v v v))
      (.fillRect gfx x y 1 1)
    )
  )
)

(defn
    ^{:doc "Draw a picture to 'gfx' that is created by using the
given color function. Use 'n' threads to create the picture from
0 to x/y max"}
  draw-valuesp [f xmax ymax n]
  (clear gfx)
  (.setSize frame (java.awt.Dimension. xmax ymax))
  (def gfx (.getGraphics frame))
  (clear gfx xmax ymax)
  (doseq [
    [xoffset xmax] (from-to-parts xmax n)
    [yoffset ymax] (from-to-parts ymax n)
  ]
    (.start (Thread. 
      #(draw-part gfx f xoffset xmax yoffset ymax)
    ))
  )
)

(draw-valuesp bit-xor 256 256 3)

The result:

Multithreaded version during processing:

Result without synchronization:

I am aware that there is not much concurrency in the problem and it is not the greatest example to show the power of clojure’s capabilities. But that wasn’t the point of it.

Android music player shuffle is bad

I just wanted to share my experience with the android music player.
From a user interface and feature perspective I am totally happy with it. It is kind of simple, responsive and okay to control as music player in your car. (Hands free of course).

But there is a problem with the shuffle function. I use that feature a lot, since the android is serving me with music almost every day in my car and I really can’t stand the same playlist order every day. The sequential order makes things too predictable and you rapidly get the feeling you heard the songs a million times.

Unfortunately android music player is not shuffling very well. There are often the same tracks in the playlist and the order seems to repeat too. I even got the feeling it doesn’t include all the tracks and just shuffles a subset of them.

It seems like I am not alone with the problem and there is already a bugreport.

So I tried the mobile winamp player. I was not too optimistic since the desktop version of it just evolved to a big fat monster. But I was positively surprised. The player looks nice, is fast and is better at shuffling. I had songs in the playlist again I missed for quite some time now.

The only thing that is not too great is the user interface uses a lot of small button elements. This is not so nice when you use it in your car. Additionally you can’t switch tracks using the little forward / backwards buttons, when the screen is locked but that is not a deal breaker.

Did you have the same experience with android music player? Let me know.

Bogenschießen: 10. Fledermaus Nachtturnier in Darmstadt (de)

Letztes Wochenende fand zum 10. mal das Fledermaus Nachtturnier bei der PSG Darmstadt statt. Es handelt sich dabei um ein Bogenturnier, bei dem man die erste Hälfte noch im Hellen schießt und die zweite Nachts, im Dunkeln. Dabei sind nur die Zielscheiben beleuchtet und es kommt eine ganz besondere Stimmung auf. Man sieht nur noch sein Visier und das Ziel, abgeschottet von sonstigen Eindrücken in der Umgebung.

Wichtig ist hierbei auch die Schussvorbereitung gut zu beherrschen, die Schießlinie ist grundsätzlich nicht beleuchtet und man sollte sich merken wo man den Bogen geparkt hat und wie herum der Pfeil eingelegt gehört.

Schießbeginn war 18 Uhr und man startete mit einigen Probepfeilen. Ich selbe bin leider in Eile angereist und hatte meine Mühe zum schießen ein wenig runter zu kommen. So habe ich es auch während des ganzen ersten Durchgangs nicht geschafft ein zufrieden stellendes Ergebnis abzuliefen. In den Pausen konnte man sich dann bei leckeren Brötchen, Kuchen oder Salaten, die von der PSG gegen eine Spende bereit gestellt wurden, etwas aufheitern.

Gegen halb neun waren die angesetzten 30 Pfeile dann geschossen und es wurde langsam dämmerig.
Dies bekommt man auf dem Bogenplatz in Darmstadt immer recht gut mit, da die Sonne zu der Zeit genau hinter den Zielscheiben unter geht. Da heißt es also die Mütze tief ins Gesicht ziehen.

Die Nacht brach herein und der zweite Durchgang startete ab neun Uhr. Es war alles etwas ruhiger, die Schützen konzentrierten sich noch ein wenig mehr als sonst. Keiner wollte seine Pfeile im Dunkeln suchen müssen. Das hat leider nicht bei allen geklappt und so mancher musste mit Taschenlampe und Metallsuchgerät über die Wiese streifen. Doch auch wenn die Pfeile alle auf einer Scheibe landeten ist man vor Missgeschicken nicht gefeit, schnell hat man im Dunkeln die falsche Bahn erwischt und ein gutes Ergebnis auf die Nachbarscheibe geschossen. Dies zählt leider nicht.

Ein wenig zur Ruhe gekommen und mit gefundenem Schießrythmus verlief mein zweiter Durchgang ohne Probleme und ich konnte Punkte gut machen. Kein Pfeil daneben und Scheibenbester, das muntert auf. So war auch das Endresultat erfreulich und ich habe es noch auf den dritten Platz der Recurve Schützenklasse geschafft.
Meinen ersten Pokal habe ich damit auch bekommen, das hat mich ziemlich gefreut. Bei den Kreis- und Gaumeisterschaften gibt es nur Anstecker und auf der Hessischen war ich leider noch nicht.

Das Nachtturnier in Darmstadt ist auf jeden Fall zu empfehlen. Wer teilnehmen möchte, sollte sich allerdings mit der Anmeldung beeilen da die Plätze meist früh vergeben sind.

Interesse am Bogenschießen? Schaut doch einfach mal bei den Aarfalken in Taunusstein vorbei.

Nachtrag: Ich denke man sollte vielleicht noch erwähnen, dass es auf dem Turnier für jeden noch ein kleines Geschenk als Andenken gibt. Früher gab mal eine selbst gebastelte Fledermaus oder nun eine nett beschriftete Tasse.

(Interessant ist dabei jedoch, dass in der Beigelegten Anleitung steht, dass keine Garantie für die Bruchsicherheit beim Einfüllen von Flüssigkeiten mit über 40°C Temperaturunterschied zur Tasse gegeben wird…)

Flea Market discovery Cherry G81-1000 Keyboard

About two weeks ago I was on a flea market and saw an old cherry keyboard. I always heard of the legendary IBM type M keyboard that makes a unique click sound and wanted to have one of these. But the ones still produced cost about 90$ at pckeyboard.com! So I thought, give that old cheery one a try and buy it … for 1,50€ it won’t hurt and may be similarly cool.

So I bought a nice old G81-1000 which was still rather white, compared to the usual computer nicotine yellow you see out there. :) The keys are not as smooth as I had hoped but in my opinion the sound is quite classic.

One little detail being a problem was the old DIN instead of a PS/2 connector. The adapter could be found on amazon but I would bet there are only some remnants.

The whole circuit board and key sensors are pretty robust and will probably survive all the rest of my current hardware. Here are some fotos I short during the big cleaning session.

More Information about Cheery G81 and G80: http://geekhack.org/showwiki.php?title=Island:5757

mod_rewrite proxy targets must be allowed first

I was trying to install a proxy redirect on my server in order to bypass the same origin policy for GWT Ajax requests. We are not using the default java servlets but a perl backend.

Therefore I wanted to rewrite a path „http://myhost/mk/*&#8220; to the host where the actual request endpoint was „http://targethost/$1&#8220;.

The Idea was to use mod_rewrite and first of all it had to be enabled. Additionally mod_proxy is used if proxy rewrites are involved. On debian this works using:

$ a2enmod rewrite; a2enmod proxy_http

The vhost config looks like this:

<VirtualHost myhost:80>
ServerName gt.myhost

RewriteEngine On
RewriteLogLevel 3
RewriteLog "/var/log/apache2/rewrite.log"
RewriteRule ^/mk/(.*) http://targethost/$1 [P]

# Allow the proxy to targethost ...
<Proxy http://targethost/*&gt;
Order deny,allow
Allow from all
</Proxy>

DocumentRoot /var/www/gt
</VirtualHost>

Important is the Proxy element here, which was not obvious to me from the start. I missed it and just got the following output in rewrite.log and error.log when trying to call http://gt.myhost/mk/login.

(2) rewrite '/mk/login' -> 'http://targethost/login'
(2) forcing proxy-throughput with http://targethost/login
(1) go-ahead with proxy request proxy:http://targethost/login [OK]

[error] client denied by server configuration: proxy:http://targethost/login

So, make sure you got the Proxy Element right, too, when using mod_rewrite and [P].

References:

mod_rewrite manual
apache rewrite guide
Ubuntu mod_rewrite Problem

GWT 2.2.0 and EXT GWT no success

I tried to use EXT GWT with GWT 2.2.0 and had no success … no one told me I couldn’t do that.

Afterwards I found out there really is no accurate version requirement noted for EXT GWT. „GWT 1.5 or above is required“ from the helpcenter was not very helpful here.

What I started with and wanted to use was:

<gwtVersion>2.2.0</gwtVersion>
<gwtMavenVersion>2.2.0</gwtMavenVersion>
<gwtLogVersion>3.1.0</gwtLogVersion>
<ginVersion>1.5</ginVersion>
<!-- My Wish: From the Sencha Roadmap, not yet released: 3.0 -->
<extGwtVersion>2.2.0</extGwtVersion>

(maven Dependency configuration)

Which resulted in compilation errors:

$ mvn -Dmaven.test.skip package
java.lang.IncompatibleClassChangeError: Found interface com.google.gwt.core.ext.typeinfo.JClassType, but class was expected at com.extjs.gxt.ui.rebind.core. TemplatesGenerator$SourceGenerator.validateType(TemplatesGenerator.java:142) at com.extjs.gxt.ui.rebind.core. TemplatesGenerator$SourceGenerator.generate(TemplatesGenerator.java:97) at com.extjs.gxt.ui.rebind.core. TemplatesGenerator.generate(TemplatesGenerator.java:56)
...

I found some board entries about that. So I had to downgrade GWT and a couple of libraries like the maven gwt plugin, gin and gwt log. Thanks to maven this was less horrible than it could have been.

<gwtVersion>2.1.1</gwtVersion>
<gwtMavenVersion>2.1.0-1</gwtMavenVersion>
<gwtLogVersion>3.0.2</gwtLogVersion>
<ginVersion>1.0</ginVersion>
<extGwtVersion>2.2.0</extGwtVersion>
<warPluginVersion>2.1.1</warPluginVersion>

So, dear vendors, please make more accurate requirement definitions.