Lost my gitosis' post-update

Don’t ask me why neither how, but I’ve lost the gitosis’ post-update on my server. So, among others, the .gitosis.conf wasn’t updated anymore…

Ok, let’s start at the beginning. I’m hosting some git repositories on my server using gitosis. Today I tried to create a new repository by editing the gitosis.conf in the gitosis-admin repo, but I couldn’t push the new created repo to the server:

~ % git push origin master:refs/heads/master
ERROR:gitosis.serve.main:Repository read access denied
fatal: The remote end hung up unexpectedly

Damn, looking at the server all rights through the gitosis home seem to be ok. But I was wondering why the $HOME/.gitosis.conf of the gitosis user wasn’t updated!? How could this happen?

After some thoughts I found out, that the link $HOME/repositories/gitosis-admin.git/hooks/post-update was pointing to nirvana:

lrwxrwxrwx 1 gitosis gitosis 97 Aug 23  2009 /home/git/repositories/gitosis-admin.git/hooks/post-update -> /usr/share/python-support/gitosis/gitosis-0.2-py2.5.egg/gitosis/templates/admin/hooks/post-update

Seems that the file /usr/share/python-support/gitosis/gitosis-0.2-py2.5.egg/gitosis/templates/admin/hooks/post-update was deleted through an update (one week ago I updated gitosis 0.2+20090917-9 -> 0.2+20090917-10 ).. Didn’t find an announce of it or any workaround, but I identified a template in /usr/share/pyshared/gitosis/templates/admin/hooks/post-update . So the solution (hack) is to link to that file:

ln -s /usr/share/pyshared/gitosis/templates/admin/hooks/post-update $GITOSISHOME/repositories/gitosis-admin.git/hooks/post-update

Just replace $GITOSISHOME with the home of your gitosis user, mine lives for example in /home/git .

Now every think works fine. If anybody has a better solution please tell me!

Suffix trees

Suffix trees are an application to particularly fast implement many important string operations like searching for a pattern or finding the longest common substring.

Introduction and definitions

I already introduced the Z-Algorithm which optimizes the searching for a pattern by preprocessing the pattern. It is very useful if you have to search for one single pattern in a large number of words. But often you’ll try to find many patterns in a single text. So the preprocessing of each pattern is ineffective. Suffix trees come up with a preprocessing of the text, to speed up the search for any pattern.

As expected a suffix tree of the word (length ) is represented in a data structure of a rooted tree. Every path from root to a leave represents a suffix of $ with . The union . Every inner node (except root) has at least two children. Every edge is labeled with a string of , labels of leaving edges at a single node start with different symbols and each leaf is indexed with . The concatenation of all edge labels on a path from root to a leaf with index represents the suffix .

Definition 1: For each node :

The path from root to is called

  • The union of the labels at all edges on is
  • is label of path ()
  • is path label to ()
  • instead of we can call this node

Definition 2: A pattern exists in suffix tree of (further called ) if and only if there is a , so that contains a node with ().

Definition 3: A substring ends in node or in an edge to with .

Definition 4: A edge to a leaf is called leaf-edge.

The tree contains all suffixes of the word extended with $. This tree is visualized in figure 1.

Building suffix trees: Write only top down

The write-only, top-down (WOTD) algorithm constructs the suffix tree in a top-down fashion.

Algorithm

Let be a node in , then denotes the concatenation of all edge labels on the path to (). Each node in the suffix tree represents the set of all suffixes that have the prefix . So the set of pathlabels to leafs below can be written as (all suffixes of the set of suffixes that start with ).

This set is splitted in equivalence classes for each symbol with is the -group of .

Case 1: For groups that contain only one suffix we create a leaf with the index and connect it to with an edge containing label . Case 2: In groups with a size of at least two we compute their longest common prefix that starts with and create a node . The connecting edge between and gets the label and we continue recursively with this algorithm in node with

Applications

Exact pattern matching

All paths from the root of the suffix tree are labeled with the prefixes of path labels. That is, they’re labeled with prefixes of suffixes of the string . Or, in other words, they’re labeled with substrings of . To search for a pattern in , just go through , following paths labeled by the characters of . At any node with is prefix of find the edge with label that starts with symbol . If such an edge doesn’t exists, isn’t a substring of . Otherwise try to match the pattern with to node . If is not a prefix of you’ll either get a mismatch denoting that isn’t a substring of , or you ran out of caracters of and found it in the tree. If is a prefix of continue searching at node . If you were able to find in , contains at any position denoted by the indexes of leafs below your point of discovery.

Minimal unique substrings

is a minimal unique substring if and only if contains exactly once and any prefix of can be found at least two times in .

To find such a minimal unique substring walk through the tree to nodes with a leaf-edge . A minimal unique substring is with is the first char of , because its prefix isn’t unique ( has at least two leaving edges) and every extended version has a prefix that is also unique.

Maximal repeats

A maximal pair is a tuple , so that , but and . A maximal repeat is the string represented by such tuple. If is a maximal repeat there is a node in . To find the maximal repeats do a DFS on the tree. Label each leaf with the left character of the suffix that it represents. For each internal node:

  • If at least one child is labeled with c, then label it with c
  • Else if its children’s labels are diverse, label with c.
  • Else then all children have same label, copy it to current node.

Path labels to left-diverse nodes are maximal repeats.

Generalized suffix trees

An extension of suffix trees are generalized suffix trees. With it you can represent multiple words in one single tree. Of course you have to modify the tree, so that you know which leaf index corresponds to which word. Just a little bit more to store in the leafs ;) A generalized suffix tree is printed in figure 2 of page one.

Further applications

There are a lot of other applications for a suffix tree structure. For example finding palindromes, search for regular expressions, faster computing of the Levenshtein distance, data compression and so on…

Implementation

I’ve implemented a suffix tree in Java. The tree is constructed via WOTD and finds maximal repeats and minimal unique substrings. I also wanted pictures for this post, thus, I added a functionality that prints GraphViz code that represents the tree.

Download: Java: Code from GitHub (Please take a look at the man-page. Browse bugs and feature requests.)

Cracked the centenary!

Wow, the new kernel is the 100th.

~ % grep '^kernel' /boot/grub/menu.lst | wc -l
100

(That was the reason why the dist-upgrade took more than an hour!^^)

Bye sidux - welcome aptosid!

I just dist-upgraded to aptosid, sidux is gone.

Yesterday the sidux team announced that sidux is dead, but the good news just followed:

As I am sure you are all aware, there have been interesting times for sidux recently. The bad news is that the sidux project is dead. The good news is that aptosid has been aptly born like a phoenix from the ashes and will provide a smooth upgrade for sidux systems. In many ways nothing has changed but our name.

After a long period of silence I already change the OS on my notebook from sidux to grml. It’s a very good alternative, but I decided to wait for an official announcement before deleting my main OS.

Now, the official announce is released, I upgraded my system to aptosid. First of all I created a aptosid.list in my /etc/apt/sources.list.d/ containing:

deb http://debian.tu-bs.de/project/aptosid/debian/ sid main fix.main contrib fix.contrib non-free fix.non-free vdr
deb-src http://debian.tu-bs.de/project/aptosid/debian/ sid main fix.main contrib fix.contrib non-free fix.non-free vdr

deb ftp://ftp.spline.de/pub/aptosid/debian/ sid main fix.main contrib fix.contrib non-free fix.non-free vdr
deb-src ftp://ftp.spline.de/pub/aptosid/debian/ sid main fix.main contrib fix.contrib non-free fix.non-free vdr

After wards calling aptitude update to reread the package listings. It notifies me that the new servers couldn’t be verified, I had to install the new keyring:

aptitude install aptosid-archive-keyring

It’s time to upgrade:

aptitude update
aptitude dist-upgrade

That fails at the first time:

Running update-initramfs.
update-initramfs: Generating /boot/initrd.img-2.6.35-4.slh.9-aptosid-amd64
initrd.img(/boot/initrd.img-2.6.35-4.slh.9-aptosid-amd64
) points to /boot/initrd.img-2.6.35-4.slh.9-aptosid-amd64
 (/boot/initrd.img-2.6.35-4.slh.9-aptosid-amd64) -- doing nothing at /var/lib/dpkg/info/linux-image-2.6.35-4.slh.9-aptosid-amd64.postinst line 348.
vmlinuz(/boot/vmlinuz-2.6.35-4.slh.9-aptosid-amd64
) points to /boot/vmlinuz-2.6.35-4.slh.9-aptosid-amd64
 (/boot/vmlinuz-2.6.35-4.slh.9-aptosid-amd64) -- doing nothing at /var/lib/dpkg/info/linux-image-2.6.35-4.slh.9-aptosid-amd64.postinst line 348.
Running /usr/sbin/update-grub.
Can't exec "/usr/sbin/update-grub": No such file or directory at /var/lib/dpkg/info/linux-image-2.6.35-4.slh.9-aptosid-amd64.postinst line 770.
User postinst hook script [/usr/sbin/update-grub] failed to execute: No such file or directory
dpkg: error processing linux-image-2.6.35-4.slh.9-aptosid-amd64 (--configure):
 subprocess installed post-installation script returned error exit status 255

As you see, /usr/sbin/update-grub wasn’t found. It is in grub-pc , but I have no idea why there isn’t a dependency so that grub-pc is installed by default!? Not fine but doesn’t matter, just install it:

aptitude install grub-pc
aptitude dist-upgrade

If this is done, just reboot and join the new kernel version 2.6.35 (slh is the greatest!!).

~ % uname -r
2.6.35-4.slh.9-aptosid-amd64

Jabber meets Twitter

This evening I implemented a XMPP bridge to twitter. So I’ll get all news via IM and can update my status by sending an IM to a bot.

Nothing new, I don’t like the twitter web interface. Neither to read, nor to write messages. So I developed some scripts to tweet from command line. These tools are still working, but not that comfortable as preferred.

Today I had a great thought. At Gajim I’m online at least 24/7, talking with people, getting news etc. So the comparison with twitter is obvious.

After some research how to connect to twitter and jabber I decided to implement the bot in Perl. I still worked a little bit with Net::Twitter, so one side of the connection is almost done. For the other side I used the module Net::Jabber::Bot to implement a bot listening for messages or commands and sending twitter news via IM to my jabber account. The call for the jabber bot looks like:

my $bot = Net::Jabber::Bot->new ({
	server => $j_serv
	, port => $j_port
	, username => $j_user
	, password => $j_pass
	, alias => $j_user
	, message_function => \\&messageCheck
	, background_function => \\&updateCheck
	, loop_sleep_time => 40
	, process_timeout => 5
	, forums_and_responses => {}
	, ignore_server_messages => 1
	, ignore_self_messages => 1
	, out_messages_per_second => 20
	, max_message_size => 1000
	, max_messages_per_hour => 1000});

$bot->SendPersonalMessage($j_auth_user, "hey i'm back again!");
$bot->Start();

Most of it should be clear, the function messageCheck is called when a new message arrives the bot’s jabber account. There I parse the text whether it starts with ! (then it’s a command) otherwise the bot schould take the message to update the twitter status. updateCheck is the background function, it’s called when the bot idles. Here is time to check for news at twitter. It is called loop_sleep_time secs.

The rest is merely a matter of form. News from twitter are jabber’ed, IM’s from the authorized user are twitter’ed. Cool, isn’t it!?

Just download the tool, create a new jabber account for the bot (you’ll get one for example from jabber.ccc.de) and update the jmt.conf file with your credentials. Of course you need the additional Perl modules, if you also experience various problems with Net::Jabber::Bot try to use the latest code from git://github.com/toddr/perl-net-jabber-bot.git.

The bot could simply be launched by running the Perl script. Send !help to the bot to get some information about known commands. Just start it at any server/PC that has a network connection.

What comes next? If anyone would provide a server I would like to implement a multiuser tool, maybe with database connectivity!?

Download: Perl: jmt.tgz please see GitHub for the latest version (Please take a look at the man-page. Browse bugs and feature requests.)

Advanced searching via Z-Algorithm

I’m actually learning some stuff related to algorithms on sequences. The naive search for a pattern in a long string is of course very slow and comes with a lot of unintelligent compares. The Z-Algorithm improves the searching by preprocessing the pattern.

Naive searching

A simple search algorithm written in java may look like

public void search (String needle, String haystack)
{
	for (int off = 0; off < haystack.length () - needle.length () + 1; off++)
	{
		boolean found = true;
		for (int p = 0; p < needle.length (); p++)
			if (needle.charAt (p) != haystack.charAt (off + p))
			{
				found = false;
				break;
			}
		if (found) System.out.println ("Fount pattern at position " + off);
	}
}

This code reliably finds any existence of needle in haystack in , with length of needle and length of haystack. That screams for improvements ;)

Definitions

The first algorithm that I want to present in this series is called Z-Algorithm. First of all we need some definitions.

Definition 1: In the following we denote as the substring of beginning at position and ending at position . We can also leave one of the limits clear, so that is the substring and means .

Definition 2: So is the length of the longest prefix of the suffix that is also prefix of itself. To abbreviate is further on mentioned as .

Definition 3: The set for a is called Z-Box at position .

Definition 4: is the set of limits of all Z-Box’es that start at the left-handed side of . Consider .

Definition 5: If and , defines the rightest Z-Box that starts before respectively at position . Consider .

Algorithm

In the following will denote the actual position we are looking for, and describe the current respectively last found of a Z-Box. First of all we set the values and to zero because we haven’t found any Z-Box yet. of our text is according to Definition 2 the length of the longest prefix of that is also prefix of itself. If we found a first Z-Box and update the limits to and .

Now we have to run through the word , so with defines the length of .

Case 1: Let’s assume position is outside of the last found Z-Box or we didn’t find any Z-Box yet (). We find by comparing the prefixes of and . If we’ve found a new Z-Box and need to update the limits to and .

Case 2: If the current position is inside of a current Z-Box () we try to find the equivalent position at the beginning of . The position we are searching for is steps off the beginning of (we are steps behind and has the same prefix as ). Case 2a: If we don’t break out of the current Z-Box by creating another Z-Box with the length of the box at position (, so position is not behind position ), we can simply apply this Z-Box to the current position and . Case 2b: Otherwise, if we would leave the actual Z-Box () we have to recheck the prefix conditions of and . We know that equals , so we only have to find the length of the longest prefix of that equals the prefix of . Now we can apply the new Z-Box such that and of course we update the Z-Box limits to and .

If we reached the end of all Z-Boxes are found in .

Pseudo code

l = r = 0
Z[2] = prefix (S, S[2 ..]).length
if Z[2] > 0 then
	l = 2
	r = 2 + Z[2] - 1

for i = 3..|S| do
	if i > r then 										'(case 1)'
		Z[i] = prefix (S, S[i ..]).length
		if Z[i] > 0 then
			l = i
			r = i + Z[i] - 1

	else 												'(case 2)'
		k = i - l + 1
		if Z[k] < r - i + 1 then 						'(case 2a)'
			Z[i] = Z[k]

		else											'(case 2b)'
			p = prefix (S[r - i + 2 ..], S[r + 1 ..]).length
			Z[i] = r - i + 1 + p
			l = i
			r = i + Z[i] - 1

Example

Let me demonstrate the algorithm with a small example. Let’s take the word . First we start with and at position 2. is the length of the shared prefix of () and (). Easy to see the prefix is with a length of 1. So , and . At the beginning of our for-loop the program’s status is:

$$T$$aabaaab
$$i$$12
$$Z_i$$1
$$l$$2
$$r$$2

At the first round in the loop , so because . So we meet case 1 and have to find the length of the prefix of () and (). Of course it’s zero, nothing to do.

$$T$$aabaaab
$$i$$123
$$Z_i$$10
$$l$$22
$$r$$22

Next round, we’re at position 4 and again (case 1). So we have to compare and . The longest prefix of both words is with a length of 2. So we start a new Z-Box at 4 with a size of 2, so and .

$$T$$aabaaab
$$i$$1234
$$Z_i$$102
$$l$$224
$$r$$225

With and we reach case 2 for the first time. so our similar position at the beginning of is position 2. and so we are in case 2b and have to find the shared prefix of () and (). It’s , so and . and .

$$T$$aabaaab
$$i$$12345
$$Z_i$$1023
$$l$$2245
$$r$$2257

Next round brings us , therefor we’re in case 2. Equivalent position is again , but now and we’re in case 2a and can just set .

$$T$$aabaaab
$$i$$123456
$$Z_i$$10231
$$l$$22455
$$r$$22577

The last round we have to process is , case 2. Equivalent position is and , so case 2a and .

$$T$$aabaaab
$$i$$1234567
$$Z_i$$102310
$$l$$224555
$$r$$225777

That’s it. The Z-Box’es we’ve found are visualized in the image.

Searching

To search for a pattern in a text just calculate the Z-Boxes of with . These calculations are done in . For any : If means is prefix of , so is found at position in .

Code

Of course I’m providing an implementation, see attachment.

Download: Java: Zbox.java (Please take a look at the man-page. Browse bugs and feature requests.)

SSH escape sequences

Such as telnet the SSH protocol also has a control character, it’s the tilde (~).

If you for example want to kill a hanging SSH session just type ~. . With ~^Z you can suspend a running session and get back to your local machine. To reactivate it just type fg (yes, the SSH session is also just a job). All supported escape sequences will be listed with ~? :

me@remote ~ % ~?
Supported escape sequences:
  ~.  - terminate connection (and any multiplexed sessions)
  ~B  - send a BREAK to the remote system
  ~C  - open a command line
  ~R  - Request rekey (SSH protocol 2 only)
  ~^Z - suspend ssh
  ~#  - list forwarded connections
  ~&  - background ssh (when waiting for connections to terminate)
  ~?  - this message
  ~~  - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)

All sequences are of course only understood after a newline ;)

First HTML5 experiences

Although I have too much to do it’s in the nick of time to try some stuff with HTML5.

You should all have heard about HTML5, next generation of web ;) I still saw a lot of new features, some are still not supported in many browsers but all in all I’m looking forward.

Here I played a little bit with the canvas stuff and created a binary clock:

Wasn’t that difficult, just created an HTML element of type canvas with enough space in it to draw the clock:

<canvas id="clock" width="250" height="100"></canvas>

and via JavaScript I draw the clock in it:

/* JS binary clock by Martin Scharm <http://binfalse.de> */
function init()
{
	clock();
	setInterval(clock,1000);
}
function draw (ctx, x, y, stroke)
{
	ctx.beginPath(); 
	ctx.arc(x, y, 9, 0, Math.PI*2,true);
	if (stroke) ctx.stroke();
	else ctx.fill ();
}
function clock ()
{
	var canvas = document.getElementById("clock");  
	if (canvas.getContext)
	{  
		var offset = 60;
		var ctx = canvas.getContext("2d");
		ctx.save();
		ctx.clearRect(0,0,300,300); 
		var now = new Date();
		var sec = now.getSeconds();  
		var min = now.getMinutes(); 
		var hr  = now.getHours(); 
		for (var i = 0; i < 3; i++)
			for (var x = 0; x < 2; x++)
				for (var y = 0; y < 3; y++)
				{
					draw (ctx, i*offset + x*20 + 20, y*20 + 20, true);
				}
				for (var x = 1; x < 3; x++)
					for (var y = 2; y < 4; y++)
					{
						ctx.beginPath();
						ctx.arc(x * offset, y * 20, 4, 0, Math.PI*2,true);
						ctx.fill ();
					}
					for (var x = 0; x < 2; x++)
						for (var y = 0; y < 3; y++)
						{
							if (sec & Math.pow (2, (1 - x) * 3 + 2 - y)) draw (ctx, 2*offset + x*20 + 20, y*20 + 20, false);
							if (min & Math.pow (2, (1 - x) * 3 + 2 - y)) draw (ctx, 1*offset + x*20 + 20, y*20 + 20, false);
							if (hr & Math.pow (2, (1 - x) * 3 + 2 - y)) draw (ctx, x*20 + 20, y*20 + 20, false);
						}
						ctx.fillText(hr + ":" + min + ":" + sec, 70, 80);
					ctx.restore();
	}
}

After wards just called init (); , that calls clock(); once a second to draw the clock. Please tell me whether it works in your browser ;)

If anybody is interested, here is the code: html5_clock. If you also want to deal with it, Mozilla has a good tutorial.

I hope this new age of web will delete all the flash trash out there!

Download: Javascript: html5_clock.js (Please take a look at the man-page. Browse bugs and feature requests.)

Umlauts on English keyboards

Micha is just sitting next to me, writing a new blog post. He’s writing in German with an English keyboard, so he has to encode umlauts like ä with an &auml; . I can not watch any longer, here is the trick.

Still blogged about it, you can create such additional keys with Xmodmap. So choose a key, get its key code for example with xbindkeys -k and create a file $HOME/.Xmodmap with the following syntax:

keycode XXX = YYY

XXX ist the code of your key and YYY is that what should happen. For example:

keycode  137 = adiaeresis Adiaeresis
keycode  139 = udiaeresis Udiaeresis
keycode  141 = odiaeresis Odiaeresis 
keycode  143 = ssharp ssharp

That gives you an ä/Ä on the key with code 137 and so on. To let the file take effect just run xmodmap $HOME/.Xmodmap . Btw xmodmap -pke will give you the actual running keymap. So Micha, no need to type to much ;)

Twitter disabled Basic Authentication

Some of you may have recognized that twitter has disabled the so called Basic Authentication. So my previous twitter-tools don’t work anymore. But don’t bury your head in the sand, here are the newer versions.

Basic Authentication means you send your account information (username/password) unencrypted with your query (status update/timeline request/…) to twitter. Of course this method isn’t a nice way, so twitter disabled this method of authentication.

But the new methods of API calls are more complicated (called “OAuthcalypse”) and I really don’t like them. But whoever listens to me?

If you now want to interact with the twitter API, you have to register your tool as new twitter tool. Don’t ask me why, but you have to choose an unique name (all over the twitter world) for your application and get some random strings. For example for a Perl script you need the ones called Consumer key and Consumer secret.

If you want to interact with twitter, you have to do the following:

<li>send the combination of <em>Consumer key</em> and <em>Consumer secret</em> to the server
<li>receive an URL from the server where the user itself can find a pin code (when (s)he is logged into twitter)
<li>send this code to the server again and the user is verified
<li>receive some more authentication information from the server, store it for the next time, so the user don't have to authenticate again

Very annoying method, but there is no alternative method and at least your account is more save against hijacker.

By the way I found a Perl module called Net::Twitter that helps a lot.

Here is my snippet to solve this authentication stuff:

use Net::Twitter;

my $CRED_FILE = "somefile";

sub restore_cred {#read creds from $CRED_FILE}
sub save_cred {#write creds to $CRED_FILE}

my $nt = Net::Twitter->new(traits => ['API::REST', 'OAuth'], consumer_key => "KEY", consumer_secret => "SECRET",);
my ($access_token, $access_token_secret) = restore_cred();
if ($access_token && $access_token_secret)
{
	$nt->access_token($access_token);
	$nt->access_token_secret($access_token_secret);
}

unless ( $nt->authorized )
{
	print "Authorize this app at ", $nt->get_authorization_url, " and enter the PIN: ";
	chomp (my $pin = <stdin>);
	my($access_token, $access_token_secret, $user_id, $screen_name) = $nt->request_access_token(verifier => $pin);
	if (save_cred($access_token, $access_token_secret))
	{ print "successfull enabled this app! credentials are stored in: " . $CRED_FILE . "\\n" }
	else
	{ die "failed\\n"; }
}
if ($nt->update({ status => $status }))

Ok, you see it’s not impossible to solve this problem. And there is another advantage, with these two scripts I don’t have to provide my username/passwort any more.

Here is the script to tweet from command line and this script dumps the actual news to the console.

To use my tools just download them to your machine, rename them as you want and then just run it:

  • To tweet something call tweet-v2.pl with your status message as argument.
  • To get latest informations from the people you are following just call twitstat-v2.pl with an optional argument defining the maximal number of messages you want to see.

For the first time you’ll see a link where you’ll get your pin (open the link with your browser), after wards the tools will store your credentials in [toolname].credentials . Just try it, won’t (hopefully) break anything :P

Download: Perl: tweet-v2.pl (tweet from command line) Perl: twitstat-v2.pl (get latest news) (Please take a look at the man-page. Browse bugs and feature requests.)