Wednesday, May 21, 2014

Grep in git with emacs

I'm sure you're aware of vc-git-grep command in Emacs, but it has a downside: you must specify the file extension every time, and it's case-sensitive.
I propose you an alternative vc-git-grep2 that is case-insensitive and only requires the directory in which to start the search.

(defun vc-git-grep2 (regexp dir)
  (interactive
   (progn
     (grep-compute-defaults)
     (cond
      ((equal current-prefix-arg '(16))
       (list (read-from-minibuffer "Run: " "git grep" nil nil 'grep-history)
    nil))
      (t (let* ((regexp (grep-read-regexp))
    (dir (read-directory-name "In directory: " nil default-directory t)))
     (list regexp dir))))))
  (require 'grep)
  (when (and (stringp regexp) (> (length regexp) 0))
    (let ((command regexp))
      (if (> 4 5)
    (if (string= command "git grep")
     (setq command nil))
  (setq dir (file-name-as-directory (expand-file-name dir)))
  (setq command
     (grep-expand-template "git grep -n -i -e <R>" regexp))
  (when command
    (if (equal current-prefix-arg '(4))
     (setq command
     (read-from-minibuffer "Confirm: " command nil nil 'grep-history))
   (add-to-history 'grep-history command))))
      (when command
  (let ((default-directory dir)
     (compilation-environment '("PAGER=")))
    ;; Setting process-setup-function makes exit-message-function work
    ;; even when async processes aren't supported.
    (compilation-start command 'grep-mode))
  (if (eq next-error-last-buffer (current-buffer))
   (setq default-directory dir))))))
 
Plus I suggest you to add the following to your .emacs. Install find-file-in-git-repo and add the following: (require 'find-file-in-git-repo) (global-set-key (kbd "C-x f") 'find-file-in-git-repo) Then bind our new vc-git-grep2: (global-set-key (kbd "C-x s") 'vc-git-grep2) Finally, because some modes don't use the common C-c C-c to comment/uncomment regions: (global-set-key (kbd "C-c C-") 'comment-or-uncomment-region)

Sunday, March 23, 2014

Gtk3 hit-a-hint: mouseless navigation module

I present gtkhah, a gtk module for hit-a-hint mouseless navigation of gtk3 applications.
It's been inspired by the various hit-a-hint browser extensions.
Usage at the project homepage. Here's a quick screenshot of Gedit:


Monday, January 20, 2014

Intersection test and optimal allocation of 2D axis-aligned boxes using linear programming

Either-or trick
In this solution, we will make use of the either-or trick. The constraints in a program are all in and, but we want some of them to be in or.
Consider the following logic formula: \(a\ge b\vee c\ge d\). It can be written with the following and constraints: \[ \begin{alignedat}{2}\, & M\cdot x\; & +a\; & \ge b\\ \, & M\cdot\left(1-x\right)\; & +c\; & \ge d\\ \, & \, & x\; & \in\left\{ 0,1\right\} \end{alignedat} \] where \(M \gt 0\) is big (depending on the specific context as we'll see later).
When \(x=0\), then \(a \ge b\) must hold, while the second constraint is always satisfied. When \(x=1\), then \(c \ge d\) must hold, while the first constraint is always satisfied.
In other words, either one of the two constraint must hold for a given value of \(x\). If neither do, then the original or formula is not satisfied.

Empty intersection test
Given two AABB boxes \(i,j\) at position \(x_i,y_i\) and \(x_j,y_j\) with size \(w_i,h_i\) and \(w_j,h_j\) respectively, we want to constraint our program such that their intersection is empty.
This can be expressed with the following logic formula:
\[ \left(x_{i}\ge x_{j}+w_{j}\vee x_{j}\ge x_{i}+w_{i}\right)\vee\left(y_{i}\ge y_{j}+h_{j}\vee y_{j}\ge y_{i}+h_{i}\right) \]
We can encode the above expression with 3 either-or tricks using 3 binary variables:
\[ \begin{alignedat}{3}\; & M\cdot b_{1}\; & \, & +M\cdot b_{3} & +x_{i}\; & \ge x_{j}+w_{j}\\ \; & M\cdot\left(1-b_{1}\right)\; & \, & +M\cdot b_{3} & +x_{j}\; & \ge x_{i}+w_{i}\\ \; & M\cdot b_{2}\; & \, & +M\cdot\left(1-b_{3}\right) & +y_{i}\; & \ge y_{j}+w_{j}\\ \; & M\cdot\left(1-b_{2}\right)\; & \, & +M\cdot\left(1-b_{3}\right) & +y_{j}\; & \ge y_{i}+w_{i}\\ \, & \, & \, & \; & b_{1},b_{2},b_{3}\; & \in\left\{ 0,1\right\} \end{alignedat} \] Real problem
Given a fixed area of size \((cols)\times(rows)\) and a set of boxes with fixed width \(w_i\) for each \(i=1..n\) (where \(n\) is the number of boxes), find the optimal allocation \(x_i, y_i, h_i\) for each box \(i=1..n\) such that we cover all the area and maximize the size of the boxes fairly.
To achieve fair allocation we choose to maximize the minimum height of the boxes. For example, if we had an area of size \(5\times100\), and two boxes of width \(5\) each, we prefer them to have height \(50\) and \(50\) respectively, rather than \(1\) and \(99\).

This problem can be encoded as follows: \[ max\; minh+C\cdot{\displaystyle \sum_{i=1}^{n}h_{i}} \] \[ subject\;to: \] \begin{equation} \forall i=1..n:\; minh\leq h_{i} \end{equation}
\[ \forall i=1..n-1,\, j=i+1..n: \] \begin{equation} \begin{alignedat}{3}\; & M\cdot b_{1}^{\left(ij\right)}\; & \, & +M\cdot b_{3}^{\left(ij\right)} & +x_{i}\; & \ge x_{j}+w_{j}\\ \; & M\cdot\left(1-b_{1}^{\left(ij\right)}\right)\; & \, & +M\cdot b_{3}^{\left(ij\right)} & +x_{j}\; & \ge x_{i}+w_{i}\\ \; & M\cdot b_{2}^{\left(ij\right)}\; & \, & +M\cdot\left(1-b_{3}^{\left(ij\right)}\right) & +y_{i}\; & \ge y_{j}+w_{j}\\ \; & M\cdot\left(1-b_{2}^{\left(ij\right)}\right)\; & \, & +M\cdot\left(1-b_{3}^{\left(ij\right)}\right) & +y_{j}\; & \ge y_{i}+w_{i}\\ \, & \, & \, & \; & b_{1}^{\left(ij\right)},b_{2}^{\left(ij\right)},b_{3}^{\left(ij\right)}\; & \in\left\{ 0,1\right\} \end{alignedat} \end{equation}
\[ \forall i=1..n: \] \begin{equation} \begin{alignedat}{1}x_{i}+w_{i}\; & \le cols\\ y_{i}+h_{i}\; & \leq rows\\ 0\leq x_{i}\; & \leq cols-1\\ 0\leq y_{i}\; & \leq rows-1\\ 1\leq h_{i}\; & \leq rows \end{alignedat} \end{equation} Equation \((1)\) is used to get the minimum height of the boxes together with the objective function. Equations \((2)\) ensure that the boxes do not overlap. Equations \((3)\) ensure that the boxes don't lie outside of the allocation area.
In the objective function we also add a second component, which ensures that on equal \(minh\) we chose the allocation that fills the remaining space. This component must thus be \(< 1\) to not bias the \(minh\) component.

Now, what are the values of \(M\) and \(C\)? The constant \(M\) must be big enough to make an inequality always true, so:
\begin{gather*} \forall i,j:\; M\ge x_{j}+w_{j}-x_{i}\\ M\ge\max\left\{ x_{j}+w_{j}-x_{i}\right\} \\ M\ge\max\left\{ x_{j}+w_{j}\right\} -\min\left\{ x_{i}\right\} \\ M\ge cols \end{gather*} Since it must hold also for rows, \(M\ge\max\left\{ cols,rows\right\}\). The result is very intuitive if you look at the original inequalities. We can choose a value of \(M=cols+rows\).
The constant \(C\) instead must be such that: \begin{gather*} C\cdot{\displaystyle \sum_{i=1}^{n}h_{i}}<1\\ C\cdot n\cdot\max\left\{ h_{i}\right\} <1\\ C\cdot n\cdot rows<1\\ C<\frac{1}{n\cdot rows} \end{gather*} This result is also very intuitive. We can choose \(C=\frac{1}{2\cdot n\cdot rows}\) to avoid numerical instability.

Demonstration
I've prepared a GMPL program to allocate \(10\) boxes with width \(3,4,10,7,4,8,2,9,8,5\) in an area of \(10\,cols\times100\, rows\). GLPK does not converge, so you can limit the time to 1 second (or more) in order to get a feasible but suboptimal solution.
You can visualize the result in the screenshot below of the two solutions while running for 1 second and 5 second respectively. After 60 seconds the solution didn't improve.
Please note that there is no relationship between the colors of the two tests.

image/svg+xml 1s 5s

Relaxing the integer constraint on \(x,y,h,minh\) might also give you better solutions in less time.
You can download the gist below and run it as: glpsol --tmlim 5 -m aabb_alloc.mod:

Friday, September 06, 2013

Regex in Haskell patterns

Have you ever wanted to do case expr of regexhere -> ... ?
You can do almost that with view patterns!

{-# LANGUAGE ViewPatterns #-}

import Text.Regex.Posix

-- Helper
pat :: String -> String -> [[String]]
pat p s = s =~ p

-- Function with matching
foo :: String -> String
foo (pat "foo(bar|baz)" -> [[_,x]]) = x
foo _ = "no!"

main :: IO ()
main = do
  print $ foo "foobar"
  print $ foo "foobaz"
  print $ foo "yes?"

The above code will print bar baz no! . Have fun!

Wednesday, July 03, 2013

Found my google reader alternative: the old reader

So I'd like to share with you my google reader alternative: theoldreader.
I've tried so far yoleo, feedly, goread and diggreader. Each of them is missing the following must have things for me:
  • The "next" button. I don't like using keyboard bindings when reading feeds.
  • Search through all feeds
  • Social by sharing/liking news
  • Exporting OPML
Additionally, theoldreader has a great (disabled by default) feature: clicking on a news will scroll to it. That is very handy if you don't want to stick your mouse clicking on the next button.

The only bad point of theoldreader is that there's an import queue, I'm currently in position 1566 (1481 after about 15 minutes). Other than that, it's perfect for my needs and resembles most of google reader.

Update: the search only looks for terms into post titles, not post contents :-(

Friday, June 28, 2013

Inline commenting system for blog sites

One side of the idea:
Lately I've seen some comment systems that inline comments in the text itself, see an example here.

Other side of the idea:
I've implemented a couple of unsupervised algorithms for news text extraction from web pages in Javascript, and they work generally well. They're also capable of splitting the news text into paragraphs and avoid image captions or other unrelated text.

The idea:
Merge the two ideas, as a new commenting service (like Disqus) for blogs, in a modern and interesting way.
  1. The algorithms are capable of extracting the news text from your blog and splitting it into paragraphs.
  2. For each paragraph, add a seamless event so that when the user overs a paragraph with the mouse, a comment action button appears.
  3. When clicking the comment button a popup will appear showing a text box at the top where you can write the comment, and the list of comments at the bottom that are related to that paragraph only. (I please you, let the user order comments by date.)
  4. Optional killer feature: together with the text box, you can also choose to add two buttons: "This is true", "This is false", so that there's a kind of voting system about the truth value of that paragraph from the readers perspective.
  5. Once you send the comment, that comment is tied to that paragraph.
  6. Give the possibility to create comments the old way, in case the user does not want to strictly relate the comment to a paragraph.
  7. Give the possibility to show all the comments at the bottom of the page (button "Show all comments"). If a comment is related to a paragraph, insert an anchor to the paragraph.
Given that the blogger shouldn't add any additional HTML code for the paragraphs because of the unsupervised news extraction algorithms, the comment service API will not differ in any way than the current ones being used.

Problems of this approach:
  • There's no clear chronology for the user between comments of two different paragraphs. In my opinion, this shouldn't be a big deal, as long as comments between two paragraphs are unrelated.
  • If a paragraph is edited/deleted, what happens to the comments? One solution is to not show them in the text, but add a button "Show obsolete comments" at the buttom of the page, or rather show them unconditionally.
  • The unsupervised algorithm may fail to identify the post. In that case, the blogger may fall back to manually define the DOM element containing the article.

Wednesday, June 05, 2013

Accessing simple private fields in PHP

A way of accessing private fields in PHP is by changing the accessibility of the fields themselves with http://php.net/manual/en/reflectionproperty.setaccessible.php.
However this approach requires PHP 5.3.

For PHP < 5.3 there's another subtle way of accessing private properties:

function getPrivateProperty($fixture, $propname) {
    try {
        $arr = (array)$fixture;
    } catch (Exception $e) {
    }
    $class = get_class($fixture);
    $privname = "\0$class\0$propname";
    return $arr[$privname];
}

Usage is pretty straightforward, pass in the object and the property name as string. The property must be private and must be convertible to array.

Saturday, April 06, 2013

Build Vala applications with Shake build system

I'm going to introduce you a very nice alternative to make: the Shake build system, by setting up a builder for your Vala application project.

First of all, you need to know that Shake is a library written in Haskell, and it's meant to be a better replacement for make. Let's start by installing cabal and then shake:
apt-get install cabal-install
cabal update
cabal install shake

TL;DR; this is the final Build.hs file:
#!/usr/bin/env runhaskell
import Development.Shake
import Development.Shake.FilePath
import Development.Shake.Sys
import Control.Applicative hiding ((*>))

app = "bestValaApp"
sources = words "file1.vala file2.vala file3.vala"
packages = words "gtk+-3.0 glib-2.0 gobject-2.0"

cc = "cc"
valac = "valac"
pkgconfig = "pkg-config"

-- derived
csources = map (flip replaceExtension ".c") sources
cobjects = map (flip replaceExtension ".o") csources

main = shakeArgs shakeOptions $ do
  want [app]
  app *> \out -> do
    need cobjects
    pkgconfigflags <- pkgConfig $ ["--libs"] ++ packages
    sys cc "-fPIC -o" [out] pkgconfigflags cobjects
  cobjects **> \out -> do
    let cfile = replaceExtension out ".c"
    need [cfile]
    pkgconfigflags <- pkgConfig $ ["--cflags"] ++ packages
    sys cc "-ggdb -fPIC -c -o" [out, cfile] pkgconfigflags
  csources *>> \_ -> do
    let valapkgflags = prependEach "--pkg" packages
    need sources
    sys valac "-C -g" valapkgflags sources
    
-- utilities
prependEach x = foldr (\y a -> x:y:a) []
pkgConfig args = (words . fst) <$> (systemOutput pkgconfig args)

Just tweak app, sources and packages to match your needs, chmod +x Build.hs then run ./Build.hs .

Explanation.
The words function splits a string by spaces to get a list of strings, e.g. ["file1.vala", "file2.vala", "file3.vala"].

The csources variable maps .vala file names to .c file names. Same goes for cobjects. It's the equivalent of $(subst .vala,.c,$(SOURCES)) you'd do with make.

There it comes the main. The shakeArgs shakeOptions part will run shake with default options. Shake provides handy command line options similar to make, run ./Build.hs -h for help.

The want [app] tells shake we want to build the app object by default. That's equivalent to the usual first make rule all: $(APP).

Then we define how to build the executable app with app *> \out -> do. We tell shake the dependencies with need cobjects. This is similar to $(APP): $(COBJECTS) in make but not equivalent. In shake dependencies are not static like in many other build systems. This is one of the most interesting shake features.
The rest is quite straightforward to understand.

Then we define how to build each .o object with cobjects **> \out -> do. Here the out variable contains the actual .o required to be built, equivalent to $@ in make. Then we need [cfile], in order to simulate %.o: %.c like in make.

One more feature shake has out-of-the-box that make doesn't is how to generate more files from a single command. With make you'd use a .stamp file due to valac generating several .c files out of .vala files. Then use the .stamp as dependency.
With shake instead we consistently define how to build .c files with csources *>> \_ -> do, then shake will do the rest.

The shake project is very active. You can read this tutorial to learn Haskell basics, and the reference docs of shake. The author homepage has links to cool presentations of the shake build system.

Thursday, March 28, 2013

Switch window by name on Linux - alternative to Alt+Tab

Today I want to share a very simple script that works with most Linux window managers: switch window by name.
It works like this: you press Ctrl+Alt+M, then a dialog appears where you write part of the name of the window, and you'll get switched to the window that matches the provided name.The string your provide will match part of window names in case-insensitive mode.
That means if you have "Foo - Mozilla Firefox" and type in "fire" you'll switch to firefox.

Note: it probably doesn't work with your configuration of awesome wm due to weird focus management.

The first step is to install the necessary packages:
apt-get install xbindkeys wmctrl zenity

With wmctrl we're able to switch to a window by specifying the name, while with xbindkeys we can bind Ctrl+Alt+M to open a zenity dialog then call wmctrl with the provided window name.

The only thing you need is the following file somewhere, let's call it keys.rc:
"WINDOWID='' app=$(zenity --text "App" --title "App" --entry) && wmctrl -R $app"
  control+alt + m

Now run xbindkeys -f keys.rc and we're done! Press Ctrl+Alt+M then type in the name of the window you want to switch to.

We can also add simpler bindings like this:
"wmctrl -R Firefox"
  control+alt + f

Now pressing Ctrl+Alt+F will switch to a firefox window.

Note that if it matches more window, only one of the window will be chosen obviously. The choice depends on xbindkeys.

I'm not using Alt+Tab anymore.

Sunday, March 24, 2013

Controlling audio volume in Awesome WM

I use awesome on my eeepc because it's much space and resource saving.
There are several possibilities for controlling volume in the Awesome window manager.
Today I'd like to share my way of doing it: using amixer for controlling the volume, and naughty for notifying the user.

Start by defining the following in your rc.lua (source discussion here):
volnotify = {}
volnotify.id = nil
function volnotify:notify (msg)
    self.id = naughty.notify({ text = msg, timeout = 1, replaces_id = self.id}).id
end

We use naughty for notifying the user instead of notify-send because of the "replaces_id" feature. It's used to replace an old notification with a new one. This is useful when you keep increasing the volume so that you only get one notification instead of stacking them up.
So the purpose of this code is to keep track of the id returned by naughty on each invocation, so that we can pass it to the next invocation.

function volume(incdec)
    awful.util.spawn_with_shell ("vol=$(amixer set Master 5%" .. incdec .. "|tail -1|cut -d % -f 1|cut -d '[' -f 2) && echo \\\"volnotify:notify('Volume $vol%')\\\"|awesome-client -", false)
end

function togglemute()
    awful.util.spawn_with_shell("vol=$(amixer set Master toggle|tail -n 1|cut -d '[' -f 3|cut -d ']' -f 1) && echo \\\"volnotify:notify('Volume $vol')\\\"|awesome-client -", false)
end

The first function is used to increase or decrease the volume. It accepts an argument of value either "+" or "-", then changes the master volume accordingly and finally displays a notification with the new volume.
The second function will toggle the mute state of the volume in a similar manner.

We are going to call these two functions whenever the user hits the media keys by binding new global keys as follows:

globalkeys = awful.util.table.join (globalkeys,
    awful.key({}, "XF86AudioMute", togglemute),
    awful.key({}, "XF86AudioLowerVolume", function() volume("-") end),
    awful.key({}, "XF86AudioRaiseVolume", function() volume("+") end)
)

Restart with Mod+Ctrl+R and that's it!

Thursday, December 06, 2012

Refactory.org is down

Unfortunately many of my snippets in this blog have been written and uploaded exclusively on refactory.org . It was a free service for uploading snippets of any kind, with a friendly versioning system and other cool features.
It's now inactive since several months. I'm sorry for anybody stumbling upon any post that has code hosted at refactory.org . From now on I will try to put the code in the post itself whenever I can, or find better places to upload the code.

Thursday, November 22, 2012

Grab focus on Gtk Widget

Many times I had to give focus to a newly created Gtk widget that still had to be mapped to screen. Since widget.grab_focus() does not work if the widget is not displayed on the screen, then I always used an idle source to delay the operation.
Today I noticed that the idle may be too late: if the user is writing something, then some key strokes may be lost because the idle runs slightly after the widget has been mapped. You may think that's imperceptible to the user, but that's not true in some cases.

So I've tried connecting to the map, map-event and show signals (also "after"), without success: the handler is called slightly before the right time thus grab_focus() will not work.

Then I ended up with this working solution, that will grab the focus as soon as the widget is first drawn to the screen:

void focus_widget (Widget widget) {
  // it may be already displayed
  widget.grab_focus ();
  // grab focus right after the widget is drawn
  // for the first time
  ulong sigid = 0;
  sigid = widget.draw.connect (() => {
    widget.grab_focus ();
    widget.disconnect (sigid);
    return false;
  });
}

I still don't know exactly what's the best way to grab focus as soon as the widget can really grab it. So if you have any better idea, please let me know :-)

Sunday, November 11, 2012

Code Search is dead. Long live Code Search!

I'm bumping a breaking news from debian.net: Introducing codesearch.debian.net, a regexp code search engine

The days of google codesearch are ended since a while, but now we have an up-to-date and open source debian codesearch.


(from the about page):
It searches all the open source projects which are included in the Debian archive (the "main" distribution only, not non-free or contrib). Currently, that includes about 18000 packages with 140 GiB of source code.
The search engine itself is based on Russ Cox’ codesearch tools, meaning it uses Regular Expressions as input. Like the codesearch tools, it was implemented in Go.

The project is a thesis so the source code won't be available until January 2013, and we all hope that the project continues beyond that date.

Thursday, September 08, 2011

Vala language introduction on IRC

Hi,
I've lately held an talk on IRC about the Vala programming language for the Ubuntu App Developer Week. I've introduced the basics of the Vala language and its features.
You can read the log of the talk here.

Tuesday, August 09, 2011

Probability of a union of independent events algorithm

Lately I was looking for a copy 'n paste algorithm to calculate the probability of a union of independent events that are not mutually exclusive (aka inclusion-exclusion principle in probability). Unfortunately I couldn't find any algorithm for such a basic problem.
Therefore, I decided to write the following naive algorithm which is fast enough for my purposes (O(n2) in time and space, where n is the number of events), and share with everyone:

You can find the code snippet here, sorry for not embedding it in the blog post but blogger is really boring me with snippets having broken layout.

The idea behind the dynamic programming approach starts from this observation:

Let A, B and C be independent non mutually exclusive events. Then:

P(A or B or C) = P(A) + P(B) + P(C) - P(A)P(B) - P(A)P(C) - P(B)P(C) + P(A)P(B)P(C)

Let me simplify the expression using A instead of P(A):

P(A or B or C) = A+B+C - AB - AC - BC + ABC

Notice that AB+AC+BC = A(B+C) + BC. In general:

AB+AC+AD+...+AZ + BC+BD+....+BZ = A(B+C+D+...+Z) + B(C+D+...+Z)

ABC+...+ABZ + ACD+...+ACZ+...+AYZ + BCD+...+BYZ = A(B(C+D+...+Z)+C(D+...+Z)+...+YZ) + B(C(D+...+Z)+...+YZ)

That's exactly where we exploit the dynamic programming to avoid recalculating the same expressions twice.

Edit: My effort was totally useless given that for independent events this is equivalent to 1 - (1 - pA)(1 - pB)..., which can be calculated in linear time. I even used this formula once and forgot about it :-(

Saturday, July 23, 2011

Give my luck back, Firefox 5!

Today I've upgraded to firefox 5, special thanks to Debian developer for packaging it. So far, everything works well and better than before, except two things (one of which I managed to tweak):
  1. The tabs bar is higher than before. This means that the mouse must move more to reach them. This has been solved. Thanks for allowing me to put the tabs bar below back again.
  2. The address bar no more involves "I feel lucky" search. The feature was awesome, because I often write a partial website name and I get most of the time to the right page without actually typing the whole name. Also, since we already have a search bar on the top-right, why was this feature removed? It's kind of duplicated now.
So, dear readers, do you know of any add-on so that I can have "I feel lucky" search back, before I write one? Having it on the top-right bar is good as well.

Edit: The solution is to open about:config and set the keyword.URL value to "http://www.google.com/search?btnI=745&q=" (without quotes). Thanks to Giuseppe for the hint.

Saturday, July 09, 2011

Python/Ruby like generators in Vala

Hello,
the post below is copied straight from here.

Here I'll show a cool snippet code making use Vala async functions and iterators for emulating Python/Ruby generators. Creating a generator is as simple as extending the Generator class and implementing the generate() method.

abstract class Generator {
    private bool consumed;
    private G value;
    private SourceFunc callback;

    public Generator () {
        helper ();
    }

    private async void helper () {
        yield generate ();
        consumed = true;
    }

    protected abstract async void generate ();

    protected async void feed (G value) {
        this.value = value;
        this.callback = feed.callback;
        yield;
    }

    public bool next () {
        return !consumed;
    }

    public G get () {
        var result = value;
        callback ();
        return result;
    }

    public Generator<G> iterator () {
        return this;
    }
}

class IntGenerator : Generator<int> {
    protected override async void generate () {
        for (int i=0; i < 10; i++) {
            yield feed (i);
        }
    }
}

void main () {
    var gen = new IntGenerator ();
    foreach (var i in gen) {
        message ("%d", i);
    }
}

You can find the above code snippet here as well.

Tuesday, July 05, 2011

Why I'm still using Emacs

Hello,
I'm using emacs since a long time by now. Everytime I ask myself why I'm using it, given emacs certainly isn't the easiest environment for programming. So, I often tried to replace emacs with other IDEs or editors, using several extensions and so on, but I still miss these killer features in a single editor:
  • Pressing a key (whatever it is, TAB in emacs) correctly/smartly indent the row according to the current language.
  • Split view, horizontal and vertical
  • No horizontal scrollbar, rather wrap the text
  • Opening/closing files without either opening a dialog or using the mouse
  • Search, search and replace (also with regexp variant) without opening any dialog
  • Switching between buffers using the longest-common-subsequence matching, without using the mouse (i.e. I don't care about file tabs, but about switching among them fast)
  • Indent entire code regions
  • Vala, C, Python, Java, Shell, Autoconf/Automake, Make and Javascript support

So, I'm not using emacs because I love it, but because it's actually the only editor with the above features.

What I'm looking for? I'm looking for a new editor/IDE, less complex, easier to customize, having the above features plus smart completion and symbol browser.
Emacs can have completion and symbol browser as well, but managing those buffers such as speedbar suck a little, things get complicated to use and to customize.

If anybody knows of such an editor, please let me know :)

Thursday, June 02, 2011

Writing binary files with bash

Hello,
I'm trying to see if I'm able to write some binary file using bash. So, when writing a binary file you often want to write a number into binary format. I ended up with this simple function for writing numbers in little endian:

function num2bin() {
printf $(printf %.$(($2*2))x\\n $1|
sed 's/\([0-9a-f][0-9a-f]\)/\\x\1/g')|
awk -F '' '{ printf $4$3$2$1 }'
}


The first parameter is the number to write, the second is the number of bytes (up to 4). For example "num2bin 40 4" will output a 4-byte long string containing the number 40 in little endian.

How do we use it? I wrote an example script for creating a wav file with noise (according to wav specifications) that you can read here.

Let me know if you have a simpler version of the num2bin function.

Friday, May 27, 2011

Complete variables with cd command in bash

Hello,
lately I've been searching for a way to complete variables containing directories with the "cd" command in bash. This is very helpful if you have something like "cd $mydir/". This is not actually working in debian bash-completion.
Then I've realized that other commands such as "ls" actually expand variables. I looked for some "complete" combo used for "ls" but not for "cd" in /etc/bash_completion and I came out with the following:

complete -F _longopt -o default cd

Luckily, this is exactly the command needed to enable variable expansion with the "cd" command. Put that in your .bashrc after loading bash_completion and you're done.