Search Results: "enrico"

10 June 2007

Enrico Zini: things-not-to-do

Things not to do with lvm and crypto At least as of june, 2007, you should never do this: "...I need some encrypted storage space...":
lvcreate -L1G -n test vgname
cryptsetup luksFormat /dev/vgname/test
cryptsetup luksOpen /dev/vgname/test test1
mke2fs -j /dev/mapper/test1
mount /dev/mapper/test1 /mnt
# ...copy important data to /tmp...
"...oh, I need more space...":
lvresize -L+1G /dev/vgname/test
# cryptsetup resize test1 did not seem to
# work, so why not try this instead:
cryptsetup reload test1 /dev/vgname/test
resize2fs /dev/mapper/test1
Message from syslogd@localhost at Sun Jun 10 13:17:37 2007 ... localhost kernel: journal commit I/O error
"...oh damn. What happened?":
umount /mnt
mount /dev/mapper/test1 /mnt
EXT3-fs warning (device dm-13): ext3_clear_journal_err: Filesystem error recorded from previous mount: IO failure EXT3-fs warning (device dm-13): ext3_clear_journal_err: Marking fs in need of filesystem check.
"...let's check it then...":
umount /mnt
e2fsck /dev/mapper/test1
"...what the hell is going on?":
e2fsck -fy /dev/mapper/test1
"...$ & ! ^ @ $ ( Y ^ Q ! @ % # !!!".

31 May 2007

Enrico Zini: package-descriptions

Writing good package descriptions Thanks to Fathi Boudra, I found the link to "Writing Debian package descriptions". Towards the bottom of the page, it contains an excellent checklist to follow when writing one. This entry is to take a note of it, so that I'll find it when I write one myself, and when I report a bug for a description that could be improved.

30 May 2007

Martin F. Krafft: Information management 2.0

Dear Lazyweb: my information management is in dire need of an upgrade. In particular, I am looking for two features, the second of which is an extension of the first. So let's start with the first: Given a certain issue a job, a project, I write and receive emails, send and receive letters, make and receive phone calls, and author all kinds of documents. In addition, I may have other tidbits of information, such as bookmarks and contact information of the involved people, which are related to the issue at hand. I can store the documents and letters in folders on my filesystem, but what emails and bookmarks and contact information are isolated from the filesystem by the application through which I access this information, even though they may be stored in standard formats. I do not want to create redundant information by copying emails to the respective folders in the filesystem, not only because of the error potential in forgetting that one message which you later need. What I want is a high-level view ideally command-line based into my information, such that for any given project, I can easily and immediately access all related correspondence, documents, and data. I almost want something like a customer relation management system (CRM), except that I don't want to organise my data contact-centric, but rather issue-centric: an issue may involve nobody, a dozen other people, or be about one single person. I took a brief look at beaglefs and was briefly impressed that it did not depend on roughly 5 gigabytes of GNOME/Mono, but then also decided that it's not what I wanted, because it's too fileystem-centric and I also do not want a hundred mounted pseudo filesystems in my home directory. Beagle, on the other hand, does have half a million dependencies and plugins for almost every other application that has half a million dependencies, but it's basically unusable to people who use simple, non-graphical tools for their information management. I am going to check strigi-daemon and doodle, but I don't really expect any different. Does anyone know of a high-level tool that I could use to tie together all my information sources/types? Then, on to the second feature I want: tags. You know it, tags are web 2.0 and web 2.0 is sexy and since I want to be sexy, I need tags. They are also marginally useful and I could use them to place the link the email from a friend about Debconf7 to his name, Debian, the conference, as well as the client we're going to be visiting on the way back. Or I could associate the slides for my talk on method diffusion with Debian, the conference, and my Ph.D. research. Marginally useful but soooo sexy. Tags should be hierarchical, such that foo::bar::baz is a subset of foo and foo::bar (and a query for foo would automatically yield results for foo::bar::baz too). Wildcards should be supported, such that I could search for foo::+::baz and also find foo::bla::baz, and of course you should be able to perform the standard logical functions, such as AND/OR/NOT on them. Enrico calls this "faceted categorisation" and I would never question him on such topics. I do like the idea of a filesystem, backed by an index, but otherwise using metadata stored in extended filesystem attributes, which is what BeagleFS does. However, I'd like it to be ad-hoc, such that the query is not a mount option, but rather determined by the filesystem syscalls. For instance, the directory listing of /TAGS/foo::bar/ should contain all files tagged with foo::bar; /TAGS/-foo::bar/, /TAGS/foo::bar,+::baz/, and /TAGS/foo::+.bla::+/ could be the shell-friendly ways to encode NOT, OR, and AND. If you think about it for a minute, then it's actually not that hard and should be a weekend job to implement on top of FUSE, but it'll only really work when each filesystem node corresponds to exactly one entity. Contacts and bookmarks are trivial to implement that way (VCards and .lnk files), but e-mail is not: with the two popular storage backends mailbox and Maildir, an e-mail message is either a set of lines in a file, or a file in a directrory hierarchy. At first, Maildir may sound like the ticket, but when you consider that a message's new status is encoded in the path and not in the message's filename or content, while the filename is used to encode other status and index information, such as deleted or a message's size, it quickly becomes a nightmare this is why I consider mairix to be more or less unusable other than for quick, one-time searches. To be able to properly deal with email in the filesystem I am proposing, one would need to use mailboxes that only ever stored one message (which would be a waste of space and is not supported by any of dozens of e-mail processing or reading tools), or a new format that used only extended filesystem attributes for metadata, never location of a file or its name. And that does not exist yet, isn't debugged, let alone supported by any tools. Where to, Lazyweb? Comments welcome. NP: Gazpacho: When Earth Lets Go Update: as many have noted, of course I am looking for something like the semantic web, or closely related to it however, given the current state of things, that doesn't get us any further. Also, I don't want any of the Web or social and community stuff that seems to be an inseperable part of the semantic web or the OWL. I just want the semantics for a single-user environment. Thus, NEPOMUK, which three people have pointed to, is not what I am looking for. On the issue of one-mail-per-file, Remi Vanicat pointed me to Gnus' nnml storage:
If you use this back end, Gnus will split all incoming mail into files, one
file for each mail, and put the articles into the corresponding directories
under the directory specified by the  nnml-directory  variable.
As long as nnml is a Gnus-specific format, it's useless to me. I want to continue using standard tools like mutt, procmail, formail, and IMAP servers.

Enrico Zini: vim-changelog

Editing ChangeLog with vim Turns out vim has a changelog.vim plugin to edit ChangeLog files. With \o you start a new entry. A look at /usr/share/vim/vim70/ftplugin/changelog.vim can show some more.

20 May 2007

Enrico Zini: create-mysql-db

Creating a new db on MySQL The grant syntax is designed in such an arbitrary way that it's impossible to remember it properly unless you use it every day. So I write it down, hopefully once and for all, here:
# mysqladmin create dbname
# mysql dbname
mysql> GRANT ALL PRIVILEGES ON dbname.* TO enrico;
Follows a list of keywords that I'm likely to use in the future to look for this information in case if I forgot that I wrote this note:

Enrico Zini: openbox

Openbox Reading that keeping X in 3D mode tends to use more power convinced me to finally drop compiz. Back to metacity, I found it unusable. I've always used Super+Right mouse drag to resize windows, and metacity refuses to do that. I haven't found a way to resize windows with it other than dragging the super-thin, impossible-to-catch window corners or using the keyboard. I had a look at debtags search x11::window-manager (I found x11::window-manager using debtags tagsearch window) and picked openbox. Quite light, standardards-compliant, it seems to handle everything as it should (gnome panel, popups, fullscreen applications, name it). It has a very simple configuration dialog, just like metacity. Unlike metacity, it also has a configuration file in which I can tweak those things that are not in the configuration dialog. And it supports much more of those than metacity does. So, here are three use cases that weren't covered by metacity (or compiz, in case of RaiseLower) and are now fully covered by openbox: And also, the fan of my laptop is not on all the time anymore. Updates:

12 May 2007

Enrico Zini: tg-i18n-quirks

Turbogears i18n quirks Collecting strings from .kid files tg-admin i18n collect won't collect strings from your .kid files: you need the toolbox web interface for that. Indentation problems in .kid files The toolbox web interface chokes on intentation errors on your .kid files. To see the name of the .kid file that causes the error, look at the tg-admin toolbox output in the terminal for lines like Working on app/Foo/templates/bar.kid. What happens is that the .kid files are converted to python files, and if there are indentation glitches they end up in the python files, and python will complain. Once you see from the tg-admin toolbox standard error what is the .kid file with the problem, edit it and try to make sure that all closing tags are at the exact indentation level as their coresponding opening tags. Even a single space would matter. Bad i18n bug in TurboKid versions earlier than 1.0.1 faide on #turbogears also says:
It is of outmost importance that you use TurboKid 1.0.1 because it is the first version that corrects a BIG bug regarding i18n filters ... The version below had a bug where the filters kept being added at each page load in such a way that after a few hundreds of pages you could have page loading times as long as 5 minutes!
If one has a previous version of TurboKid, one (and only one) of these is needed: So, in short, all i18n users should upgrade to TurboGears 1.0.2.2 or patch TurboKid using http://trac.turbogears.org/ticket/1301.

Enrico Zini: tg-more-singleselectfield-quirks

Turbogears quirks when testing controllers that use SingleSelectField Suppose you have a User that can be a member of a Company. In SQLObject you model it somehow like this:
    class Company(SQLObject):
        name = UnicodeCol(length=16, alternateID=True, alternateMethodName="by_name")
        display_name = UnicodeCol(length=255)
    class User(InheritableSQLObject):
        company = ForeignKey("Company", notNull=False, cascade='null')
Then you want to make a form that allows to choose what is the company of a user:
def companies():
    return [ [ -1, 'None' ] ] + [ [c.id, c.display_name] for c in Company.select() ]
class NewUserFields(WidgetsList):
    """Fields for editing general settings"""
    user_name = TextField(label="User name")
    companyID = SingleSelectField(label="Company", options=companies)
Ok. Now you want to run tests:
  1. nosetests imports the controller to see if there's any initialisation code.
  2. The NewUserFields class is created.
  3. The SingleSelectField is created.
  4. The SingleSelectField constructor tries to guess the validator and peeks at the first option.
  5. This calls companies.
  6. companies accesses the database.
  7. The testing database has not yet been created because nosetests imported the module before giving the test code a chance to setup the test database.
  8. Bang.
The solution is to add an explicit validator to disable this guessing code that is a source of so many troubles:
class NewUserFields(WidgetsList):
    """Fields for editing general settings"""
    user_name = TextField(label="User name")
    companyID = SingleSelectField(label="Company", options=companies, validator=v.Int(not_empty=True))

7 May 2007

Enrico Zini: tg-override-sqlobject

Quirks when overriding SQLObject setters Let's suppose you have a User that is, optionally, a member of a Company. In SQLObject you model it somehow like this:
    class Company(SQLObject):
        name = UnicodeCol(length=16, alternateID=True, alternateMethodName="by_name")
        display_name = UnicodeCol(length=255)
    class User(InheritableSQLObject):
        company = ForeignKey("Company", notNull=False, cascade='null')
Then you want to implement a user settings interface that uses a Select box to choose the company of the user. For the Select widget to properly handle the validator for your data, you need to put a number in the first option. As my first option, I want to have the "None" entry, so I decided to use -1 to mean "None". Now, to make it all blend nicely, I overrode the company setter to accept -1 and silently convert it to a None:
    class User(InheritableSQLObject):
        company = ForeignKey("Company", notNull=False, cascade='null')
        def _set_company(self, id):
            "Set the company id, using None if -1 is given"
            if id == -1: id = None
            self._SO_set_company(id)
In the controller, after parsing and validating all the various keyword arguments, I do something like this:
            user.set(**kw)
Now, the overridden method didn't get called. After some investigation, and with the help of NandoFlorestan on IRC, we figured out the following things:
  1. That method needs to be rewritten as _set_companyID:
            def _set_companyID(self, id):
                "Set the company id, using None if -1 is given"
                if id == -1: id = None
                self._SO_set_companyID(id)
    
  2. Methods overridden in that way are alsop called by user.set(**kw), but not by the User(**kw) constructor, so using, for example, a similar override to transparently encrypt passwords would give you plaintext passwords for new users and encrypted passwords after they changed it.

2 May 2007

Enrico Zini: linux-usb-foot-pedal

Linux and a USB VEC foot pedal A new gadget has been showing up: a VEC USB foot pedal used for transcription. I plug the foot pedal into the USB port and a /dev/usb/hiddev0 device shows up. This is enough to make Transcribe! happy, and you can assign actions to the pedal devices in Transcribe! and go on using it. In Ubuntu Feisty /dev/usb/hiddev0 won't appear automatically. Luckily, an old style mkdir /dev/usb; mknod /dev/usb/hiddev0 c 180 96 does the job. What I couldn't do is make the device show up as a joystick, a keyboard or whatever else that could generate usable events. This is strange, because the device seem to identify properly as a HID device. Dear Lazyweb, how can I get events out of the thing, and then map one pedal to Alt, one to Enter and one to TAB?

1 May 2007

Enrico Zini: index

Debtags paper for Debconf 7 Paper contents:

Enrico Zini: recovering-fat-partition

Recovering a corrupted FAT partition A friend has seen his FAT partition in his USB key become unmountable. Here's how I recovered it. Analysis:
  1. Make a dump: dd if=/dev/sdb1 of=partition.img
  2. Have a look. I like mc for this, as it has a nice hex viewer and editor (F3 to view, then F4 for hex view; F2 would then allow hex edit, if needed).
  3. Turns out that the initial part of the partition has been completely overwritten by 0xff bytes. After some point (around block 224), the 0xff bytes end and there seems to be a FAT structure (easy to identify because it contains sequences of increasing 16bit values).
It seems that the damage is only limited to filesystem structures. I should be able to recover most data by regenerating the filesystem data and hoping that at least the second FAT is still intact. Solution:
# Make a copy of the partition
cp partition.img partition1.img
# Reformat it: that gives us the bits of filesystem structures we need
mkdosfs partition1.img
# Graft together the two parts
dd if=partition1.img of=partition2.img count=224
dd if=partition.img of=partition2.img seek=224 skip=224
# Tidy up the result, telling dosfsck to use the 2nd FAT.
dosfsck -rw partition2.img
# Mount and check what's available
mount -o loop,ro partition2.img /mnt
Yo! Everything was there again. When I teach about standard Unix commands, it takes a while for people to realise all the powerful things you can easily do with them.

30 April 2007

Enrico Zini: tg-quirk

Turbogears form quirk I had a great idea:
@validate(model_form)
@error_handler()
@expose(template='kid:myproject.templates.new')
def new(self, id, tg_errors=None, **kw):
    """Create new records in model"""
    if tg_errors:
        # Ask until there is still something missing
        return dict(record = defaults, form = model_form)
    else:
        # We have everything: save it
        i = Item(**kw)
        flash("Item was successfully created.")
        raise redirect("../show/%d" % i.id)
It was perfect: one simple method, simple error handling, nice helpful messages all around. Except, check boxes and select fields would not get the default values while all other fields would. After two hours searching and cursing and tracing things into widget code, I found this bit in InputWidget.adjust_value:
# there are some input fields that when nothing is checked/selected
# instead of sending a nice name="" are totally missing from
# input_values, this little workaround let's us manage them nicely
# without interfering with other types of fields, we need this to
# keep track of their empty status otherwise if the form is going to be
# redisplayed for some errors they end up to use their defaults values
# instead of being empty since FE doesn't validate a failing Schema.
# posterity note: this is also why we need if_missing=None in
# validators.Schema, see ticket #696.
So, what is happening here is that since check boxes and option fields don't have a nice behaviour when unselected, turbogears has to work around it. So in order to detect the difference between "I selected 'None'" and "I didn't select anything", it reasons that if the input has been validated, then the user has made some selections, so it defaults to "The user selected 'None'". If the input has not been validated, then we're showing the form for the first time, then a missing value means "Use the default provided". Since I was doing the validation all the time, this meant that Checkboxes and Select fields would never use the default values. Hence, if you use those fields then you necessarily need two different controller methods, one to present the form and one to save it:
@expose(template='kid:myproject.templates.new')
def new(self, id, **kw):
    """Create new records in model"""
    return dict(record = defaults(), form = model_form)
@validate(model_form)
@error_handler(new)
@expose()
def savenew(self, id, **kw):
    """Create new records in model"""
    i = Item(**kw)
    flash("Item was successfully created.")
    raise redirect("../show/%d"%i.id)
If someone else stumbles on the same problem, I hope they'll find this post and they won't have to spend another two awful hours tracking it down again.

27 April 2007

Enrico Zini: tg-file-download

File downloads with TurboGears In TurboGears, I had to implement a file download method, but the file required access controls so it was put in a directory not exported by Apache. In #turbogears I've been pointed at: http://cherrypy.org/wiki/FileDownload and this is everything put together:
from cherrypy.lib.cptools import serveFile
# In cherrypy 3 it should be:
#from cherrypy.lib.static import serve_file
@expose()
def get(self, *args, **kw):
    """Access the file pointed by the given path"""
    pathname = check_auth_and_compute_pathname()
    return serveFile(pathname)
Then I needed to export some CSV:
@expose()
def getcsv(self, *args, **kw):
    """Get the data in CSV format"""
    rows = compute_data_rows()
    headers = compute_headers(rows)
    filename = compute_file_name()
    cherrypy.response.headers['Content-Type'] = "application/x-download"
    cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="'+filename+'"'
    csvdata = StringIO.StringIO()
    writer = csv.writer(csvdata)
    writer.writerow(headers)
    writer.writerows(rows)
    return csvdata.getvalue()
In my case it's not an issue as I can only compute the headers after I computed all the data, but I still have to find out how to serve the CSV file while I'm generating it, instead of storing it all into a big string and returning the big string.

Enrico Zini: debconf-logo

I like the Debconf logo I like the Debconf logo. There's something familiar in it: Debconf logo with Mario

18 April 2007

Enrico Zini: 5-star-hotel

5 star hotel tips There are things you don't think about until you spend 2 weeks in a 5 star hotel. In 5 star hotels you have a minibar that you're not supposed to open unless you want to be charged something stupid like 10 euros for 25cl of still water claiming to have been bottled in the opposite side of the world from where the hotel is located. But on top of the minibar there are glasses you can use for drinking, and an ice bucket you can refill in the corridor. This allows you to put ice in tap water. If the tap water is undrinkable, buy a 3l water bottle in the nearby supermarket and use the ice to make it colder without upsetting the minibar. Note: this specific minibar has sensors, and charges you the very moment you take things away from the fridge, so it's out of the question to temporarily empty it to put my things in for a while. Now, the ice bucket, the ice clips in the ice bucket and the glasses used for drinking, how do they clean them? Are they sent 6 floors downstairs to the dishwasher? Certainly not. They use the DETERGENT FOR THE WINDOWS. I went to get some ice and realised that the inside of the bucket (and the ice clip to put the ice in your cocktails) smelled like window detergent. Then I sniffed around: same did the glasses, and one had leftover foam in the bottom. So I had to wash the toxic stuff away from them before using them. Now I can assume that I have to wash the glasses every time I need them, as I know that they are not necessarily cleaned with food-safe detergents. So, here's the tip: before leaving the room in the morning, I put glasses and ice bucket back on the tray on top of the fridge, and I put the cheap-pretending-to-be-fancy cocktail mixing plastic sticks back in the glasses. This succeeded in tricking the cleaning people into believing that I didn't use them. As a consequence they didn't clean them, and now I can use them without needing to wash the window detergent away first. Another tip: don't leave your shoes next to the sofa, or the cleaning staff will put them on the sofa when cleaning (sometimes they forget them on the sofa, so you realise). Even better: don't put them next to the bed. Another tip: if the breakfast buffet has only scary things it takes half a day to digest, make friend with the omelette cook.

6 April 2007

Erich Schubert: Debtas AI (it's, like, alive!)

These days I picked up the Debtags AI topic again (so yes, development is alive, not the AI). Some people will remember this topic, it was a Google Summer of Code project. The project didn't really complete back then. Since my thesis isn't coming along too well (I don't know how to explain to my professor what I'm trying to achieve...), I've been playing around with different stuff. So I've picked up the Debtags AI again. Back at the end of the GSoC or sometime later last summer, I had started a rewrite of the Debtags AI stuff in C++ for performance reasons. I also had some ideas on how to make it scale better and on how to improve the results. I think I've reached an interesting state now; training time of the AI is down to a few minutes (remember it was a few days when the GSoC started?), so I managed to cut off another order of magnitude. Evaluation of a text against the database (i.e. for every tag) happens in the fraction of a second. This AI is turning out quite well now. I have one more idea for a trick that could improve the results from an algorithm side, and one from the data side. Enrico is already looking at how to integrate it with the web apps. :-) And I also want to scale it up further. How about using it to classify web pages by their text content? I already have an idea on how to get some good training data... maybe I should consider writing a business plan instead of a diploma thesis...

3 April 2007

Enrico Zini: aptitude-ui-tweaks

My Aptitude UI tweaks This is the way I tweak aptitude: I find it useful, other people found it useful, time to share it.
  1. Run aptitude
  2. Options / UI Options
  3. Disable "Prompt for confirmation at exit" (aptitude saves state, so a quit can perfectly be undone by running aptitude again)
  4. Enable "Advance to the next item after changing the state of a package"
  5. Go to "The default grouping method for package views" and remove this part: ,section(subdir,passthrough),section(topdir) (I find that splitting packages by section adds too many levels between me and the packages)
  6. Go to "The display format for package views" and change it into %c%a%M%S %p %d %Z %v %V (I like to see the short descriptions)
Then most of the work I do on aptitude is using l (powerful filters, like in mutt) to get to packages, + or _ to install/purge them and the fantastic ^u to have a multi-level undo. ^u in fact allows to play what-if with package selections: priceless!

29 March 2007

Enrico Zini: remoteform-weird-error

TurboGears RemoteForm tip In case your RemoteForm misteriously behaves like a normal HTTP form, refreshing the page on submit, and the only hint that there's something wrong is this bit in the Iceweasel's error console:
Errore: uncaught exception: [Exception... "Component returned failure
code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXMLHttpRequest.open]"
nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)"  location: "JS frame ::
javascript: eval(__firebugTemp__); :: anonymous :: line 1"  data: no]
the problem can just be a missing action= attribute to the form. I found out after:
  1. reading the TurboGears remoteform wiki: "For some reason, the RemoteForm is acting like a regular html form, serving up a new page instead of performing the replacements we're looking for. I'll update this page as soon as I figure out why this is happening."
  2. finding this page on Google and meditating for a while while staring at it. I don't speak German, but often enough I manage to solve problems after meditating over Google results in all sorts of languages unknown or unreadable to me. I will call this practice Webomancy.

28 March 2007

Enrico Zini: passing-values-to-turbogears-widgets

Passing values to turbogears widgets at display time In turbogears, I often need to pass data to widgets at display time. Sometimes it works automatically, but sometimes, in cases like passing option lists to CheckBoxLists or number of repetitions in a RepeatingFieldSet, it doesn't. All the examples use precomputed lists or pass simple code functions. In most of my cases, I want them computed by the controller every time. Passing a function hasn't worked, as I did not find any obvious way to have the function know about the controller. So I need to pass things the display() method of the widgets, but I could not work out how to pass the option list and default list for a CheckBoxList that is part of a WidgetsList in a TableForm. On IRC came the answer, thanks to Xentac:
you should be able to...
    tableform.display(options=dict(checkboxname=[optionlist]))
And yes, it works. I can pass the default value as one of the normal form values:
    tableform.display(values=dict(checkboxname=[values]), options=dict(checkboxname=[optionlist]))

Next.

Previous.