Go to the navigation

elblogg

»programming

Round, Floor and Ceiling in Expression Language

Java Conference 2006 by Matteo Penzo ( matteopenzo on flickr)

Expression Language makes working with Java Server Pages a slightly less pain in the behind. But, its functionality is very limited, there is for instance no way to round off a number, neither as floor, ceiling or to the closest integer

Floor(foo) -> ${foo - ( foo % 1 ) }
Ceiling(foo) -> ${foo + ( 1 - (foo%1)) % 1}
Round(foo) -> ${foo +0.5 - ((foo+0.5) % 1) }

This still gives you a float, so to get an integer, you must either use the <fmt:formatNumber>-tag

<fmt:formatNumber value="${foo - ( foo % 1 ) }" var="fooAsInt" maxFractionDigits="0"/>

(really, this returns a string, representing the number without the decimals. But as EL automatically casts between strings, floats and integers, this is mostly OK.)

or you can hack it using fn:replace():

${fn:replace(foo - ( foo % 1 ),'.0','') }

(Yes, you may use singlequotes for strings in EL, even though this is supposed to be Java….)

Video: BLUG Last Thursday November 2009: Mercurial

Dette er mitt første forsøk på å lage video av BLUG-foredragene. Forhåpentligvis blir det flere etterhvert, og med mer erfaring, sannsynligvis bedre kvalitet (og kanskje litt mindre filer…). Volumet kan variere relativt mye igjennom foredraget.
OGG Theora (512×288) MP4 h.264 (720×405)

Mercurial er et distribuert versjonskontrollsystem som har blitt svært populært siden det ble annonsert i 2005. Det støttes nå offisielt av tjenester som SourceForge, Google Code og BitBucket. Det vil bli gitt en introduksjon basert på typisk bruk, innebygde kommandoer, utvidelser og verktøy. Det trengs ingen spesielle forkunnskaper, men kjennskap til mer tradisjonelle versjonskontrollsystemer som CVS og subversion kan være en fordel.

Knut Arild jobber som utvikler i Vizrt og har brukt Mercurial både profesjonelt og for private prosjekter.

Foilene kan også leses her

Flickr shortcode plugin for WordPress

Earlier this week I wrote about how you can add a shortcode to the functions.php to make it easier to use Creative Commons images on your blog, while always remembering to put in the correct attribution.

Adding this to your theme has some drawbacks. The most important one is that you’ll have to do it all over when you change the theme, another is that you have to add the flickr api key directly into the code.

That’s why I have just made it into a wordpress plugin. This means you just need to download the package, extract it into the plugins folder, and then use the “El Flickr” menu entry to add the flickr api key.

I have changed the flickr shortcode to elflickr, so there should be less possibility for conflict with other plugins. You chan also change the shortcode to whatever you want (including flickr) from the configuration page.

I’ve also added another feature. Lets say you need a HDR picture of Bergen, but don’t care too much which one is used, what if you could add the picture without going to flickr to look it up? The question is of course rhetorical, because now you can.

[elflickr search="HDR Bergen from Fløien"]

yields the picture in the beginning of this article. The result of the search is stored, so you don’t need to worry that the search results will change over time. It also limits the search to Creative Commons licensed pictures.

[elflickr search="Tilt shift bergen city"]
old houses in Bergen by Julia ( kroolik on flickr)

I have a lot of ideas for this plugin, the release is numbered 0.0.2, and there’s a lot of room for improvements. For instance I will incorporate the gallery into the plugin, which currently is implemented in my theme.

Download el_flickr 0.0.2


If your blog is hosted on my server, I will install it for you if you ask me to.

The plugin just generates the HTML code, you need to style it using your stylesheet, see the flickr shortcode for an example, and for more examples on how to use the plugin.

Planned improvements:

  • styling from configuration page
  • configuration of licenses to search for
  • more caching of rest call results
  • integrate the gallery into the plugin
  • provide a default theme
  • search by geolocation

[1 of 3] Updating your brightkite location using Google latitude

BrightKite is a service, much like twitter actually, but that uses your location to find interesting stuff. It could be a great tool to create ad-hoc gatherings of some group of people, for instance coders. If there were a lot of BrightKite users in Bergen for instance, I could leave a message on brightkite that I and some other Python coders were going for a beer at Henriks, and that any others that is interested could join if they wanted, together with the GPS coordinates for Henriks. Other BK users in Bergen interested in Python could then see that message based on the proximity to that location and maybe the search term BrightKite.

The problem is that, though there are BK applications for the iPhone, theres no client for the S60 mobile market, and also the iPhone app provides a poor precision on the location.

Unofficial Google Latitude T-Shirt by Matt Jones ( moleitau on flickr)

I came to think of the Google Latitude service, which is a service that retreives your GPS location, and makes it available online, and to other Google Maps users in your Google contacts list when you’re using the Google Maps application. (though this is a privacy concern). I started investigating, and discovered that they have a “badge” you can use to post on your website.

This post is going to tell you how to use the data provided by this service in your Python apps. Upcoming posts will tell you how to turn this data into an address, using the Google Maps API, and the final post will show you how to use this address to update your BrightKite location through their API.

I strongly discourage using this badge as it is, as it exposes your private URL’s for your location information, and once these are available on another page than the google latitude badge page, you can never use the the webservices I’m about to tell you about, without possibly having strangers get to it.

As long as you keep these URL’s private, you should be pretty safe.

Go to the Google Latitude Badge page, and enable the service at best available precision, then go to the bottom of the page, where you would find a public json feed. It’s url looks someting like this: http://www.google.com/latitude/apps/badge/api?user=YOUR_SECRET_ID&type=json We’re going to use that URL in a moment.

The script below defines a GLatitude class, which we will initialize with your secret id (the long number from the json feed url), and which we then can use to get the latitude and longitude of the current location the Latitude service has on you.

Note that you can specify your location yourself using the privacy settings in the Google Maps application, so you can perfectly well lie about your location.

?View Code PYTHON
import urllib2, json
class GLatitude:
  def __init__(self,uid):
    self.uid=uid
  def getLocationData(self):
    return json.load(urllib2.urlopen("http://www.google.com/latitude/apps/badge/api?user=%s&type=json" % self.uid))
  def getCoords(self):
    return self.getLocationData()['features'][0]['geometry']['coordinates']

It’s really simple. All I do is to fetch the json data, and lets the json module parse it. then the getCoords() method extracts the coordinates from the data returned.

I placed this code in a file called GoogleMaps.py, which we also will use in the next post, so I can use it as a module later on.
To use this then, you could do the following:

?View Code PYTHON
import GoogleMaps
gl=GoogleMaps.GLatitude("YOUR_SECRET_ID")
myLocation=gl.getCoords()
print "I'm located at latitude %s and longitude %s " % myLocation

Running this would produce something like the following:

I’m located at latitude 60.390218 and longitude 5.330515

Stay tuned for the rest of this tutorial.

PHP frustration

Most of the code I’ve written in my life so far has been PHP, as long as I include all the small testing of different stuff just to see if it could be done.

PHP is quick to prototype stuff in, because you quickly get something you can poke around with, there’s little boilerplate code. However, specially when I’m just hacking together something in a hurry, theres one thing that’s really, really frustrating. Specially when I deal with SimpleXMLElements.

In Python you can do this:

?View Code PYTHON
firstbar=element.getElementsByTagName("bar")[0]

to get the first bar element inside “element”, in Java, i can do pretty much the same, and even in javascript you could do this, but in PHP, you always have to assign the result of getElementsByTagName() to a variable before accessing it’s index.

<?
print $element->xpath("//bar")[0]; // FAILS
$bars=$element->xpath("//bar");
print $bars[0]; //WORKS
?>

Now of course, this is not the only thing that frustrates me with PHP, but this was the thing biting me yesterday.

EDIT:
I realize that the best way to do this is using the current() function in PHP:

<?
print $element->xpath("//bar")[0]; // FAILS
print current($element->xpath("//bar")); // WORKS
?>

Flickr shortcode (and some nice HDR photos)

I like using creative commons photos from flickr as illustrations on my blog, however, I find it tedious to add all the metadata to satisfy the BY directive in the creative commons license in a consistent manner. Then it’s really nice that flickr has an API where I can automatically fetch that information. I use the shortcode feature of wordpress, so I can use

[flickr url="http://www.flickr.com/photos/stuckincustoms/4099398743/in/photostream/"]

to include an image like below:

Crossing the Bridge into Old Lyon by Trey Ratcliff ( Stuck in Customs on flickr)

or

[flickr pid="4097758830"]

to insert the image below:

or to get another size version i can use

[flickr pid="4088949046" version="Small"]

, like below:

The River Runs Through the Andes by Trey Ratcliff ( Stuck in Customs on flickr)
Tokyo Road by Trey Ratcliff ( Stuck in Customs on flickr)

Here’s the code, notice that you need to get an API key from the flickr api site:

<?
/**
  * This piece of code is created by Bård Aase <elzapp@gmail.com>, 
  *  and is licensed under the GPL.
  *  Contact me if you need another license. 
  */
function sc_flickr($atts){
    /**
     * This function gathers information about a flickr image, and complies with the
     * shortcode API in Wordpress.
     * @param $atts array of options
     *   Options:    pid: picture id
     *               version: Small, Medium or Large (default:Medium)
     *               class: class to apped to the <div class="image "> so you can style it
     *               url: You can use an URL instead of a picture id, the pid will be 
     *                     extracted
     */
    $FLICKR_APIKEY="INSERT YOUR API KEY HERE"
    extract(shortcode_atts(array(
    "pid" => $atts[0],
    "version"=>"Medium", //setting default value
    "class"=>"centered", //setting default value
    "url"=>""
    ), $atts));
    if($url != ""){
       $e=explode("/",$url);
       $pid=$e[5];
    }
    /* broken into several lines to look better on the blog */
    $sizes_url="http://api.flickr.com/services/rest/?method=flickr.photos.getSizes";
    $sizes_xml=file_get_contents("{$sizes_url}&api_key={$FLICKR_APIKEY}&photo_id=$pid");
    $info_url="http://api.flickr.com/services/rest/?method=flickr.photos.getInfo";
    $info_xml=file_get_contents("{$info_url}&api_key={$FLICKR_APIKEY}&photo_id=$pid");
    $c=new SimpleXMLElement($info_xml);
    $sizes=new SimpleXMLElement($sizes_xml);
 
    $size=$version;
    $un=$c->xpath("//owner/@username");
    $rn=$c->xpath("//owner/@realname");
    $t=$c->xpath("//title");
    $u=$c->xpath("//url");
    $image=$sizes->xpath("//size[@label='$size']/@source");
    $width=$sizes->xpath("//size[@label='$size']/@width");
    $height=$sizes->xpath("//size[@label='$size']/@height");
    $fontsize="A";
    if($height[0] > 300 & $width[0] > 500){
        $fontsize="C";
    }elseif($height[0] > 200 & $width[0] > 300){
        $fontsize="B";
    }
    $r=<<<EOT
<div class="image imageclass{$fontsize} {$class}" style="width:{$width[0]}px">
<img src="{$image[0]}" width="{$width[0]}" height="{$height[0]}"><div class="caption">
<span class="title"><a href="{$u[0]}">{$t[0]}</a></span> 
    <span class="author">by {$rn[0]} ( 
    <a href="http://flickr.com/photos/{$un[0]}">{$un[0]}</a> on flickr)</span>
</div>
</div>
EOT;
    return $r;
}
?>

Put that in a file in your theme directory, and call the file “flickr.php”, then put the following into the functions.php-file in the same folder:

require_once("flickr.php");
add_shortcode('flickr','sc_flickr');

Note that this generates the HTML only, the visual style is added to your blog's css, here's the CSS I've used in this example:

 
.image { position:relative; }
.caption {
  position:absolute;
  bottom:0;
  left:0;
  right:0;
  padding:5px;
  background:transparent url(tr75b.png) repeat scroll left top;
  color:#FFF;
  font-family:"Trebuchet MS";
}
.image:hover .caption {
  background:#000;
}
.caption a {
  color:#CFC;
}
.image img {
  display:block;
}
.imageclassA { font-size:10px;}
.imageclassB { font-size:14px;}
.imageclassC { font-size:18px; }
.image.centered {
margin:auto;
}
.image.floatleft {
margin:5px;float:left;
}
.image.floatright {
margin:5px;float:right;
}

the image referenced in the stylesheet is available from here

Great news in the software world

During the last week there has been a couple of great releases in the software I use every day.


First out was Python 3.1. It was released June 27th and features

  • An ordered dictionary type
  • Various optimizations to the int type
  • New unittest features including test skipping and new assert methods.
  • A much faster io module
  • Tile support for Tkinter
  • A pure Python reference implementation of the import statement
  • New syntax for nested with statements


Next out was Mozilla Firefox 3.5, which was released earlier today (June 30th), most noteworty items from that release is the @font-face css-attribute, that allows web-designers to bundle custom fonts with their website designs, and use custom fonts in their design.  I have used that feature to change the header of my blog, you would se a grudge font if you use the new Firefox or Safari. They have also released a new javascript-engine, which they claim to be a lot faster than the old one. Also, support for the <video>-tag has been added.


Then last, but not least, the long awaited PHP 5.3.0 has been released, which provides namespaces and closures for PHP.

Merging two lists

Lets say you have two lists, one of them containing the values [1,2,3] and the other one containing the values [4,5,6], and you want to combine these two lists into one list, like this one: [1,2,3,4,5,6].

Let’s see how this can be done in different (high level) programming (or scripting or templating) languages.

Java

Java has multiple list implementations, lets start with the most basic one, the builtin array.

int[] A = {1,2,3};
int[] B = {4,5,6};
int[] C = new int[A.length + B.length];
int counter=0;
for(int e : A){
  C[counter]=e;
  counter++;
}
for(int e : B){
  C[counter]=e;
  counter++;
}

or with an ArrayList:

/*Dropped importing the correct classes, 
and constructing the ArrayLists A and B, since thats not the focus here...*/
List<Integer> C = new ArrayList();
C.addAll(A);
C.addAll(B);

PHP

So, how is the same done in PHP?

$A=array(1,2,3);
$B=array(4,5,6);
$C=array_merge($A,$B);

Python

And at last, how does the Pythonistas do this?

?View Code PYTHON
A=[1,2,3]
B=[4,5,6]
C=A + B

Note: the rubyists use the same approach.

New howto: Using apache to create an authenticated proxy

I just wrote a description on how you can use apache to create an authenticated proxy ahead of your development server, or other http-based servers that doesn’t provide authentication themselves.
You can find it under the docs-section or by clicking here: Using apache to create an authenticated proxy.

Merkelapper

De observante der ute (og som ikke bare leser bloggen min fra rss-leseren sin) kan ha oppdaget at merkelappene på bloggpostene har fått et nytt utseende.

Det begynte egentlig med at jeg så på en post jeg hadde skrevet og tenkte “Hm, de taggene der ser ikke ut som om de egentlig hører hjemme der”. Videre tenkte jeg, hva skal jeg gjøre for å få dem mer inn i det visuelle uttrykket på bloggen. Det hadde vært fint med noen bilder, men da må jeg vedlikeholde en haug med bilder for alle taggene. Det har jeg forsøkt før, da bare for kategoriene, og det er nesten ti ganger så mange tagger som kategoriene.

Hva om jeg kunne lage en bakgrunn som fikk merkelappene til å se mer ut som merkelapper? Vel.. min assosiasjon til merkelapper i denne sammenhengen er slike brune lapper som brukes på postsekker. Jeg kunne alltids lage en bakgrunn som så slik ut, men jeg syntes det ville være rart om de bare gikk rett horisontalt.

Her kommer vi til en av de tingene som jeg har savnet i CSS. En mulighet til å rotere objekter.

Velvel. vi kan jo alltids generere bilder på serveren, og bruke det… Og det var akkurat det jeg endte opp med også. Ikke bare får jeg da generert merkelappene slik jeg vil ha dem, men jeg kan velge den fonten jeg vil ha også, selv om webfonts ikke er støttet i nettleserene enda.

Resultatet er merkelappene nedenfor, og php-koden som genererer dem finner du her
Og her er det jeg brukte for å putte det inn i wordpress-temaet

Bloggurat Twingly BlogRank Blogglisten