Disclaimer: This is a personal web page. Contents written here do not represent the position of my employer.

Monday, March 24, 2008

 

Unmanaged documentation hard to manage

I'm not supposed to deal much with low level technologies (unmanaged code, C language...), but in order to test things from the beginning to allow myself understand things better, I'm dealing with Atk for later translating code to C#+Atk#.

One of the things I hate more is not having the excellent refactoring options that the modern IDE's nowadays can provide. For example, how do I know where is some element defined (in my code? in a reference? in which reference?)? Sometimes I find myself copy-pasting a function into another empty test project and start adding references to it until it compiles. Someone would say: hey but there's a lot of documentation out there! Really? Take this example:

Function: g_type_class_ref
- It smells like a Glib/Gobject function.
- Surprisingly, calling it in a test project that has a reference to glib doesn't work.
- More surprisingly, calling it in a test project that has a reference to glib and atk works.
- Mmmm, but it doesn't smell like an ATK component, right? Maybe atk ref already depends on the lib I'm looking for...
- Let's google it...
- WTF! the majority of links provided are forums, not docs.
- Finally got one from the LinuxFoundation, which tells me something about a libgobject-2.0 thingy... but that lib is not in my system.
- Anyway, the page redirects me to the "Gobject 2.6.2 Reference Manual"...
- But! it's a broken link which ends on main gtk.org doc page.
- Well, then, let's look for "site:gtk.org g_type_class_ref"... No results!

Ok ok, this is not C language fault, but how do you guys get to know these type of things? I hope you don't download all the source code of all these libs and grep for the word you're looking for... :D

Please make me feel dumb if you want to reply, and I will learn one more interesting thing today :)

In managed code with an IDE, you just have to right-click on the method and select "Go to definition" and if the method is found in a binary reference, there are different behaviours depending on the IDE you use, if you use VS2005 or later, you get an Object Browser that shows you the API of the library, and with MonoDevelop it tries to use the debugging symbols for showing the source code or otherwise it shows a minibug.

SOLUTION of the QUIZ: I had to look for the library 'gobject-2.0', not libgobject-2.0. Of course, Mike Gorse was the unmanaged expert that made me feel dumb! :D

SOLUTION to avoid the QUIZ to other people in the future: bug 369927. Mmmm, it has been closed as WONTFIX, maybe the unmanaged side of things should not get easier :)

Another mini-quiz that I solved also recently comes from the managed world. Do you know how static constructors work? They get called automatically whenever the code flow comes in the type where they lay. Example:


public static class MainClass
{
  public static void Main(string[] args)
  {
    Console.WriteLine("begin");
    new StaticCtorTest(1);
    new StaticCtorTest(2);
    Console.WriteLine("end");
  }
}

public class StaticCtorTest
{
  public StaticCtorTest(int initValue)
  {
    Console.WriteLine("Normal ctor");
    this.initValue = initValue;
  }

  static StaticCtorTest()
  {
    Console.WriteLine("Static ctor");
  }

  private int initValue;
}


What's the output of this test? This:


begin
Static ctor
Normal ctor
Normal ctor
end


Now, what happens if we drop the custom constructor? We can still create objects from our class, but using the implicit empty constructor:


public static class MainClass
{
  public static void Main(string[] args)
  {
    Console.WriteLine("begin");
    new StaticCtorTest();
    new StaticCtorTest();
    Console.WriteLine("end");
  }
}

public class StaticCtorTest
{
  static StaticCtorTest()
  {
    Console.WriteLine("Static ctor");
  }

  private int initValue;
}


Output:


begin
Static ctor
end


This constructor can only be called when no other constructors have been defined. Example: the following code will give a compiler error:


public static class MainClass
{
  public static void Main(string[] args)
  {
    Console.WriteLine("begin");
    new StaticCtorTest(); //The type `StaticCtorTest' does not contain a constructor that takes `0' arguments(CS1729)
    Console.WriteLine("end");
  }
}

public class StaticCtorTest
{
  public StaticCtorTest(int initValue)
  {
    Console.WriteLine("Normal ctor");
    this.initValue = initValue;
  }

  static StaticCtorTest()
  {
    Console.WriteLine("Static ctor");
  }

  private int initValue;
}


Ok, but here comes the surprise. What happens if, instead of using a class, you use a struct?


public static class MainClass
{
  public static void Main(string[] args)
  {
    Console.WriteLine("begin");
    new StaticCtorTest();
    Console.WriteLine("end");
  }
}

public struct StaticCtorTest
{
  public StaticCtorTest(int initValue)
  {
    Console.WriteLine("Normal ctor");
    this.initValue = initValue;
  }

  static StaticCtorTest()
  {
    Console.WriteLine("Static ctor");
  }

  private int initValue;
}


What happens is that you don't receive any compiler error, and thus you may think that the static constructor is being called, however, the output:


begin
end


WTF! This stupid thing made mkestner and me feel like crazy, wondering if any JIT optimization would kill our call in the GLibSharp bindings.

Fortunately, with this little research and his help, all was solved and I can keep on concentrating on how to complete Atk# in order to get my toplevel-with-n-children sample to work, and finishing the documentation that is still in a draft stage.

Labels: , , , ,


Tuesday, March 11, 2008

 

Cambridge hacking

I'm excited to be joining Novell, to work on some .NET 3.x libraries implementation on the Mono stack.

I started to get things up and running for my new role in Calvin's A11Y Team last week in the Boston/Cambridge office, where the Microsoft+Novell interoperability lab is located, and had a great time meeting the other members of the team.

After all the planning and organizative meetings, we started on the hacking phase (look ma, no UML! ;) ), which I will be tracking in blog entries like this. So let's start:

As I will have to use Windows OS to test things from time to time, I firstly decided to set up virtualization. I decided to switch from VMWare to VirtualBox this time (given that the latter is open source) and it's happenning to be tricky because:
- Drag'n'drop doesn't work yet.
- Copy/paste doesn't work yet.
- You have to add your user to the group vboxusers.
- You have to launch the vbox kernel module (I don't know why the RPM didn't prepare this on the installation phase):
sudo /etc/init.d/vboxdrv setup
- For sharing data between the guest and the host (given that DnD doesn't work), you can share resources with this command:
VBoxManage sharedfolder add Vista11y -name VmShare -hostpath /home/knocte/Desktop/VmShare
But trying to access it via the path \\vboxsvr\VmShare wasn't working! I wondered if it was related to the network interfaces so I looked at it and:
- Network interface was not working in the first place (NAT type). I then added a new network interface (internal type) and Vista recognized it but couldn't install the drivers itself.
- It seems I can find the drivers on some place on the internet, but what's first? the egg or the hen? Because I need to pass those files to the OS guest... oh dear, it seems that I can convert a ZIP file to an ISO file but... this is becoming...
- Let's do this stuff later... maybe it's worth reconsidering Qemu again.

I've also studied the UIA API:

- http://en.wikipedia.org/wiki/Microsoft_UI_Automation
- http://msdn2.microsoft.com/en-us/library/ms747327(printer).aspx
- http://msdn2.microsoft.com/en-us/library/ms788733(printer).aspx
- http://accessinteropalliance.org/docs/Introducing_IAccessibleEx.doc
- http://download.microsoft.com/download/5/e/1/5e168e97-91dd-4ca3-ac7e-2131aec8cd1b/Overview_UIA.pdf

And Gnome A11Y:

- http://library.gnome.org/users/gnome-access-guide/2.20/
- http://live.gnome.org/Accessibility/Developers
- http://live.gnome.org/Accessibility/GetInvolved
- http://live.gnome.org/GAP/AtkGuide

Things that surprised me?

a) Neither GAIL (Gnome Accessibility Implementation Library) nor ATK (Accessibility ToolKit) where named here: http://www.gnome.org/projects/ . But suddendly discovered that:
b) GAIL is now part of Gtk+ (which could explain statement [a]) and ATK is toolkit independent, however:
c) GAIL still resides in its separate SVN path (which contradicts statement [b1])
d) Suddendly wondered about ATK+KDE (given the independence mentioned in statement [b2]) and came out with this: http://accessibility.kde.org/developer/atk.php), however:
e) ATK is GObject based (which makes [b2] difficult)
f) ATK seems to be considered a part of GTK+ (which contradicts [b2]), as said here: http://live.gnome.org/GAP/AtkGuide

Thus, this set of statements surrounds a big WTF.

I installed also some tools that are going to be needed for my work:
- Orca (already installed).
- LSR (didn't found any RPM package named this way, so I downloaded from SVN), which stands for Linux Screen Reader.
- Accerciser (didn't find a package in normal repositories, but found one OpenSUSE extra repository that contained it, thanks OBS community!). I could say this application is the analogy to DOM Inspector in the Mozilla environment, but oriented to accessibility. Surprisingly you can discover that still many native Gnome applications are not accessible when running it (like NetworkManager, the new OpenSUSE updater, or Accerciser itself; or maybe the latter was disabled by default in order to not cause strange recursive behaviours...). You can read more about it in this LinuxJournal article or in its Gnome page.

I'm still in the HelloWorld hunting phase, dealing with Atk# and stuff related. On the way, I've been using MonoDevelop a bit and just filed 5 bugs:
- Wrong location of caret in the new managed editor
- Special output from mcs not parsed correctly.
- References dialog on a C project should not show managed libs
- Protected constructor is shown on autocompletion list
- Issues with paths in a C project

(Don't get me wrong, MonoDevelop team is doing an unbeatable work, but I usually find cosmetic errors and cannot avoid saving them in Bugzilla to enable them to polish it more and more.)

Better than start coding blindly I'm still finding examples on which I can base my first steps. For example:
- the file ea-combo-button.c file from Evolution, mentioned on a11y-dev mailing list.
- an unfinished patch made by my teammate Mike Gorse, that implements Atk accessibility on some Abiword bits (hosted on Abiwords Bugzilla).
- the Mozilla module Accessible where resides either MSAA and ATK interface layers (thanks Calvin for the guidance).
- GAIL source code that I just mentioned.


TODOLIST:
- Play more with Accerciser
- Play more with ORCA
- Finish reading this huge doc about GAIL and ATK.
- After finishing getting some ATK examples running, convert them to manage code using Atk# (BTW thanks mkestner for all the help I'm getting from you to start ).
- Read WindowCatcher source code (thanks for the link Calvin) in order to get some UIA examples running.

Non-hacking TODOLIST:
- Figure out how to change my Bugzilla's account email (already done it, but I keep getting emails to my old account).
- Get a new keyboard from my laptop: I don't want to loose my beloved Spanish keys :)

Another TODOLIST that is not related to a11y but is not non-hacking either is:
- Figure out why the hell OpenSUSE 10.3 won't wake up after hibernating in my new T61P (I guess it's related with the NVidia proprietary drivers... :( ). But it seems I'm not the only one.
- Figure out how to make the fingerprint reader work with OpenSUSE (anyone with a driver out there??).

But the one I wish more is to pass this first phase (in which you seem to test and read many things but don't get any useful code at all) as quickly as I can, in order to feel more productive.

UPDATE 11-MAR-2008: This clarifies part (c) of my WTF.

UPDATE 06-APR-2008: It turns out that GuestAdditions is not an addon for your VirtualBox software (that's what I understood when I saw an RPM on my OpenSUSE that had this name), but a software that you have to install on the Operating System you're emulating with VirtualBox. Now the clipboard is working, but not the DragNDrop or the network (although I found the driver and installed it, it seems that it can't contact the router or the DHCP server).

UPDATE 07-APR-2008: Installing again the guest OS in a new VM, install the Guest additions as the very first step, and then configuring the network connection with the driver provided in the GuestAdditions ISO image (letting the default settings for Networks: just one NAT-based), fixed all the problems! (The only feature I miss is DragNDrop.)

UPDATE 14-APR-2008: Finally fixed the SharedFolders issue! You have to do this (apart from adding the shared folder with the VBox command line or GUI):

- Share the folder on the host via SMB (Yast -> Network Services -> Samba Server => enable user shares; reboot; right-click on a folder -> Sharing options).
- Install the *last version of GuestAdditions* (the one that comes with your version of VirtualBox; beware: reinstall it when you upgrade your VirtualBox). Install it via menu Devices -> Install Guest Additions... in your virtual machine window. Beware: guest additions neads a clean restart, if you reboot it and get an error on boot, you will need to reinstall it.
- In the virtual machine window, go to menu Devices -> Shared Folders and set up the same folder you just shared in SMB.
- Disable UAC in VISTA through msconfig.
- Not try to explore \\vboxsvr\ or something like that, because name resolution doesn't work. This only works through the virtual drive mapping opening a command line (Start Menu > All Programs > Accessories > Right click on Command-Prompt, and run it as an administrator) : net use x: \\vboxsvr\vmshare (it's not case sensitive, but spell it correctly! it's vboxsvr, not vboxsrv).

For the record, I'm not SURE if all of these three steps are required (maybe the key is just one of them) because I have just tried to disable Samba sharing and it seems to be working too (maybe it will no longer work when I restart the session??? I hate being a sysadmin, this should be made easier...). And it seems that the UAC stuff is only needed if you don't launch the command-prompt as and admin (I don't want to be sure about this, I don't want to test it, I don't want to loose more time on this).

Labels: , , , ,


Sunday, March 02, 2008

 

La falacia del voto útil

Lo que empezó como una actualización sobre mi entrada "Quejándote mejoras el mundo", en la que quería yo quejarme también de la ley electoral que regulariza la distribución de escaños en el sistema electoral español (y el cual tiene implicaciones muy graves, como que beneficia a los partidos mayoritarios y a los nacionalismos territoriales), acabará siendo esta entrada en la que hablaré de lo que los partidos mayoritarios (que hacen gala del triste bipartidismo que existe en nuestro país) hacen al tergiversar el concepto del voto útil.

Para empezar, me referiré a un buen artículo en el que se denuncia el problema que se da como consecuencia de aplicar el sistema D'Hondt: "Lo que vale tu voto", en el que explica cómo nuestro voto es más valioso en función del partido al que votes (pero no por ser un partido concreto, sino dependiendo de su resultado global electoral).

Este mencionado artículo tiende a ser engañoso, aunque no dice ninguna falsedad, ¿por qué? Porque el hecho de que un voto de IU valga cuatro veces menos que uno del PSOE no es algo "siempre verdad", sino sólo verdad para la distribución de votos resultante de las elecciones pasadas. ¿Cómo puedo demostrar esto? Pues simplemente imagínese que todos los votantes de IU hubieran votado al PSOE, ¿tendría el congreso más diputados de lo habitual como consecuencia de esto? NO. Por lo tanto, el hecho de que, de forma resultante global tras las elecciones, un voto de un partido valga más que otro, es consecuencia únicamente de que, por casualidad (o por cualquier otra razón) las personas que han votado más al partido menos favorecido han estado en regiones donde la distribución de población es mayor que en otras (ya que, como bien se explica en este otro artículo, hay diputados con mayor representación poblacional que otros, como consecuencia de que se intenta dar igual representatividad a una región que a otra independientemente de su número de habitantes). Por lo tanto, y esto lo digo precisamente para sacarle de su error a mucha gente, si votas a PSOE en lugar de IU (por poner un ejemplo de dos partidos) no estás optando por el voto útil. El voto útil es una falacia.

El argumento del voto útil sólo se puede sustentar por dos situaciones: o bien cuando un partido es tan minoritario que no llega ni siquiera a 1 escaño (y por tanto su electorado se reparte entre los mayoritarios), cosa que no ocurre con IU, o bien solamente para el número de votos sobrantes tras hacer la división por escaños (cantidad que puede ser despreciable; y además esto le ocurre a cualquier partido; sólo que los mayoritarios lo recuperan en mayor o menor medida, COSA QUE ES LA QUE TENDRÍA QUE CAMBIAR).

Además, que a causa del falso argumento del voto útil la gente opte por una opción política mayoritaria (por ejemplo votar al PSOE en lugar de IU) puede incluso tener consecuencias aún más graves y que el elector no pretendía, por ejemplo:

MADRID: Elige 35 diputados, 1 más que en 2000
Participación: 72,1% (+ 6,8). Votaron 407.581 personas más
El Partido Popular perdió 49.195 votos, el Partido Socialista ganó 521.464 votos e Izquierda Unida trasvasó 57.071 votos, previsiblemente en favor del PSOE

¿Cuántos votos le faltaron a Izquierda Unida para no perder su escaño?
Como el último diputado se atribuyó al PP, necesitaba conseguir (92.743-75.036)*3 = 53.121 votos más. Si los restamos a los del PSOE, tendremos:
Si IU hubiera trasvasado 3.949 votos respecto al año 2000, el PP habría perdido 3 escaños, el PSOE habría ganado 4, e IU conservaría el mismo número de escaños que entonces.

Conclusión: El llamado voto útil benefició a la derecha regalándole un escaño de Izquierda Unida


No sólo pueden ocurrir consecuencias indeseables, sino que el cambio de voto sólo sirva para cambiar un escaño (y por tanto el concepto de voto útil en este caso se erige sólo para robar votos). Ejemplo:

MÁLAGA
Elige 10 diputados
Participación: 65% (+ 6,9). Votaron 88.897 personas más
El Partido Popular ganó 15.433 votos, el Partido Socialista ganó 85.529 votos e Izquierda Unida trasvasó 5.541 votos, previsiblemente en favor del PSOE

¿Cuántos votos le faltaron a Izquierda Unida para no perder su escaño?
Como el último diputado se atribuyó al PSOE, necesitaba conseguir (61.293-47.182)*1 = 14.111 votos más. Si los restamos a los del PSOE, tendremos:
Si IU hubiera ganado 8.570 votos respecto al año 2000, el PP seguiría perdiendo 1 escaño a favor del PSOE, e IU conservaría el mismo número de escaños que entonces.

Conclusión: El llamado voto útil debilitó la opción a la izquierda del PSOE capaz de condicionar su política en sentido social.



Estos últimos dos estudios hipotéticos sobre las elecciones de 2004 han sido extraídos de una presentación elaborada y disponible por el nuevo sitio web de IU http://www.iuexiste.es/.

Actualizacion 16/MAR/2008: No dejeis de apuntaros a esta interesante iniciativa.

Actualizacion 23/ABR/2008: Interesante este grafico que muestra lo que seria el congreso de tener un sistema electoral proporcional. Ademas de la que mencione en la actualizacion anterior, tambien hay otra iniciativa de IU (pobres, habria que prestarles un buen disenyador experto en usabilidad, porque el formulario no se ve el boton de Enviar y hay que pulsar en las barras de desplazamiento para descubrirlo).

Labels: ,


This page is powered by Blogger. Isn't yours?

Categories

RSS of the category Gnome
RSS of the category Mono
RSS of the category C#
RSS of the category Programming
RSS of the category Mozilla
RSS of the category Web Development
RSS of the category Security
RSS of the category Open Source
RSS of the category Engineering
RSS of the category Misc
RSS of the category Politics

Contact with me:
aaragonesNOSPAMes@gnNOSPAMome.org

Archive
My Photo
Name:
Location: London, United Kingdom
Follow me on Twitter