Archive for June, 2007

JavaScript Client Side Image Thumbnailing

First of all, the Quality of the thumbnail is quite bad, at least by now (just tested in firefox). Furthermore it’s a bad idea to do thumbnailing on the clientside but it works.

function makeThumb(src, canvas, width, height) {
  canvas.width = width;
  canvas.height = height;
  var ctx = canvas.getContext('2d');
  ctx.scale(
    width / src.width,
    height / src.height
  );
  ctx.drawImage(src, 0, 0);
}

src must be an Image, canvas a canvas element and width/height is the size of the resulting thumbnail. If you want to get the image data of the thumbnail for saving on the server or whatever, you can do canvas.toDataURL() which returns the data of the image as base64 version of a png.

Another Way to Capture Print in Python

When working with the Python ast module i found the pycodegen which generates bytecode from an ast. Basically what you can do with it is modifying the ast before compiling the code. So one use case is compiling code and patching all Print/Printnl nodes without a destination to buffer into a stream:

import compiler

def compile_with_stream(code, stream, filename='?'):
    print_nodes = [compiler.ast.Print, compiler.ast.Printnl]
    rv = compiler.parse(code)
    nodes = [rv]
    while nodes:
        node = nodes.pop()
        node.filename = filename
        if node.__class__ in print_nodes and node.dest is None:
            node.dest = compiler.ast.Const(stream, node.lineno)
        nodes.extend(node.getChildNodes())
    gen = compiler.pycodegen.ModuleCodeGenerator(rv)
    return gen.getCode()

Instead of using compiler.ast.Const you can also use compiler.ast.Name and point to a variable that contains the stream. This would allow caching the bytecode too. Now what it does is translating “print ‘Hello World’” to “print >> stream, ‘Hello World’” if there is no given destination. This can be useful for template engines (once again ^^).

Example usage:

from StringIO import StringIO
stream = StringIO()
exec compile_with_stream('print "Hello World"', stream)
print 'Captured: %r' % stream.getvalue()

any/all for Python2.4

Want to use any/all in Python2.4? Here the minimal implementation that break on the first not matching value like any and all in Python2.5 do:

def any(iterable):
    return False in (not x for x in iterable)

def all(iterable):
    return True not in (not x for x in iterable)

Credit for the idea goes to BlackJack from the German python forum

Patching Python Tracebacks — Part Two

June 16th, 2007

After posting this I hacked up a “tbtools” module that contains various traceback helper functions to modify tracebacks. You can find it here: tbtools.

It’s far from stable and I want to ask some of the authors of other template engines (namely zzeeek) for their ideas. There is also an example of the werkzeug minitmpl engine with support for tbtools. Now what it does is the following:

It converts this useless traceback of a template engine with code generation:

Traceback (most recent call last):
  File "templating.py", line 151, in <module>
    print tmpl.render(broken=broken)
  File "templating.py", line 120, in render
    return u''.join(tuple(tmp['__generate']()))
  File "<template>", line 10, in __generate
  File "templating.py", line 149, in broken
    foo()
  File "templating.py", line 148, in foo
    raise RuntimeError("nested broken")
RuntimeError: nested broken

Into this:

Traceback (most recent call last):
  File "templating.py", line 151, in <module>
    print tmpl.render(broken=broken)
  File "test.html", line 3, in <module>
    <%= broken(item) %>
  File "templating.py", line 149, in broken
    foo()
  File "templating.py", line 148, in foo
    raise RuntimeError("nested broken")
RuntimeError: nested broken

Because Python locks the traceback object a minimal C module is required. ctypes also doesn’t work because the python API doesn’t export the struct we need.

Pylons Screencasts

Part 3 of the pylons screencast is online. Good work Chairos.

Patching Python Tracebacks

June 15th, 2007

So what’s one of the greatest features Python has? Correct. Exceptions and Tracebacks. Especially the latter is a cool thing but it’s also limited. Say you have a template engine that generates code before executing the template. So if an runtime error occurs the message is correct but the line number points to the generated code and not the source line.

So how to fix? The plan basically is:

  • Have a generated line <-> source line mapping somewhere
  • catch exceptions that happen in the code execution and skip the first one or two frames until you reach the frame where the generated code is
  • reraise the exception in a isolated namespace but in the new line (hackish)
  • patch the traceback and inject your new traceback from the isolated frame (nearly impossible)

Now the mapping is the smallest problem, as well as the frame skipping (just access tb_next a couple of times). The real problems is reraising the exception in a different line and patching that new traceback into the traceback chain. There are solutions but it requires a C extension module and some code that you better hide. Still, it works :D

If you want to see how it’s implemented check those files:

So yes. You can patch tracebacks and customize them, but it’s deeper magic.

HTML5 Ahead

changes from HTML4 — awesome. Let’s forget about XHTML and friends and go with HTML5. The specs rock, rock, rock!

Adrian Holovaty at Youtube

adrianholovaty — I didn’t know that he posts videos of himself playing guitar there.

SQLAlchemy Book Arriving

<zzzeek_> well now im writing a book and the three or four little lines
on the web page are going to be like 15 pages for you to read, harder to iss
…
<beachcoder> zzzeeek - what book are you writing ?
<zzzeek_> beachcoder: the SA book
<zzzeek_> details to follow

seen on #pylons, some minutes ago

Give us today our daily FUD…

June 14th, 2007

Microsoft once again supported a study that should prove that Microsoft products are superior to Open Source projects. This time the company that did the dirty work this time is Wipro, an Indian based technology company. Conclusion first: schools are happier with Microsoft solutions than with Open Source solutions, being Microsoft powered also means that your system is more stable and of course cheaper too. I guess nobody is surprised about those results.

But what’s remarkable about that study is this:

For the purpose of study segmentation Wipro defines Open Source schools as any school that has adopted greater than 50% use of an OSS solution — in terms of installed base — on any one of the three ICT platform aspects. All schools not meeting these criteria are defined as Microsoft schools.

First of all: What’s a school? Surprisingly there is no definition in that paper. There are enough schools powered by non Microsoft UNIX systems which are not open-sourced. So are those Microsoft schools now? It’s interesting because it looks like that fight Microsoft is fighting is only against Open Source, leaving out proprietary solutions of competitors. The cool thing about this study is that they actually found open source schools:

Country Microsoft Schools OSS Schools
France 8 8
Italy 10 7
Poland 6 8
Spain 7 10
Sweden 3 1
UK 5 0

For me this is great news. I expected that the result of the study would be: there are no open source schools. Because with the definition of what’s an open source school from above in mind there are at least 73 schools in Europe that use more than 50% open source software. My school advertised some time ago that they used Linux on their computers but that was two years ago, only additionally to windows, nobody knew how to use LILO and the rest of the system was closed. So there is hope :D

Also the quotes are…. well…. priceless:

“We have about 20 dual-boot machines that came preloaded with Linux but no one ever uses them; everyone just prefers Windows.” — ICT Manager, Spanish secondary school

Everybody prefers in th in this context basically means: “everybody just knows”. But hey, they came preloaded with Linux, that’s good news, so there are actually companies shipping Linux.

“At our school, many of the computers are equipped with both Microsoft Office and Open Office — but the students have a significant preference for the Microsoft solutions. — Director of ICT for a secondary school in France

Who’s surprised this time? Raise your hands. Now!. No hands? except of some hands in the digg corner
That really reminds me of my school, two years ago. We had (and still have) a proxy that filters incoming and outgoing data for “bad content”. Usually you don’t see that proxy, it just asks you for a password and blocks some useless websites like any URL with the word “nintendo” in it. That worked for a long time pretty well until /var was full and the proxy just locked any access because there was no more space for logging and $admin was unable to enabled log rotation or just find the issue. However. The result was that I installed portable firefox und my homefolder and just not enabled that darn proxy in the settings. After the issue was resolved by an external administrator I continued using firefox. Two weeks later the proxy was once again down but when I logged in I found out that one of my friends copied the portable firefox installer to the communication drive and even some really dumb users were using it. That trend continued and even when the network was working flawlessly again the firefox was still in use.
Two years later: Firefox is installed by default, just with the proxies enabled in the config. Because $admin is still the same nobody locked those configuration values (although it’s possible) and most of the users just disable that proxy because it takes equally long to enter your password or just disable the proxy. And nowadays you see far more firefox users than IE users in the computer rooms.

So what’s the conclusion of that firefox story? (At least in our school) people pick the default because it’s the default and not because it’s better. If you are used to IE, MS Office and friends you won’t switch yourself because it “just works”. But not necessarily better.

The rest of the paper isn’t better, just another quote that is equally funny:

The ICT Manager pointed to the role of Microsoft PowerPoint in lesson
presentation. He stated that, “simply put, on Open Office, our results do not have the same visual quality as the
lessons our teachers create using Microsoft PowerPoint.”

Visual quality?

If you are still interested in that paper, it’s downloadable as PDF from the Microsoft website here: Wipro: ICT in European Schools.

cogitations driven by wordpress