Including static HTML snippets in Weblocks

Generating your HTML directly in Lisp with CL-WHO (or some other HTML generation toolkit) is effective.
However, sometimes you need to include HTML from external sources, for example when you want HTML writers to provide page elements.

Here’s a widget for Weblocks that will create a widget from static HTML:

(in-package :weblocks)
 
(export '(static-html make-static-html-from-file
          with-widget-header render-widget-body))
 
(defwidget static-html (widget)
  ((html :type string :accessor html :initarg :html :initform ""))
  (:documentation "Represents a piece of static HTML body mark-up."))
 
(defmethod with-widget-header ((widget static-html) body-fn &rest args &key
                                                    prewidget-body-fn postwidget-body-fn &allow-other-keys)
    (apply body-fn widget args))
 
(defmethod render-widget-body ((widget static-html) &rest args)
  (format *weblocks-output-stream* "~A~_" (html widget)))
 
(defun make-static-html-from-file (file)
  "Create a static-html widget representing the mark-up in “file”."
  (with-open-file (input file :direction :input)
    (let ((data (make-string (file-length input))))
      (read-sequence data input)
      (make-instance 'static-html :html data))))

The Lisp paste is at http://paste.lisp.org/display/54023.

Sending mails in Common Lisp

Just a quickie that might be useful for people new to CL.

Install CL-SMTP if you don’t have it yet:

(asdf-install:install 'cl-smtp)

You’re now able to load it into your Lisp core at any time:

(asdf:oos 'asdf:load-op 'cl-smtp)

And use it, either interactively (HOST is your SMTP server, e.g. localhost):

(cl-smtp:send-email "HOST" "from@foo.com" "recipient@bar.com"
                    "SUBJECT" "BODY")

or non-interactively:

(handler-case
  (prog1 t
    (cl-smtp:send-email "HOST" "from@foo.com" "recipient@bar.com"
                        "SUBJECT" "BODY"))
  (error (msg) (format t "Could not send mail: ~A~%" msg) nil))

We need the prog1 because send-email always returns nil, even on success.
With the above, the whole expression will return true on success, which lets us decide afterwards whether we were able to hand our message to the mail server.

cl-i18n 0.4 released

If it continues like this, we will be at 1.0 soon. ;)

Vilson Vieira has added translation resource merging and has refactored the code base in a nice way.

I also put up my darcs repository at http://viridian-project.de/~sky/cl-i18n/ so you can provide patches against it if you want to contribute.

Kalman filtering

Engineering reality often confronts us with systems that can’t be modelled very well with fixed formulas.
Sometimes we don’t even know some of the system equation’s variables; think of signal noise, for example.

Enter the Kalman filtering algorithm. Given a number of observable and non-observable states, a Kalman filter tries to predict the non-observables ones.

Normally the state vectors have a dimension greater than 1, so you have to fiddle around with matrices. We once implemented the filter in Java; it was astonishingly simple, but the Java idiosyncrasy of making even the most simple code look complicated diminished this simplicity considerably. Here’s the core of it, i.e. the code minus the various “object-oriented” boilerplate methods:

public void filter(State state) throws MatrixException {
 
    setStateTransitionMatrix(delta, state.getAcceleration());
 
    x = lastX;
 
    y.setValue(0, 0, state.getPosition().getX());
    y.setValue(1, 0, state.getPosition().getY());
    y.setValue(2, 0, state.getPosition().getZ());
 
    /* PREDICT */
    x = A.multiply(x);
 
    if ((!E.isZeroMatrix()) && (R != null) && (!R.isZeroMatrix())) {
        E = ((A.multiply(E)).multiply(A.transpose())).add(Q);
        Matrix K = null;
 
        /* CORRECT */
        K = (E.multiply(B.transpose())).multiply(((B.multiply(E))
                .multiply(B.transpose()).add(R)).invert());
 
        if (!K.isZeroMatrix()) {
            x = x.add(K.multiply(y.subtract(B.multiply(x))));
            E = (I.subtract(K.multiply(B))).multiply(E);
        }
 
    }
    lastX = x;
    setState(state);
}

And now you may leave the torture chamber and take a look at an implementation in q. Beautiful!

cl-i18n 0.3 released

I had not expected contributions coming in so quickly, but thanks to Vilson Vieira cl-18n can now extract translatable strings in a rudimentary fashion. Use it like this after loading the package:

(i18n-util:generate-i18n-file "gowron-monologue.lisp" "klingon.lisp")

You need cl-ppcre for it right now, and it can’t merge yet (the target file gets overwritten). But it’s a good start!

Good enough in any case for me to add a README and call it version 0.3.

Adding accessiblity warnings to HTML-generating Lisp code

Image objects in HTML should have at least an ALT attribute for text browsers and screen readers, so let’s automate the checking:

(asdf:oos 'asdf:load-op 'cl-who)
 
(defmacro demand-image-attrs (img want-attrs have-attrs)
  "Check an image's accessiblity information for completeness."
  (let ((missing-attrs (gensym)))
    `(let* ((,missing-attrs (loop for attr in ,want-attrs
                                 when (not (find attr ,have-attrs))
                                 collect attr)))
       (unless (null ,missing-attrs)
         (warn "image ~S is missing the following attributes: ~{~A~^, ~}" ,img ,missing-attrs))))
 
(defmacro render-image (src &rest attrs)
  "Produce HTML code from an image location."
  (declare (type string src))
  `(demand-image-attrs src (list :alt :title) attrs)
  `(cl-who:with-html-output (*standard-output*)
     (:img :src ,src ,@attrs)))
 
CL-USER> (render-image "cat.png" :title "Tom")
WARNING: image "cat.png" is missing the following attributes: ALT
"<img src='cat.png' title='Tom' />"

Simple and effective.

Methods of customizing CLOS objects

CLOS objects provided by other people, for example as parts of libraries, are always a generalization of the concept they represent. What are the ways in which we can model our own objects, with their peculiar presets?

Suppose this simplified class from a layman’s biological classification library:

(in-package :bio)
 
(defclass flower (plant)
  ((stem-color :initform nil)
   (petal-color :initform nil)))

Suppose further that accessors and initargs are named like the slots themselves.

Now let’s try to model a white rose; green stem, white petals. What choices do we have?

Class specialization

The next best thing:

(defclass white-rose (flower)
  ((bio::stem-color :initform 'green)
   (bio::petal-color :initform 'white)))
 
(make-instance 'white-rose)

Watch out for package scoping when overriding slots!
This is a little bit ugly because we have to override the protection of the “bio“ package.
Also, any additional slot arguments (accessors, initargs) defined in some parent class are probably lost.
But instantiation is really clean, simple and straight-forward. As an added bonus you can customize the class beyond presets for existing slots: new slots are easily added.

See the comments section for a better version of this approach.

Constructor function

This method uses a simple function setting up the general object in a customized way and returning it:

(defun make-white-rose ()
  (make-instance 'flower :stem-color 'green :petal-color 'white))

Nice and without package lock intrusion, but not as obvious as class specialization.

initialize-instance :after-method

This is a variation on the first method. It might seem a bit intimidating, but works suprisingly well.

(defclass white-rose (flower) ())
 
(defmethod initialize-instance :after ((self white-rose))
  (setf (stem-color self) 'green)
  (setf (petal-color self) 'white))

initialize-instance gets called after make-instance to initialize the slots of the new object. We provide an :after method so the built-in method can do its housekeeping beforehand (assign specified initargs to slots, for example).

How do you provide specialized presets?

Announcing cl-i18n

This is an early release of a humble package.
I could not find a translation framework for CL that served my needs, so I wrote one.
The focus is on clean and easy usage; the code is by no means witchcraft and it’s likely that people already implemented this on their own, but to my knowledge it’s the first one that is available to the public and comes in an ASDF package.

There’s a separate page on cl-i18n that lists its features and deficiencies.
You can also find an usage example there.

CSS doesn’t scale

While customizing a CMS for a client, I was forced to confront an old enemy of mine: CSS.
“What”, you say, “but surely you must be convinced that CSS is the latest and greatest in the separation of style from content?”

Well, latest, yes. Greatest? Far from it.

The good points: CSS is the only standardized tool that lets you separate content. The cascading model is well-designed and most often well-implemented. The set of selectors and attributes is as well.

But now let’s face two glaring problems of CSS. And no, cross-browser compatibility hacks are not among them.

  1. dynamic layout: show me a CSS multi-column layout without at least one column fixed in width. With the scourge called
    I can specify percentages and they work nicely, adapting themselves to the screen estate of the client. Why this omission? It feels like stone age in a world full of handheld devices and lots of different resolutions.Most web designers seem fine with specifying pixels all around. But then again a lot of web designers have Macromedia Dreamweaver, Adobe Illustrator and Adobe Photoshop among their favourite tools. I’m always tempted to use tables instead, which gives me the additional boon of a working vertical alignment.
  2. arithmetic expressions: it’s not possible to do even the most simple of calculations like 2em + 50px. Also, wouldn’t it be badly needed to be able to say: 2em + (SCREEN-WIDTH / 2), especially with absolute positioning? In this case, I can actually see why CSS don’t has this, though: Microsoft Internet Explorer often messes up even with only one value.

What makes it really bad is that CSS3 doesn’t attempt to solve those, to my knowledge. But let’s see whether HTML5 with its semantic additions can help here.

What are your experiences with CSS?

Free Game Soundtrack: Doom III — Last Man Standing

The Last Man Standing Doom III mod has released its soundtrack for free download. I’m listening to it right now, and it’s a great mixture of heavy rock and retro-gaming synth sounds. What’s more, it’s not in MP3, but in Ogg Vorbis format, making it doubly sweet! :)

I’d post a torrent file, but I’m not sure whether that’s covered by the terse license terms. So let me just point you to the official HTTP download page, section “Last Man Standing Official Soundtrack”.

« Previous Page