Archive for July, 2006

Dynamic file read with Perl

GNU/Linux command-line users, programmers and hackers worldwide have probably come to know and love the wonderful tail shell command, together with cat, head, grep, awk and sed, easily one of the single most usefull commands.

A killer feature of tail is the -f (--follow) argument, which outputs the last lines of a file and then keeps waiting for new lines that might keep appearing in the file, and show them on the screen when they do. This is invaluable to keep track of, e.g., logfiles where new entries are being added all the time, and one does not want to be doing a tail by hand.

Since I am a great fan of Perl, and use its scripts for anything short of cooking dinner (but wait…), I have found myself in situations where I had to tail the last lines of a file. This can be done in several ways:

system "tail $file";

or

my $str = `tail $file`;
print $str;

or with a open() statement, then reading the whole file (or a part), and printing it. The first example with system is the most “direct” one, but reading the file (or a part) into a variable is very handy for doing with it all the nifty things Perl does so well to text strings (substituting, deleting, including, reordering, comparing…).

However, when tail -f was needed (i.e., keep on tracking the file and operate on the output as it appears), I kept using system calls, and all the formatting had to be done in the shell spawned by the system call, not by Perl. This was sad.

So, I was so happy when I discovered a simple trick to make open() read dynamically. There are better ways of doing it, more efficiently and correctly, but this one works, and is quite simple. If efficience is vital for you, this is not probably the place to learn about it. Actually, if you look for efficiency, you shouldn’t be using Perl at all :^)

Example of Perl code that reads dynamically a file “$in“:

open(INFILE,"tail -0f $in |") || die "Failed!\n";
while(my $line = <INFILE>)
{ 
  do whatever to $line;
};
close(INFILE)

Update: Explanation to the code above:

The open() call pipes the output of the tail command (notice the -f flag. Do a man tail to know more) to the file tag “INFILE”. The “||” sign is an [[logical disjunction|OR]], and means “do the thing on my right side if the thing on my left didn’t end successfully (but ONLY in that case!)”.

Next, we perform a while loop over the lines in the pipe. The “<INLINE>” construct extracts elements in INLINE, treating it as an array. As you can see, these elements are assigned to a new variable $line, and the loop continues while $line has some non-false value, i.e. while there are lines in INFILE.

The paragraph inside the curled keys is [[pseudocode]], obviously; you put there your code. And, for tidiness, once we exit the loop, and INFILE is exhausted of lines, we close it.

Comments (4)

Lord of War

They say, “Evil prevails when good men fail to act.” What they ought to say is, “Evil prevails.”

Yesterday I watched Lord of War… and what a movie it is!

I was a little worried that this could be one of Cage‘s bad actings, because I have a kind of love-hate relationship with this guy. I like most of his characters, but some of them are not well played, kind of not very believable.

However, in this movie Cage acts quite well, as do all other actors and actresses. The movie is very well made, with a photography, and specially a soundtrack, that helps telling the story quite beautifully.

However, the main point of the film is its truthfull, even cruel, portrayal of not only the weapon smuggling, but also the corruption and complicity of the “respectable” governments, and casts a dark shadow over the humanity as a whole, I believe. All that is accomplished through the speech of the main character, Yuri Orlov (Cage), a Ucranian immigrant in the USA who becomes the world’s biggers arm trafficker. Orlov tells us everything about his life as a smuggler, his moral degradation, his perception of the world, how the whole arm business works…

This movie is a definitive must-see, if you want to open your eyes to some sad truths. If you don’t, just go watch Superman and enjoy the good white American boy saving the world, the democracy, the right to bear arms, the land of the free, and the home of the brave.

Comments

What I want in a Desktop Environment

Probably just a reminder to myself (things to test that a DE or WM I consider using has).

In no particular order:

Panel

I want the posibility to have a panel that looks like Engage, or the modubar desklet of adesklets.

All of them are, yes, clons of the Mac “Dock”.

Volume control

Yes sounds stupid, but I want something like the convenient applet in the Xfce panel, which turns volume up and down when scrolling the mouse wheel over it.

There are workarounds, like having a mixer (e.g. kmix) icon in the system tray, which fulfill the same task (you can hover and scroll), or configuring a keybinding for it.

Maybe both, specially the latter, are even better than what I originally wanted, so… nevermind.

Alt+Tab cycling for ALL windows

I have tried Enlightenment DR16, and the default is to cycle only raised windows (that is, the minimized ones don’t appear in the cycle). How stupid is that? And I am sad to say that I haven’t been able to change this default behavior. I have given Enlightenment DR17 a try, and it does cycle through all windows…

Iconbox with all windows

I absolutely love the Xfce iconbox, which is a replacement for a “normal” taskbar, i.e., a place where iconified windows “go”. The only thing I think is less than perfect is its looks. The Enlightenment iconbox looks better, specially since you can make it 100% invisible, so that only the icons are visible.

Problem with Enlightenment iconbox: only minimized windows appear there. Again (second time with a window issue in E.), how silly is that? In Xfce you can configure the iconbox to show all windows, or just minimized ones. Having all windows appear in the iconbox is very handy. When you minimize a window, it goes to the iconbox. You can then maximize it clicking in its iconbox icon. Now, without moving the mouse, you can change your mind and minimize it back, clicking the icon again. But in E. you can’t, because the icon is no more there!

Themeability

I like some Enlightenment themes but I prefer the Xfce way of having a theme for the window manager, and another one for the “general look and feel”. The latter includes font types and sizes, scrollbar styles, button styles and so on. In E., it’s all-in-one, so one theme might have a very nice window decoration, but awful scrollbar or button style…

Easy and powerful keybindings

Most WMs have customizable keyboard shortcuts. The ones of Xfce are not espectacular, but can be accepted.

Shading with mouse

This is a very small detail, but very usefull. 99% of WMs shade the window (“roll it up”, showing only the topbar) when scrolling up with the mouse over its topbar. No need to say, scrolling down unshades the window back. In some WMs (e.g., KDE), you can even configure what you want to have done when scrolling with the mouse over the topbar of a window.

Well, there are WMs where you can not do that trick! Sad.

Comments

Blackout summary III

Today the power supply has failed again twice: first for some 15min; 10min later, for some other 5min.

Here goes the updated list of blackouts I have been able to compile, with comments if any:

  1. 2005-Dec-13
  2. 2005-Dec-21
  3. 2006-May-26 (The card-based automated access to the Faculty broke down)
  4. 2006-Jun-04
  5. 2006-Jun-08
  6. 2006-Jun-13
  7. 2006-Jun-16
  8. 2006-Jul-04 (Orpheus didn’t fall)

Summary: 8 blackouts in 204 days, or 25.5 dpb (days per blackout). 19 days since last blackout. Average dpb went down by 0.8.

First post in the series: here

Comments

last.fm

I have discovered this interesting web site called last.fm, via the amazing amaroK music player.

Basically, info about all songs I play (with amaroK, or another last.fm-enabled player) is uploaded to my last.fm profile, where anyone can see it.

If you want to find people with similar musical tastes, or find out what other groups people who likes a group listens to, or how many people listen to some song or group… all that can be found at last.fm.

And if you are just curious what music I listen to, just follow this link.

Comments

Los caraduras de la SGAE

Leo en el Diario Vasco un artículo haciéndose eco del enfrentamiento entre SGAE y usuarios de material informático (o sea, tú y yo), en relación con el famoso canon por copia privada que se aplica a medios como CDs y DVDs.

El preclaro Farré afirma (refiriéndose a los fabricantes de soportes de almacenamiento digital), con su acostumbrada hipocresía:

Lo lógico es que compartan una mínima parte de esa ganancia con quienes crean esos contenidos […] ¿Venderían tantos soportes si no se pudieran copiar las obras?

Este es el puñetero argumento de “gracias a la música se venden más CDs vírgenes, por lo tanto los autores deben recibir una parte del pastel”. Dejemos a un lado si dar dinero a la SGAE equivale a darlo a los autores de la música, o si la SGAE realmente representa a los autores españoles (muchos de los cuales no se adhieren a ella), o en qué lugar queda la música CC… Supongamos que SGAE=música (aguantad las risas, es un suponer).

Pues bien, ese argumento seguiría siendo FALSO.

Es falso y bien falso. El mercado libre no funciona de esa manera, querido Farré.

Supongamos que yo vendo coches. Supongamos que vendo 1000 coches este año. Supongamos que el año que viene la compañía X inventa un combustible más barato. Como el combustible es más barato, la gente empieza a comprar más coches, y mis ventas suben a 2000 coches en el 2007. ¿A alguien en su sano juicio se le ocurriría pensar que la compañía X puede pedirme un “canon” por los coches que vendo, alegando que “gracias a ellos he vendido más”? Pues a nadie, claro.

Supongamos que, en vez de inventar un combustible más barato, X inventa un coche solar. La nueva competencia hace que mis coches sean impopulares, y mis ventas del 2007 bajan a 500 coches. ¿Tengo derecho a demandar a X por hacer que mis ventas bajen? Pues no, claro.

Si acciones de terceros negocios afectan favorable o desfavorablemente al mío, lo tengo que tomar como imponderables del mercado, y adaptarme al cambio sin rabietas y sin pataletas. Pero parece que la SGAE no ha entendido esto: en un mercado justo y libre, NADIE COBRA POR BENEFICIOS INDIRECTOS A TERCEROS.

Es más, tampoco es tan claro que la música beneficie la venta de soportes digitales, pero no al revés, ni en qué medida se dan estos beneficios mutuos, o en qué medida afecta la música a la venta de soportes digitales, comparada con otros factores. Legislar el cobro de un canon indiscriminado en estas circunstancias es irresponsable, y nuestros políticos deberían ser conscientes de ello.

Alguien podría alegar que en el ejemplo de coches y gasolina barata, el vendedor de gasolina también se beneficia de la venta de coches (así que el beneficio es mutuo), pero con la música “pirateada” no pasa eso: la música beneficia la venta de soportes digitales, pero no al revés. Pues bien, esto es otra mentira. Yo planteo la pregunta: ¿acaso se vendería tanta música (CDs originales) si los usuarios no tuvieran un medio barato y fiable para hacer copias? ¿Acaso la música en CDs habría ganado tanta popularidad si no pudiera uno pasarla a MP3 u OGG en su ordenador, o a un reproductor portátil? Recordemos cómo MS-DOS se hizo tan popular en su momento gracias a que se podía “piratear”. Sí, señores, sí, gracias a que eran bien sencillo de copiar.

Hay una corriente de usuarios descontentos (entre los que me encuentro), que reduce su compra de CDs por desprecio a unas discográficas mafiosas, a un canon injusto, a unos artistas mezquinos y ruines, y a “protecciones” anticopia y DRMs abusivos. Leed, por ejemplo mi carta a Bebe.

Está claro que la venta de música se ve perjudicada por esas medidas, pero cada cliente descontento que pierden por sus abusos, ellos lo atribuyen a las redes p2p y al “pirateo”. Por otro lado, cada CD que en mi grupo de investigación utilizamos para hacer una copia de seguridad, se lo apropian como si lo usáramos para grabar a Bisbal. ¡Menuda jeta!

Cada día me tienen más harto estos ladrones.

Comments

Microsoft and Creative Commons

I have come to know that Microsoft has planned to add to MS Office a plug-in for licensing the documents thus produced under one of the Creative Commons licenses (if the author so wishes, of course).

You can read about it in Slashdot, C|Net and Lawrence Lessig’s blog.

Now, a lot of people see it as something possitive (including Enrique Dans[es]), but I don’t see it completely clear. It seems to be a big boost to the popularity of CC licenses, no doubt about it.

But, is it good news to the freedom of the culture?. It would seem so, since more people will license their works under a CC (many even unwillingly, because they hit the incorrect button in their toolbar, or have the defaults of their Office wrongly configurated), but it is not. They key point is twofold:

1) What the hell is this plug-in good for? What can the author achieve with it that is not promptly achieved just adding a “This work is licensed under blah-blah-blah” manually (keyboard-lly)? It is implied that someone will write a 500-page book, but is too lazy to manually add a statement that could be inserted clicking the ultra-mega-kewl MS Offiz plug-in button…

2) What good is it to free one’s artistic (or otherwise) work under a permisive copyright, if it is burdened by a proprietary format such as those MS Office saves under?

These two facts (doesn’t benefit the author, doesn’t benefit the freedom) make it clear that (as all the steps MS takes) it mainly benefits MS. It effectively helps the author refrain from controling her work too tightly, but moves this “control” into its (MS’s) own hands. Free distribution of important, interesting, popular CC documents will make it even more important to have MS Office if these documents are DOC or similar. More so, MS could threat to cut support for the readers of such documents, increase their price, tighten the piracy controls for MS Office, and/or legally prosecute the compatible readers (OpenOffice.org)… all that supported by a more tight grip in the freedom of choice of the public.

And remember: all the aforementioned attacks to the users’ freedom can only be done from a power position… power given to them in first place by the users. Don’t fall for it!

Comments

« Previous Page « Previous Page Next entries »