Monday, December 30, 2013

Framebuffer and Vigra running on Raspberry Pi

I just had some spare hours that I could spend working on my Raspberry Pi. I finally got the framebuffer running in conjunction with vigra:
http://www.youtube.com/watch?v=tcMQd5eSeLA&feature=youtu.be

Friday, December 13, 2013

C+=

From now on, I will dump C++ and use this new progamming language: https://github.com/FeministSoftwareFoundation/C-plus-Equality Apparently, the content has been deleted from github. You can still find it on bitbucket: https://bitbucket.org/FeministSoftwareFoundation/c-plus-equality/overview

Thursday, December 12, 2013

classicthesis.sty

Just found this in the latex package classicthesis (classicthesis.sty):

% Disable single lines at the end of a paragraph (Hurenkinder)

Friday, November 29, 2013

Detexify - Easily find the LaTeX command you are looking for

Have you ever been searching for hours when you needed just a simple LaTeX command for a symbol? Well, this might be over now:
Check out Detexify: Just draw the symbol you need and the applet will give you possible matches for your query.

Sunday, November 10, 2013

Framebuffer Manipulation with Vigra(numpy) Interface for Linux Framebuffer

I wrote an interface that allows accessing a Linux framebuffer using vigra(numpy). It is at a very early stage and lacks documentation and offers only very basic functionality (writing an array to the framebuffer) so far.
This video shows the library in action. Again, all that is included is vigranumpy and Linux framebuffer. No X or other graphics system is used.

Another video showing framebuffer manipulation in action (vigra.filters.gaussianGradientMagnitude), this time captured directly from framebuffer using ffmpeg.

As always, the code can be found on my git repository:
https://github.com/hanslovsky/rpi_st7735

Sunday, November 3, 2013

Sainsmart 1.8" finally running on Arch@RaspberryPi

R and B channels are swapped, but that just requires copying the newly compiled kernel to the pi.
http://www.youtube.com/watch?v=GA3vhDO2cxs&feature=youtu.be



Acknowledgements:
I followed these instructions:
http://www.whence.com/rpi/
http://marks-space.com/2012/11/23/raspberrypi-tft/

This was neccessary in order to get the kernel to work:
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=53&t=53784

The video shown on the display is taken from:
http://hubblesource.stsci.edu/sources/video/clips/

Image source:
gramophone.co.uk

Saturday, November 2, 2013

First Successful Image Operation Using Vigra On Arch@Raspberry Pi

I just applied a gaussian gradient magnitude filter on an image in vigra on arch@raspberry pi for the first time. It took me quite a while to get it running, but now Image analysis can be done on that little box.



Image Source:

Friday, November 1, 2013

Raspberry Pi X-Compilation using distcc

I just successfully used distcc for cross compilation for the first time on my Raspberry Pi. I am using Arch Linux both on my Pi and my desktop. You can get distcc from the official Arch repos.
Setting up distcc is not hard:
You need to edit the following files (as root):

  • /etc/conf.d/distcdd (both server(s) and daemon):
    • add allowed ip addresses to DISTCC_ARGS with --allow <addr>
  • /etc/makepkg.conf (daemon only):
    • in BUILDENV: change !distcc to distcc
    • uncomment DISTCC_HOSTS and add hosts using the format <addr>/<number of threads>
    • edit MAKEFLAGS to use the desired number of threads, e.g. MAKEFLAGS="-j3"
    • if neccessary specifiy a PATH variable
  • /etc/distcc/hosts (daemon only):
    • add the hosts here (this seems redundant, but it was neccessary for me)
In order to use distcc you will need proper compilers on your hosts. For the Pi you can build your own toolchain or just download one if it's available for your platform.
Test your compiler with a small program like this (c++):

distcc c++ hello.cxx -o hello

Instructions and a cross compilation toolchain for Arch can be found here:

Thursday, October 24, 2013

Python: defaultdict of defaultdict

Recently I was trying to create a nested dict (or better nested defaultdict) in Python. This is the solution that matched my needs perfectly:

 from collections import defaultdict
nested_dict = defaultdict(lambda : defaultdict(list))

The defaultdict constructor takes any factory as an argument, a requirement that can be easily be met using python lambda functions.

Sunday, September 1, 2013

PyQt4: Widget that holds an image and a quit button

I made an extension to the WidgetWithQuit class I introduced recently in this post.
It now can hold an image (input should be a 2D or 3D numpy.ndarray). In WidgetWithQuit the quit button would keep its position relative to the bottom right corner. In WidgetWithPictureAndQuit the image displayed is resized likewise: It always keeps the distance to the borders and the quit button while keeping the aspect ratio. If the image, after resizing, is not centered (it happens, when it is not wide enough), it will be centered, such that the distance to the left and right border will be increased.
In addition to the usual imports, you now also need qimage2ndarray which can be installed via pip.
Please note that in order to make the example shown below work you will need the code introduced in my recent post.

from qimage2ndarray import array2qimage

class WidgetWithPictureAndQuit(WidgetWithQuit):
    def __init__(self, parent=None, buttontext="Quit", margin=10, image=None):
        WidgetWithQuit.__init__(self, parent, buttontext, margin)
        self.image = array2qimage(image)
        self.label = QtGui.QLabel(self)
        if self.image is not None:
            self.resize_image()

    def resize_image(self):
        widget_geometry = self.geometry()
        button_geometry = self.quit_button.geometry()
        width = widget_geometry.width() - 2*self.margin
        height = widget_geometry.height() - (button_geometry.height() + 3*self.margin)
        width_offset = self.margin
        pixmap = QtGui.QPixmap.fromImage(self.image).scaled(width, height, QtCore.Qt.KeepAspectRatio)
        if pixmap.width() < width:
            width_offset = (widget_geometry.width() - pixmap.width())/2
        self.label.setGeometry(width_offset, self.margin, width, height)
        self.label.setPixmap(pixmap)

    def resizeEvent(self, event):
        WidgetWithQuit.resizeEvent(self, event)
        self.resize_image()

PyQt: Qt Widget with button with a fixed margin from bottom right corner

PyQt4 provides an easy to use interface for the creation of GUI Applications. In order to get some practice in PyQt4 I decided to create a subclass WidgetWithQuit of QWidget that has a QuitButton (derived form QPushButton) as member variable that sends a quit signal to the qapp on a left click.
Thanks to the high level interface of PyQt4 this requires only a small modification of the resizeEvent function of QWidget (see code below).


from PyQt4 import QtGui, QtCore
import sys


class QuitButton(QtGui.QPushButton):
    def __init__(self, parent, text="Quit"):
        QtGui.QPushButton.__init__(self, text, parent)
        parent.connect(self, QtCore.SIGNAL('clicked()'),
                       QtGui.qApp, QtCore.SLOT('quit()'))
        self.resize(self.sizeHint().width(), 
                    self.sizeHint().height())


class WidgetWithQuit(QtGui.QWidget):
    """QWidget that has a QuitButton at the bottom right;
    margin specified in the constructor"""
    def __init__(self, parent=None, buttontext="Quit", margin=10):
        self.margin = margin
        QtGui.QWidget.__init__(self, parent)
        self.quit_button = QuitButton(self, text=buttontext)
        self.align_button()

    def align_button(self):
        widget_geometry = self.geometry()
        button_geometry = self.quit_button.geometry()
        width_offset = widget_geometry.width() - (button_geometry.width() + self.margin)
        height_offset = widget_geometry.height() - (button_geometry.height() + self.margin)
        self.quit_button.move(width_offset, height_offset)

    def resizeEvent(self, event):
        QtGui.QWidget.resizeEvent(self, event)
        self.align_button()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    widget = WidgetWithQuit()
    widget.setGeometry(300, 300, 100, 100)
    widget.quit_button.setToolTip('Quit on left mouse click')
    widget.show()
    sys.exit(app.exec_())

Of course this is just a very simple, "academic" example; still it should be clear that PyQt4 offers an easy to use interface to build user-friendly GUI applications.
Thanks to C/C++ binding generators such as boost python you can still rely on fast C/C++ for the underlying algorithms which gives you the best of both worlds: easy implementation of the GUI using a high level language and fast algorithms working on (big) data in the background.
For the documentation of the classes used above, see:

Thursday, July 25, 2013

install_name_tool on OSX

Usually I do not have to cope with OSX. But today I had to and Apple's dylib policy drove me crazy (especially when there are many dylibs with absolute paths to their dependencies). The blogpost that saved the day for me introduced the handy tool install_name_tool. Calling with the -id switch, you can change the install name of the target. When used with the -change switch, install_name_tool will change the path to the dependency according to your settings (paths preferably relative!).
I wrote this post in case I ever have to deal with OSX again. Knowing that makes life a lot easier.

Saturday, July 20, 2013

blog recommendation

Whoever is interested in C++ should have a look at http://herbsutter.com/. Amongst other occupations Herb Sutter used to be a chair of the ISO C++ standards comittee. That qualifies him to produce interesting and informative posts on C++, especially with regard to standard C++.

For me the section Guru of the Week is  particularly useful. Every week there's a C++ problem (not a specific implementation task, but general questions regarding standard C++) that you can try to solve yourself. If you need a hint or are just interested in the solution, there is always an exhaustive answer. The problems are being updated to match C++14, therefore many problems are currently offline for revision. However, until they are back again, I recommend having a peek at the remaining ones.

Thursday, July 11, 2013

Disable CPU throttling in Debian (aptosid)

When building ATLAS you cannot have CPU throttling enabled:
"CPU Throttling apparently enabled! It appears you have cpu throttling enabled, which makes timings unreliable and an ATLAS install nonsensical. Aborting. "

Disabling throttling is just a single command (for each cpu):
cpufreq-set -g performance -c  <CPU>

Where CPU denotes the cpu index (0 through 7 in my case). If you do not have cpufreq-set, you can get it from the package cpufrequtils.

Wednesday, July 3, 2013

online UML diagrams

yuml is a website that allows you to draw UML diagrams online. You can export your diagrams to various formats, such as svg, png, json.


sample diagram generated using yuml

Sunday, June 30, 2013

Elisp Function to Add License File at Beginning of Buffer

I wrote a small function that allows for reading a file and adding it at the beginning of the buffer. This comes in handy when you need to add license terms to all your source files.
The function can be found in my .emacs on github. There is also a fake license containing just one line for trying that function.

The call syntax is
(add-license-handling license_dir license_type)

license_dir is the directory containing the license file (defaulting to ~/.emacs.d/license) and license_type is the license that you want to use stored in the file <license_dir>/<license_type>. You will also need the functions get_default_license_dir and get_default_license_type from my .emacs file to get this to work.
If you want to set different default values, add this to your .emacs:

(setq default_license_dir "~")
(setq default_license_type "FAKE")

Monday, June 10, 2013

Polymorphic Allocators and Concepts in C++14

With the release of the first feature complete C++11 compiler gcc 4.8.1, you might consider taking a peak at the upcoming standard C++14.
Two - in my opionion - very interesting aspects are:

  1. Polymorphic Allocators - The object type should be independent of the container. This is especially important when you consider two containers whose data have been allocated with different allocators. In previous standards they are incompatible, but with C++14 they will not depend on the allocator anymore.
  2. Concepts are finally introduced in C++. Concepts are very helpful for template programming and restricting the type of the template parameters. This will make interfaces much clearer and also reduce cryptic template error messages, very helpful both for developers and users. Examples for concepts are Iterators, Containers, Numerical, etc.
Those are only two features of many to come in C++14. If you want to check out more propositions and ideas, there is a blog that dedicated four rather long posts on papers regarding C++14:
1 2 3 4

Sunday, June 9, 2013

Improving an Object Detector and Extracting Regions using Superpixels (CVPR 2013)

As usual there will be shortpapers in our journal club on Thursday. The one I picked titled "Improving an Object Detector and Extracting Regions using Superpixels" is from the upcoming CVPR and the authors are Guang Shu, Afshin Dehghan, Mubarak Shah from the Computer Vision Lab at the University of Central Florida. A pdf can be obtained here.
Their goal is to improve offline-trained object detectors such as Deformable Parts Model (DPM), that are trained generally on training data that do not neccessarily represent future test data. Variant illuminations, background and camera viewpoints will degrade detector performance. The authors' approach can be subsumed in four steps:

Initial Detection

Using a DPM detector with a low threshold \(t_d\) (design parameter) they obtain a large number of true detections and also many false alarms. Given the detector's confidence scores they classify each target positive or hard. Negative examples are obtained from background (without overlap).

Superpixels and Appearance Method

Using SLIC Superpixels each target is segmented into a given number of superpixels \(N_{sp}\)(design parameter, chosen such that each superpixel is roughly uniform in color and preserves object boundaries). Each superpixel is described by a five-dimensional feature vector containg the average CIELAB colorspace value and the average location of all contained pixels.
Using K-Means an \(M\)-word (design parameter) vocabulary is created and superpixels are aggregated into an \(M\)-bin L2-normalized histogram for each target (representation in a Bag-of-Word (BoW)-fashion).

Classification

A support vector machine (SVM) is trained for classification of hard examples, based on positive and negative examples. Hard examples with high scores will get the label positive, low scores will be negative. The SVM is retrained until all example labels stay unchanged.

Region Extraction

To get en estimate of the actual shape of the target rather than a bounding box a confidence map for each superpixel belonging to the target is calculated. First all superpixels of the negative samples are clustered into \(M_n\) (design parameter) clusters using CIELAB color features. For every superpixel of a positive example the similarity to each of the negative cluster centers is measured by
\[ W_{i,j} = exp(||Sp(i) - clst(j)||\times prior(j))\]
where \(W_{i,j}\) is the respective entry in the similarity matrix, \(Sp(i)\) is the i-th superpixel of a positive example, \(clst(j)\) is the j-th negative cluster center, \(prior(j)\) is the prior probability that a cluster belongs to the background, defined by the number of superpixels in that cluster.
The similarity matrix can be used to calculated the confidence \(Q_i\) of superpixel i belonging to the target
\[Q(i) = 1 - max_jW_{i,j}\]
Using this confidence map to form unary potentials \(\Psi(c_i|s_i)\) and pairwise edge potentials (to account for smoothness) \(\Phi(c_i,c_j|s_i,s_j)\), the energy in the sense of a Conditional Random Field (CRF) needs to be minimized, to achieve the most probable solution.
\[E=\sum_{s_i\in Sp}\Psi(c_i|s_i)+\omega\sum_{s_i,s_j\in Edge}\Phi(c_i, c_j|s_i, s_j)\]
\(\Phi\) is specified in the paper. \(c_i\) is the label for each superpixel \(s_i\). The weight between unary and 
binary terms \(\omega\) is another design parameter.

Experiments

The proposed method is compared to the original DPM approach and outperforms it on all datasets. The used values of the design parameters are specified (except for \(\omega\), but the authors do not state how they obtained them.
\[t_d = -2, N_{sp} = 100, M = 400, M_n = 200, \omega=?\]
It would be very interesting to know how problem specific or general those parameters are.

Conclusion

The paper is quite straight forward, well written and easy to understand. Few typos and misaligned images indicate that the paper's been finished just before the deadline.
When I first read the title and abstract, I was hoping for a method that did not need segmentation candidates and would not introduce many design parameters. Both assumptions were wrong (first segmentation using DPM, five design parameters), but the approach might still be interesting to the cell tracking project I am working on.

Saturday, June 8, 2013

img2term v0.6 - create awesome text output from image input

This is the day of the first release of img2term 0.6. It contains a lib for image to ascii/color escape sequences conversion upon which a command line program is based. Requirements so far are  vigra and boost::program options. The current version lacks unit tests and might need some improvement on color matching, which uses predefined terminal colors from konsole. An adaptive approach would make the output much nicer for any other terminal as the colors might vary.

I am open to new ideas, but please take notice that this is a one-man project done in free time, effort strongly depending on motivation and other occupation. Even if I really like your idea, I cannot guarantee it will be included within a day or months.

Future work

  • adaptive terminal color matching (no predefined terminal colors)
  • more functinality
  • better documentation, if neccessary
  • unit tests
  • VERY MAYBE video support

For a first start you should run img2term --help.
To give you an impression what it looks like (using konsole):



Kudos who knows why the current version is 0.6. Also kudos to those who have seen this awesome movie.

You can obtain version 0.6 on my github. For a more up-to-date version checkout the master branch.

Project Euler Problem 32

After quite a long while I did another Project Euler Problem: 32 - Pandigital products.
Quoting projecteuler:


We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39  186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.

The problem is quite straight forward: For all permutations of 123456789 check if you can form a pandigital product. If so, add the product to a unique set. The first five digits of each permutation are reserved to form the two factors, the last four for the resulting product.
The STL offers all the neccessary tools: std::next_permutation and std::set. Obviously, the implementation did not aim for good design.


bool check_product(int x1, int x2, int res) {
  return (x1*x2) == res;
}

template <typename t>
int get_int_from_array(T* begin, T* end) {
  --end;
  --begin;
  int res = 0;
  for (int n = 1; end != begin; --end, n *= 10) {
    res += n*(*end);
  }
  return res;
}


void get_set_of_pandigital_products(int* begin, int* end, std::set<int>& prods) {
  int n_digits = end-begin;
  int n_max = 5;
  int x1, x2, res;
  do {
    for (int i = 0; i < n_max-1; ++ i) {
      x1 = get_int_from_array(begin, begin+i);
      x2 = get_int_from_array(begin+i, begin+n_max);
      res = get_int_from_array(begin+n_max, begin+n_digits);
      if (check_product(x1, x2, res)) {
        prods.insert(res);
      }
    }
  } while (std::next_permutation(begin, end));
}

As usual, the code can be found on github.

Bayesian Reasoning and Machine Learning

If you are interested in Machine Learning and are looking for literature, I do recommend having a look at "Bayesian Reasoning and Machine Learning" by David Barber. You can order a hardcover version from a vendor of your choice or get a free copy online at the book's website. This also includes a Machine Learning toolbox for Matlab.

Sunday, June 2, 2013

How to specify filepaths when using latex \include or \input

Just as a reminder for myself:

  • \include cannot be nested. Use \input in child documents!
  • Always specify paths relative to the root document, not relative to the child document you are using \input from! 

Thursday, May 30, 2013

unused parameters in function

When you have an interface with an abstract base class Base and several classes that have derived from it. For a while this setup works out well, but at some point you have another class that inherits from Base and also has its definitions for the virtual functions. For one of the virtual functions you do not need all of the function arguments. This will cause a compiler warning in case you compile with gcc
and set the flags "-Wall -Wextra".

class Base {
public:
  virtual bool some_func(bool param) = 0;
};

class DerivedClass1 : public Base {
public:
  virtual bool some_func(bool param) {return param;}
};

class DerivedClass2 : public Base {
public:
  virtual bool some_func(bool param) {return true;}
};


It is obvious that you want to get rid of all compiler warnings. One possible solution is to make a void cast on param (taken from stackoverflow):

class DerivedClass2 : public Base {
public:
  virtual bool some_func(bool param) {(void)param; return true;}
};


Another solution that is - in my opinion - more elegant, is to just specifiy the parameter type without giving a variable name for the functions that do not use that parameter (also from stackoverflow):

class DerivedClass2 : public Base {
public:
  virtual bool some_func(bool /*param*/) {return true;}
};

Saturday, May 11, 2013

bash welcome message

Hi there,

I haven't had a blog post in quite a while due to being busy.
Last night I did the least relevant to this blog/machine learning, yet probably most awesome bit of python/shell scripting.
Basically I wanted my welcome message to be an ASCII art of an Arnie movie screenshot. However, I was very disappointed with most results of the online convertes and the lack of color made it look really bad. http://www.text-image.com/convert/ gave really good results for to html conversion. I took the source code and made a python script that parses the html string to replace the relevant color- and linebreak information with appropriate bash escape characters.
The results are really cool and now I have a welcome screen chosen randomly from those (so far only) 3 "pictures":




Useful links:
http://www.text-image.com/ (image2ascii)
http://www.commandlinefu.com/commands/view/5879/show-numerical-values-for-each-of-the-256-colors-in-bash (show 256 colors in bash)
http://www.enigmacurry.com/2009/01/20/256-colors-on-the-linux-terminal/ (how to get a bash-to-html color table with emacs)
http://tldp.org/LDP/abs/html/colorizing.html (linux documentation on bash colors)

Those were the links that helped me make the script. It is still slow and maybe I will speed it up some day. If you want to use it, and do not want to install python-Levenshtein, just delete any import and function calling that module (it's not needed). Levenshtein is on pypi.


Saturday, February 23, 2013

Python Decorators

Just as a reminder for myself in case I ever forget how Python decorators work: This blog post gives an understandable and also concise introduction to decorators. It is very clear in describing how they work and what they are useful for. So if you have not used decorators so far, this might be a trigger for you to start using them.

Sunday, February 17, 2013

Estimating Pi Using Random Samples

Programming languages usually come with defined values of pi. However, if you want to estimate it yourself, there is a very simple way to do so.
The area of a circle is given by \[A_c = \pi r^2\]
The area of a square is given by \[A_s = a^2\]
Choose the circle to be the unit circle and the square to be enclosing the circle and draw random numbers that are uniformly distributed over the square. By calculating the ratio of the number n of samples within the circle and all samples N you can get an estimation for pi. a and r are chosen according to above descriptions.
\[pi = \frac{n}{N}\frac{a^2}{r^2} = \frac{n}{N}\frac{2^2}{1^2} = 4\frac{n}{N}\]
In Python numpy this can be done within a few lines of code, in fact you can even condense it to one line.
import numpy as np

def estimate_pi(N):
    rand = 2.0*np.random.rand(2, N) - 1.0
    dist = rand[0,:]*rand[0,:] + rand[1,:]*rand[1,:]
    return np.sum(dist <= 1)*4.0/N

You should choose a large N, as you will get a better and more stable estimate:

Calculating pi using 1000 random samples
pi = 3.092
derivation from numpy.pi =  0.0157858319197

Calculating pi using 100000 random samples
pi = 3.1438
derivation from numpy.pi =  0.000702620184601

Calculating pi using 10000000 random samples
pi = 3.1424128
derivation from numpy.pi =  0.000261060710487

Note: Even if you do not know how to calculate the area of a circle, you still can calculate the area of a circle with an arbitrary radius using this method and then you can figure out that the area is a quadratic function of the radius.

Saturday, February 16, 2013

Buffer Overflow Exploit

Yesterday I have been told about the buffer overflow exploit. The idea is very simple and an example can be implemented very easily. Nowadays compilers provide protection against Stack Overflows, still it is a good idea to write your programs overflow safe. The example I show here demonstrates an unsafe password authentiaction, given you disable your compiler's stack protection. Basically, you provide char arrays, that hold the user name and password, and an indicator variable for the result of user name and password comparison.
#include <iostream>
#include <cstring>
using namespace std;

int main (int argc, char** argv) {
  if (argc != 3) {
    return 1;
  }
  char user[10];
  char pass[10];
  int granted(0);
  strcpy(user, argv[1]);
  strcpy(pass, argv[2]);
  if (strcmp(user, "admin") == 0 && strcmp(pass, "pw") == 0) {
    granted = 1;
  }
  if (granted) {
    cout << "Access granted\n";
  } else {
    cout << "Access denied\n";
  }

  return 0;
}


If you are using gcc, your need to disable stack protection:

g++ -fno-stack-protector -o overflow main.cxx

If you choose your user name long enough you cause an overflow and change the value of the variable "granted". In my case the user name needs to be at least 13 characters long.

~ » ./overflow abc 123
Access denied
~ » ./overflow admin 123
Access denied
~ » ./overflow admin pw
Access granted
~ » ./overflow AAAAAAAAAAAAA AA
Access granted

If you build your program with debugging symbols, you can print the value of the variables. For the last case, you will have an output like (granted != 0):
(gdb) print user
$5 = "AAAAAAAAAA"
(gdb) print pass
$6 = "AA\000\000\000\000\000\000\220\006"
(gdb) print granted
$7 = 65

This very simple way of exploiting overflows can be avoided very easily, e.g. length checks, and only works if you disable stack protection. However, it shows the very basic idea behind overflow exploitation and should convince you to write code that is overflow safe.

Sunday, February 10, 2013

i3 tiling window manager

These days it just so happened that I got to know of the tiling window manager i3. So far I had only used desktop environments like Gnome, KDE, etc and was currently quite happy with Cinnamon. Nevertheless the concept of a tiling window manager seemed quite convinced to me so I gave it a shot. My impression is that it is very intuitive to use. It has a good multi-screen support and can be configured via plain text in a config file, which makes modification quite easy. It is very helpful for working with an editor when at the same time you want to have a shell and a webbrowser to be visible and accessible, so I do recommend it for any programmer.
Depending on your OS you might even have a version in your repos. Unfortunately, the version I found in the Linux Mint 12 repos is quite old. With Ubuntu 12.04 you will have access to a newer version.
If you want to check it out yourself, go to http://i3wm.org/ or just install it from your repos.

Update: I added a screenshot (version 3.e-bf3 (2011-05-08)) with emacs, shell and chrome.


Saturday, January 5, 2013

boost python

Boost Python is a very helpful tool if you want to access fast C++ code in Python. For the longest time I have avoided starting to use it, because it seemed rather confusing to me. Now I had a look at a Hello World! example and it doesn't seem that hard to me anymore (of course, complexity comes with more advanced modules).

Here is the example program:
#include <iostream>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
void helloWorld() {
  std::cout << "Hello World!\n";
}

int add(int a, int b) {
  return a + b;
}

BOOST_PYTHON_MODULE(libhello) {
  using namespace boost::python;
  def("hello", helloWorld);
  def("add", add);
}

To compile this into a shared library, first you need to compile the object file and then make a shared object out of it:


g++ -I/usr/include/python2.7 -fPIC -c -o hello.o pythonWorld.cpp
g++ -fPIC -shared -Wl,-soname,"libhello.so" -o libhello.so hello.o -lboost_python

-Wl: Pass option as an option to the GNU linker. If option contains commas, it is split into multiple options at the commas (taken from http://tigcc.ticalc.org/doc/comopts.html).
Now you can import the module libhello in python and call its functions (given it is in a place where python can find it).
This was my first very simple program to get a touch on boost python. If there are mistakes in what I did that just did not have any effect because of simplicity and might show up in more complex programs, I will be very thankful if you point it out.

Thursday, January 3, 2013

Raspberry Pi cross-compiler

If you have a raspberry pi, you might want to build your own cross-compiler, because compiling on the pi is not very fast and if you have a template heavy library, compiling might exceed the pi's memory capacities. As that happened to me, I decided to build a toolchain using crosstools-ng on linux mint 12.
I stuck to these instructions that I found on google. However, whatever combination of gcc, target linux kernel and binutils version I chose, building the chain failed when building binutils.
I tried to build binutils on my and even then it failed. So I got rather frustrated, but after some search on the web, I came across a solution. It's as simple as that:
If your C_INCLUDE_PATH ends with a trailing colon, just remove that colon. After doing that I did not have any trouble compiling binutils, both on my own as well as part of the toolchain.

More detailed instructinos can be found on this blog.
I tested the toolchain and I was able to compile Hello World for my raspberry pi. So now is the time to have a look at more sophisticated stuff.