Curiosities about parameters and variable declarations in Javascript

  1. <html>
  2. <body>
  3.  
  4. <script type="application/javascript;version=1.7">
  5.  
  6. function f1(parameter) {
  7.  alert(parameter);
  8. }
  9.  
  10. function f2(parameter) {
  11.  alert(parameter);
  12.  let parameter = "value";
  13. }
  14.  
  15. f1("hello");
  16. f2("hello");
  17.  
  18. </script>
  19.  
  20. </body>
  21. </html>

Continuing with the “Curiosities” serie, today I bring another one: Javascript doesn’t take too well the definition of a variable with the same name as a function parameter. If you do this, the parameter is lost.

Copy the code to a local file and try it yourself… Surprisingly, the second alert will print “undefined”.

Meiga 0.1.0 released

As presented on my last post, I’ve been working in Meiga, a lightweight content sharing tool for the desktop.

What you could find these days in the git repository was a beta. I’ve been working last days in the final details and now it’s ready to be released. Here it is:


http://meiga.igalia.com

There you will find packages for Ubuntu Hardy, Intrepid and Jaunty, as well as a link to the source code.

I hope you to enjoy it as much as I’ve enjoyed writing it. Of course, comments and improvement suggestions for next versions are welcome. 🙂

Meiga: lightweight content sharing from the desktop

No, this time I’m not going to talk about the wonderful new Igalia office opening party, nor about the Igalia summit that we’re going to have this weekend in a hotel near Santiago de Compostela. This time I’m going to talk about a new free software project I’ve been working on to take advantage of the paid hackfest ours that our company provides us. Ladies and gentlemen, I’m proud to present the Meiga project to you.

As all of you already know, the current trend in the Internet is to publish contents in centralized servers to be shared to other people. Nevertheless, sometimes it’s handy for users to be able to serve their own contents directly from their desktops in a convenient way (instead of using a pendrive, for instance). Why bothering about publishing your contents if you can share them directly from your desktop to the LAN or even to the whole Internet?

To satisfy this need we’ve created Meiga, a tool that makes possible to share selected local directories via web. But that’s only the beginning. In fact, the ultimate goal of the project is to serve as a common publishing point for other desktop applications, such as the file manager, picture viewers or music players.

Meiga is lightweight, easy to use, network friendly and also application friendly. It’s written in a mix of Vala and pure C code, using existing Gnome technologies to perform its tasks: libsoup is used as a simpler alternative to fat web servers, libgupnp is in charge of doing port redirections if the network router supports UPnP, and DBUS exposes a public API to allow the GUI and third party applications to control what is served. Some advanced publishing features are already implemented, like the feed server that can render an RSS view of a given directory.

From the educational point of view, the source code of this project is a live example of Vala technology usage: pure Vala programming, different alternatives to interface Vala with pure C code (using Vapi files or running a child executable program) or the usage of a “programmable context” to handle sequentiation of asynchronous operations. An autotools based build system completes the set of interesting features. This system uses a Vapi file to pass configuration parameters from the config.h to the Vala program. Finally, some additional rule files allow the building of a Debian package, the last step to make the program available to final users in a convenient way.

Meiga is free software. It’s released under GPL 2.0 and can be downloaded just typing:

git clone http://git.igalia.com/meiga.git

Curiosities about using closures in loops in Javascript

Just execute this code in your browser and find the ten differences between the two loops:

  1. <html>
  2. <body>
  3. <script type="application/javascript;version=1.7">
  4.  
  5. let funs = {};
  6. let msg = "";
  7.  
  8. for (let i = 0; i < 10; i++) {
  9.   funs[i] = function() {
  10.     msg += "i = " + i + "n";
  11.   }
  12. }
  13.  
  14. for (let i = 0; i < 10; i++) funs[i]();
  15.  
  16. alert("Without redeclaration: n"+msg);
  17.  
  18. msg = "";
  19. for (let i = 0; i < 10; i++) {
  20.   let idx = i;
  21.   funs[i] = function() {
  22.     msg += "i = " + idx + "n";
  23.   }
  24. }
  25.  
  26. for (let i = 0; i < 10; i++) funs[i]();
  27.  
  28. alert("With redeclaration: n"+msg);
  29.  
  30. </script>
  31. </body>
  32. </html>

As you can see, the i variable works as if it was declared outside the loop, so it’s reused inside it. Thus, if you use it inside a closure, all the closures share the same reference and can see the changes produced during the iterations.

However, in the second loop a new fresh local variable is defined for each iterations, so the values aren’t shared among the closures.

Shell Scripting notes

Eight years ago, back in 2000, I was decided to learn shell scripting. I found the Bourne Shell Programming book by Robert P. Sayle a very good way to start, so I began my way through it, reading the concepts, making the exercises and taking advantage the opportunity to write a sort of personal notes (in Spanish) using LyX (a text processor I liked very much at the moment).

Some time later I submitted the notes to the GPUL mailing list and they were posted at the research groups page. Unfortunately, there’s no way to access the notes from there, because a disk failure and the website revamping got them lost. It’s a pity, because not even the Internet Archive preserves a copy of them.

Those notes have a symbolic value for me. They served as a basis for later bash scripting courses I taught and, after many changes and adaptations, are still the main inspiration for the shell scripting slides used in the Caixanova Free Software Master.

For that reason, today I did a bit of computer archaeology and searched through my old backups until I found it. Now that this material is back, I want to share it with all of you:

Enjoy it!

Spanish version / versión en español:

Hace ocho años, allá por el 2000, me decidí a aprender shell scripting. Descubrí que el libro Bourne Shell Programming de Robert P. Sayle era una muy buena forma de empezar, así que inicié mi camino a través de él, leyendo los conceptos, haciendo ejercicios y aprovechando la oportunidad para escribir una especie notas personales (en español) usando LyX (un procesador de textos que me gustaba mucho en aquel momento).

Algún tiempo después envié las notas a la lista de correo de GPUL y fueron publicadas en la página de grupos de investigación. Por desgracia, no hay forma de acceder a las notas desde allí, porque un fallo de disco y la remodelación del sitio web hicieron que se perdieran. Es una pena, porque ni siquiera el Internet Archive guarda una copia de ellas.

Esas notas tienen un valor simbólico para mi. Sirvieron como base para cursos posteriores de scripting bash que impartí y, tras muchos cambios y adaptaciones, son aún la inspiración principal para las transparencias de shell scripting usadas en el Master de Software Libre de Caixanova.

Por esa razón, hoy hice un poco de arqueología informática y estuve buscando en mis viejos backups hasta que lo encontré. Ahora que este material ha reaparecido, quiero compartirlo con todos vosotros:

  • Notas sobre Shell Scripting (versión PDF): bash.pdf
  • Notas sobre Shell Scripting (archivo con versiones LyX, tex, ps y HTML): articulo_scripting.tgz

Disfrutadlo!

How to interact with an SVG image from an HTML document

Did you know that modern browsers already implement builtin support to visualize SVG drawings? And that you can make changes on them from the HTML document and make changes into the document from the SVG? In this post I’m going to explain all that through a simple example.

To create the SVG document you can use Inkscape. This program has a nice feature that allows you to edit attributes of particular nodes. For instance, you can select such a node, open the XML editor (Edit –> XML Editor…) and add a new attribute onclick to the node with the value:

javascript:window.parent.document.form1.bodypart.value='head';

When you’ve finished, just save the document as “plain SVG” to prevent compatibility problems.

Let’s go to the HTML part now. The easiest way to show the SVG in the document is by using an “embed” tag:

<html>
<body>

<h1>Anatomy of a smiley</h1>

<form name="form1">
Body part: <input type="text" name="bodypart" /> <br/>
</form>

<embed id="smiley" src="smiley.svg" width="745" height="1053" />

</body>
</html>

But that’s not enough. If you want to change SVG attributes using javascript, just add this code:

<script type="text/javascript">
   function changeColor(color) {
   var path=document.getElementById("smiley")
      .getSVGDocument()
      .getElementById("path2383");
   path.style.setProperty("fill",color, "");
   }
</script>

[...]

Color: <input type="text" name="color" value="#FFFF00" /> <br/>

<input type="button" value="Change color"
 onclick="javascript:changeColor(this.form.color.value);"/> <br/>

And that’s all. Now you have bidirectional knowledge between your HTML document and your SVG document. Take a look here to see the whole example.

There are still pending issues, like embedding the SVG code as part of the HTML source. That can be done including the proper DTDs and making sure that the document is interpreted as XHTML (that’s the most important think). Here is a modified version of the previous example to illustrate that, but I hadn’t been able to resolve nodes using this kind of embedded drawings.

Basic commands and scripting class at Free Software Master

This weekend I’ve taught the first sessions at Caixanova Free Software Master. It consisted of a brief introduction to basic command line tools and some concepts about shell scripting and regular expressions tools.

All the course slides are licensed under a Creative Commons license. Until we finish to set up the course collaborative platform, the slides and exercises will be available in my personal web page. I’ll update this link when a final destination for those materials is found.

In addition, Ive compiled some interesting links related to the subject, which can be found in this dedicated Delicious section.

Pam_preprofile 1.1, a swiss army knife for PAM

Pam preprofile is a PAM module that ensures that some program or script is run each time a user logs into the computer. It’s suited for network administrators when they can’t rely on a particular shell to execute the user’s .profile, .bash_profile, .bashrc or similar… because sometimes the user home directory doesn’t even exist yet.

There are already many PAM modules out there, each one suited to a particular need (mounting shares, creating tmp dirs, etc.), but the real advantage of pam_preprofile is its versatility. Pam_preprofile can be used to satisfy any need not being implemented by any existing PAM module at this time but which can be written as a script by the system admin.

The configuration is simple. Just install the module at /lib/security/ and add this line at the end of /etc/pam.d/common-session:

session required pam_preprofile.so /tmp/myprogram.sh /usr/doc

That will call /tmp/myprogram.sh every time the user starts a session (logs into the desktop), passing it a “/usr/doc” parameter, plus an extra parameter with the username being authenticated.

In the previous version of the module, the script was executed always at the session stage. It was very helpful to create the user account. But some weeks ago, a network administrator presented me a scenario where he needed to execute the script each time the system asked the user for a password (that is, at “auth” stage), because the user info could have been updated meanwhile and some local configuration should be updated based on that.

I then improved the module and the new 1.1 version is out. It allow scripts to be executed in the PAM stage you want (account, auth, password and session), not only at the “session” stage allowed by the previous version.

Are you a network administrator? You can download it from:

http://community.igalia.com/twiki/bin/view/Corunix/ProjectDownloadStable

I’ve a landline phone number in USA

I know, I know… having a landline phone number in USA isn’t uncommon if you live there. But the fact is that I don’t live there.

The phone number is offered for free by IpKall and it’s binded to my Gizmo SIP account (VoIP). That way, when you call that number, and if I’m logged into my Gizmo account, I can receive your call. Moreover, if you’ve a Skype account it should be cheap for you to call me. Yes, you’ve catched it: it’s the perfect and cheap (but not free) SIP-Skype bridge.

In fact, I’m thinking to bind the number to the SIP account of the PolyCom we’ve in the office. That way, we could set up a multiconference among some Skype users and the PolyCom.

P.S.: I’m not showing here the real phone number nor the Gizmo account for privacy reasons. If you’d like to know them, just contact me.