Logarithmic tag cloud using Python.

I needed a simple logarithmic based tag cloud where the frequency of the tags was weighted logarithmically. This means that lower frequency tags get dampened down into the same font size and higher frequency tags are popped out in a tag cloud.

def tag_weight(x):
    if x==None or x==0:
         x = 1
    return weight * math.log(x, math.e)

It is pretty simple. It protects against a None or 0 as putting either of those into the log function would result in a ValueError.

The 'weight' variable can be fixed or calculated and is a means to add a formula to the log output to make the tag cloud look good to a human eye when displayed on the page. I use the output of the tag_weight() function in the style attribute of li with with font-size and em.

You can see the results of this algorithm on this tag cloud.
Very cool. A nice elegant mechanism to incorporate REST into turbogears/python.

Logarithmic Tag Cloud for Python

I needed a simple logarithmic based tag cloud where the frequency of the tags was weighted logarithmically. This means that lower frequency tags get dampened down into the same font size and higher frequency tags are popped out in a tag cloud.

def tag_weight(x):
    if x==None or x==0:
         x = 1
    return weight * math.log(x, math.e)

It is pretty simple. It protects against a None or 0 as putting either of those into the log function would result in a ValueError.

The 'weight' variable can be fixed or calculated and is a means to add a formula to the log output to make the tag cloud look good to a human eye when displayed on the page. I use the output of the tag_weight() function in the style attribute of li with with font-size and em.

Why Your Favorite Programming Language Sucks

Disclaimer, I make most of my living working in Java and this blog is written in Python. Elliotte Rusty Harold writes after seeing Python 3 come out with little care for backwards compatibility:

Unless we're willing to make the hard choices and abandon the legacy as Python has, Java is doomed to the fate of C++ and Cobol: a tool for programmers with long white beards who grew up with the language and have learned all its arcana by gradual accretion and who spend their lives maintaining code written a decade or more ago.

Meanwhile a new generation of programmers will abandon Java in favor of more nimble modern languages like Python just as we abandoned C++ in our youth in favor of Java.

There are still an awful lot of systems written in Java that will need to be maintained; there is also a great deal of business logic in freeware and payware libraries that are used to ease the burden on development. I don't see that changing soon. I do agree it is frustrating to work in a language and see its limitations and clunkiness day after day after day.

A good rant none the less.
MySQL-python via easy_install on OSX. Not so fast.

I am trying to set up this blog's software, which I wrote on python, on the Macbook as opposed to the old Vista desktop I wrote it on. No luck so far. Doubt i have the patience to fix all the compile and egg errors. It might be easier to rewrite the blog in lisp and upload it as one big .emacs file.

Python and the Flickr Services API

I decided to try and integrate my flickr feed into the blog somehow. After some cursory looking around it seemed using the Flickr Services and the flickrapi was the simplest way to achieve that. While this open style of API might enable Web 2.0, the cloud, and all other manner of new uses, for me I just wanted to put my latest flickr uploads on one page on my blog.

I used easy_install to put the flickrapi library on my dev machine and ISP's server. I got the api-key from flickr and since I haven't changed my user id to something more human readable it was a simple find as well.

 # get the list of photos from flickr
def get_flickr_photos(self):
    flickr = flickrapi.FlickrAPI(self.flickr_api_key, format='etree')
    photos = flickr.photos_search(user_id=self.flickr_user_id, per_page='50') # comes out as the _ElementInterface
    # parse out the XML and return an array of URLs
    # http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg
    urls = []
    for image in photos.getchildren()[0]:
        img = {}
        src = 'http://farm%s.static.flickr.com/%s/%s_%s_m.jpg' %  (image.attrib['farm'], image.attrib['server'], image.attrib['id'], image.attrib['secret'])
        url = 'http://www.flickr.com/photos/%s/%s/' % (self.flickr_user_id, image.attrib['id'])
        img['src'] = src
        img['title'] = image.attrib['title']
        img['url'] = url
        urls.append(img)
    return urls

Turned out to be simpler than I expected. The hardest part was working out what the hell I was getting back, Python interfaces can be quite opaque to what data they are carrying. I finally found ElementTree.toString(_ElementInterface) so I could see what I was getting and how far down it I had to drill to get the information I wanted.

You can see the results on the photography page. I made it permanently accessible by the camera icon at the top of the page.
ranomatic: This is cool. I could imagine all sorts of UI fun if you went all flash on it, but as it stands, it is simple and does exactly what you wanted to do.
cam: I have a six month project coming up that is in Flex.
To downgrade sqlobject from 0.10.4 to 0.9.0 using the python easy_install utility:

easy_install SQLObject==0.9.0

Courtesy of OSX and sqlobject installing an admin script I had to sudo it.
Turbogears 2 is out. With some significant changes of the default components; sqlobject to sqlalchemy and kid to genshi. This site runs on Turbogears, I will have to upgrade and see what the change/break is.

Random ResultSet with SQLObject

Was trying to get a result set that was semi-random with only three result coming back using sqlobject. I over-engineered my first attempt into a mess, and sat back to think for a while. In the end I came up with:

 def randResultSet():
    resultSet = Table.select()
    count = resultSet.count()
    upper_bound = random.randint(3,count)
    lower_bound = upper_bound - 3;
    return resultSet[lower_bound: upper_bound]

Two very cool things. SQLObject's SelectResults object on the count() function does a quick query with COUNT rather than loading all the results the select() function returned. Which makes the count call cheap.

SQLObject loads the results lazily anyway, only doing the query when you actually want them. When combined with python's splicing this makes a semi-random result set pretty simple. With some fudging of the orderBy argument and reversed() it is random enough for human eyes.

Internal Redirect in CherryPy based on URL with Turbogears

For phoenix eats out I had to do an internal redirect with CherryPy based on the URL that was coming in, but only for the index page. I did it for all other cases in Apache, but decided with the index page to do it using Turbogears.

The main issue, which took me a while to workout, was that I was running CherryPy as a server locally on my dev machine, but in production I am using mod_proxy with apache. CherryPy gives you quick and easy access to the request headers as a dict, so it is easy to punch out and see what is going on. In my dev environment I set up phoenixeatsout.com in my /etc/hosts to resolve to localhost and wrote:

 if cherrypy.request.headers.get("Host") == 'www.phoenixeatsout.com':
    raise cherrypy.InternalRedirect('/restaurants/')

Which worked fine when I was running CherryPy as the http server. With mod_proxy that doesn't work as the host is always localhost:8000 or whatever host and port you are running CherryPy on that Apache connects to through mod_proxy. After pumping out the headers to the main page I changed it in production to:

reqHost = cherrypy.request.headers.get("X-Forwarded-Host")
if reqHost == 'www.phoenixeatsout.com':
    raise cherrypy.InternalRedirect('/restaurants/')

Because it is an internal redirect it slides to that controller without changing the URL to the user's eye. Quite neat.

More And fwiw the point versioning of the South Sea Republic, Cam Riley and Phoenix Eats Out codebase has gone from 1.3.64 to 1.4.0.
Next 10 articles

Most Popular on South Sea Republic

The articles that have been viewed the most:

Most Popular Restaurants in Phoenix

Phoenix Eats Out is the restaurant review site for Phoenix, Scottsdale and Old Town Scottsdale which lists the modernist and contemporary restaurants, taverns and bars in the greater Phoenix area. This is the list of the most popular restaurants pages from phoenixeatsout.com that have been viewed the most; My personal favourite restaurants in Phoenix are AZ88, Postinos, Bomberos with Grazie, Humble Pie, Orange Table, The Vig, Fez and others coming close behind. View the complete list with the photo-journalistic style images on phoenixeatsout.com

Most Popular Hikes in Arizona

Arizona is an outdoor state and has lots of hiking in the city and around the state. Phoenix is unusual for most cities in having several large mountains in the center of the city with great hiking. Anyone who comes to Phoenix has to do the Echo Canyon trail on Camelback and the Summit Hike on Squaw Peak or Piesta Peak. The views of the city, suburbs and surrounding mountains are wonderful from Camelback and Piesta Peak. For more experienced hikers there is the McDowell Mountains in North Scottsdale that has several difficult and strenuous hikes in Tom's Thumb and Bell Pass. Alternatively, you can hike the highest mountain in Arizona. At 12,600 feet Humphrey's Peak is a long and difficult hike.

Alternate Australian Constitutions

Between 2004 and 2009 this site, southsearepublic.org, was a constitutional blog based on scoop which focused on Australian and global constitutional issues. One of the strongest aspects of it was the development of constitutions by those involved in the blog. These constitutions are the outcome: The constitutions were built using principles from Montesquieu's separation of powers, the enlightnment's universal political rights and the ancient Athenian technology of sortition and choice by lot.

Archives For South Sea Republic

South Sea Republic started in 2004 as an Australian constitutional blog in 2004 based on scoop software. It was an immigrative outgrowth of Kuro5hin. The archives for each year since then; The articles are ordered by views.

Who Is Cam Riley

Cam Riley I am an Australian living in the United States as a permanent resident. I am a software developer by trade and mostly work in Java and jump between middleware and front end. I originally worked in the New York area of the United States in telecommunications before moving to Washington DC and working in a mix of telecommunications, energy and ITS. I started my own software company before heading out to Arizona and working with Shutterfly. Since then I have joined a startup in the Phoenix area and am thoroughly enjoying myself.

I do a lot of photography which I post on this website, but also on flickr. I have a photo-journalistic website which lists the modernist and contemporary restaurants in phoenix. I have a site on the Australian Flying Corps [AFC] which has been around since the 1990s and which I unfortunately lost the .org URL to during a life event; however, it is under the www.australianflyingcorps.com URL now. The AFC website has gone through several iterations since the 90s and the two most recent are Australian Flying Corps Archives(2004-2002) and Australian Flying Corps Archives(2002-1999) which are good places to start.

Websites Worth Reading

Websites of friends, colleagues and of interest;