Archive for November, 2008

Injecting javascript with Firebug

Nov 30 2008 Published by Eneko Alonso under uncategorized

Sometimes you may want to include a Javascript file on a live web page to see how things will work or to try new things. Usually you would do this by editing the source code including the new file but there is a fastest way if you have Firefox with Firebug. Just run the following code in the Javascript console:

  1. var headID = document.getElementsByTagName("head")[0];
  2. var newScript = document.createElement('script');
  3. newScript.type = 'text/javascript';
  4. newScript.src = 'http://enekoalonso.com/lib/jquery-1.2.6.min.js';
  5. headID.appendChild(newScript);

Here I am loading the jQuery library from my own server, but I could load any Javascript from any server on the net. The best is this will work on any website, whenever you have access to the server or not. Once you have the Javascript loaded you can use it right away. For example, here on this blog I could use jQuery to check how the header will look if its height was only 100px by running the next command on the console:

  1. jQuery('#header').css('height',100);

Yep, it won’t look very good, right? Try it! You have to see it by yourself. Firefox is great. Firebug is awesome. And Firebug’s Javascript console is the best thing ever!
PS: In case you are wondering, the Javascript file injected will exist only on the current browser session.

No responses yet

Setting up a development environment

Nov 29 2008 Published by Eneko Alonso under uncategorized

I want to left behind the days when I was developing code without any version control system. I have been using these at work for years now, but never for my personal projects. So know I use/have two SVN repositories:

But SVN doesn’t solve all problems, specially when working with Javascript and HTML. This is because I want to see my code in action. For this, I have http://code.enekoalonso.com. Until now I was uploading manually javascript and html demo pages that I was working on, but synchronizing it with the SVN repository became a pain very fast. So in order to avoid this, I have done a checkout of my SVN repository on my webserver. Now, whenever I update or add a new project to the repository, updating http://code.enekoalonso.com will be as simple as running the command:

svn update

And that’s it!

Now I can develop and test locally on my own computer, then commit to svn and update my code server without any pain.

No responses yet

JS.Class: a very nice object oriented approach

Nov 29 2008 Published by Eneko Alonso under uncategorized

I have been using jQuery and Mootools in the last few months at work, among other libraries. So far, jQuery was my favorite because it is very fast and encapsulated (it doesn’t interfere with other librearies, etc). But I love Mootools too because of its object oriented approach and beautiful things like the Class class which lets you create JS classes very easily. Every time I use jQuery I miss that from Mootools.

Well, a copuple of days ago I have discovered JS.Class which I think is the best thing I have seen so far in object oriented Javascript. It is awesome! Very well designed and documented and very well encapsulated.

JS.Class is not a library for DOM manipulation but just a framework to build object oriented code. And I love that! I think it is way better to focus on a single task, instead of trying to cover it all. This makes JS.Class a very lightweight library too :)

Copy-constructor test class in Mootools:

var myClass = new Class({
  1.   text: '',
  2.   say: function() {
  3.     console.log(this.text);
  4.   }
  5. });

Copy-constructor test class in JS.Class:

var myClass = new JS.Class({
  1.   text: '',
  2.   say: function() {
  3.     console.log(this.text);
  4.   }
  5. });

As you can see, the way of creating classes is almost the same. So what makes JS.Class better than Mootools? Where, both allow inheritance and extending classes with other class-helpers, but JS.Class does this better. I’ll work on some example code to prove this :)

PS: Don’t take me wrong, I still love Mootools and I’ll still use it on web development. But I try to use JS.Class as much as possible.

No responses yet

Making your objects sortable

Nov 28 2008 Published by Eneko Alonso under uncategorized

Making your objects sortable in Python is very simple: add the __cmp__ function and the logic to compare the two objects and you are done!

  1. class person:
  2.   def __init__(self, name, age):
  3.     self.name = name
  4.     self.age = age
  5.  
  6.   def __str__(self):
  7.     return 'Person %s (%d)' % (self.name, self.age)
  8.  
  9.   def __cmp__(self, other):
  10.     return cmp(self.name+str(self.age), other.name+str(other.age))
  11.  
  12. lista = [
  13.   person('Ren Smith', 24),
  14.   person('Aohn Doe', 31),
  15.   person('Aohn Doe', 22),
  16.   person('Eneko Alonso', 30),
  17.   person('Ren Gomas', 34)
  18. ]
  19.  
  20. for person in lista:
  21.   print person
  22. print '—–'
  23. for person in sorted(lista):
  24.   print person

As you can see, you can totally customize your __cmp__ method and compare any class members.

Download the code: http://enekoalonso.com/svn/python/classes/sorting-objects.py

No responses yet

MyGameOfLife source code

Nov 28 2008 Published by Eneko Alonso under uncategorized

Almost a year ago I was learning some Cocoa and I decided it will be fun to implement a Cocoa based version of Conway’s Game of Life. Back then I didn’t publish the source code, not for any special reason. So now I have just uploaded it to Google Code. It’s not fully functional, since the last time I worked on it I was creating an structure editor. My idea was to create a library of structures, with drag&drop and import/export options.

If you are interested on working on the project, let me know :)

http://code.google.com/p/my-gameoflife

My Game of Life

No responses yet

Unnecessary function calls inside loops

Nov 28 2008 Published by Eneko Alonso under uncategorized

Calling to functions that return the same value over and over to test the exit condition on a loop is a very novel error or mistake, but I have seen it multiple times in different programming languages. At the end, the problem is the programmer relying on the compiler optimization, which I think is a bad practice. Write efficient code and let the compiler do its job. But don’t rely on it to optimize your inefficient code. Not to say than there is no compiler optimization at all when writing interpreted code like Python or Javascript.

Here is a simple test to show how adding a simple string.length call on a loop impacts the performance.

  1. var text = "Calling to functions that return the same value over and over to test the exit condition on a loop is a very novel error or mistake, but I have seen it multiple times in different programming languages. At the end, the problem is the programmer relying on the compiler optimization, which I think is a bad practice. Write efficient code and let the compiler do its job. But don't rely on it to optimize your inefficient code. Not to say than there is no compiler optimization at all when writing interpreted code like Python or Javascript.";
  2. var iterations = 100000;
  3.  
  4. var start_slow = (new Date()).getTime();
  5. for (var n=0; n<iterations; n++) {
  6.   for (var i=0; i<text.length; i++) { // Call to text.length inside loop is executed N times
  7.     // Nothing to do
  8.   }
  9. }
  10. var end_slow = (new Date()).getTime();
  11.  
  12. var start_fast = (new Date()).getTime();
  13. var l = text.length;    // Call to text.length outside the loop is executed only once
  14. for (var n=0; n<iterations; n++) {
  15.   for (var i=0; i<l; i++) {
  16.     // Nothing to do
  17.   }
  18. }
  19. var end_fast = (new Date()).getTime();
  20.  
  21. console.log('Slow:' + (end_slow – start_slow));
  22. console.log('Fast:' + (end_fast – start_fast));

Note: I have tested it on Firefox 3.0 and Safari 3.2. The second seems to have a bigger performance impact.
Firefox: Slow: 3,667ms Fast: 3,342ms
Safari: Slow: 6,273ms Fast: 2,157ms
Demo: http://code.enekoalonso.com/js/tests/strlen-loop-test.html

2 responses so far

Copy-constructor test in Javascript

Nov 27 2008 Published by Eneko Alonso under uncategorized

After posting about assigning objects in Python only copies the reference and does not clone the object, I wanted to verify if the behavior happened in Javascript. Here is the code:

  1. var myClass = function() {
  2.   this.text = '';
  3.   this.say = function() {
  4.     console.log(this.text);
  5.   }
  6. }
  7. var A = new myClass();
  8. var B = new myClass();
  9. A.text = 'testing A';
  10. B.text = 'texting B';
  11. A.say();
  12. B.say();
  13. A = B;
  14. A.say();
  15. B.say();
  16. A.text = 'testing A2';
  17. A.say();
  18. B.say();

Here is the output:

testing A
texting B
texting B
texting B
testing A2
testing A2

Both A and B end up pointing to the same instance in memory, while the old A instance is inaccessible.
Demo: http://code.enekoalonso.com/js/tests/copy-constructor-test.html

No responses yet

Copying objects vs. copying references

Nov 26 2008 Published by Eneko Alonso under uncategorized

C++ is a language that allows creation of static instances of objects, this is without using pointers. This is why copy-constructors are needed, since it is common to copy or clone objects. Other languages like Delphi don’t allow to create static variables to instantiate objects. Instead, all objects are pointers. So in C++, assignments of instances of the same class create a copy of the object, while in Delphi, only the reference to the second instance is copied.

When I started learning Python one year ago, I wanted to know if objects were cloned on assignments or if only the reference to the object was assigned instead. Here is how I found it:

  1. class Item():
  2.   def __init__ (self):
  3.     self.text = ""
  4.   def sayIt(self):
  5.     print self.text
  6.  
  7. A = Item()
  8. B = Item()
  9. A.text = "testing A"
  10. B.text = "testing B"
  11. A.sayIt()
  12. B.sayIt()
  13. A = B
  14. A.sayIt()
  15. B.sayIt()
  16. A.text = "testing A 2"
  17. A.sayIt()
  18. B.sayIt()

This code will output 6 messages. The first two will be obviously different, since A and B are to separate instances on memory. When B is assigned to A, two things can happen. B is cloned and A is a new instance equal to B or the reference to B is assigned to A so A and B become the same instance in memory (B). No matter which one happens, both messages after the assignment will correspond to the B instance (“testing B”).

But what will happen when we modify A again? Will B be also modified?

Here is the output:

testing A
testing B
testing B
testing B
testing A 2
testing A 2

So A and B are now the same object in memory.

2 responses so far

Fibonacci

Nov 26 2008 Published by Eneko Alonso under uncategorized

Fibonacci is a fast growing sequence that can easily overflow your integer variables. Fortunately, Python doesn’t have this problem, since it can handle huge integer numbers.

  1. #!/usr/bin/env python
  2. def fib(n):
  3.   if n==0 or n==1:
  4.     ret = n
  5.   else:
  6.     ret = fib(n-1) + fib(n-2)
  7.   return ret
  8.  
  9. for i in range(1000):
  10.   print fib(i)

The example avobe has a big performance issue, due to the recursive calls to calculate n-1 and n-2 values, which are calculated multiple times over and over. By storing the results on a list we solve this issue, although we now relay on the amount of available memory.

  1. #!/usr/bin/env python
  2. fibs = []
  3. def fib(n):
  4.   if n==0 or n==1:
  5.     ret = n
  6.   elif n < len(fibs):
  7.     ret = fibs[n]
  8.   else:
  9.     ret = fib(n-1) + fib(n-2)
  10.     fibs.append(ret)
  11.   return ret
  12.  
  13. for i in range(1000):
  14.   print fib(i)

Thus, Fib(1000) = 43,466,557,686,937,456,435,688,527,675,040,625,802,
564,660,517,371,780,402,481,729,089,536,555,417,949,051,890,403,879,840,079,
255,169,295,922,593,080,322,634,775,209,689,623,239,873,322,471,161,642,996,
440,906,533,187,938,298,969,649,928,516,003,704,476,137,795,166,849,228,875

No responses yet

Presentation

Nov 26 2008 Published by Eneko Alonso under uncategorized

dev.enekoalonso.com is a new blog where I plan to publish my notes, code, tests, exercises and studies in Javascript & Python among other languages.

No responses yet