Posts

Five reasons why you should buy my old post office van

1. The most patriotic vehicle you could buy

IMG_2518It’s 2016. One hundred years ago a bunch of lads took over a post office and announced to the world our nation’s great destiny. It is your patriotic duty to commemorate these great men and women and what better way to do it than drive around in a green post office van. As Pearse wrote “there are many things more horrible than bloodshed, and not owning a van is one of them”. Commemorate the historic anniversary of the minor disruption to our postal services with the Renault Kangoo Tiocfaidh Ár Lá Centenary Edition today, together with its unique 2016 numberplate. Never forget the sacrifice of our forefathers.

2. Profit from the great gay conspiracy to destroy Irish family values

DSCF6730
Remember last year when the gays got together and mounted a well-funded campaign to undermine traditional Irish Family Values? This is your chance to benefit from some of the trillions of euro that were pumped into this country to destroy marriage, which would have remained secret but for the courageous work of Breda O’Brien. Obviously I can’t detail the secret investments that were made into this van as part of The Great Liberal Conspiracy To Force Sodomy On The Good Irish People but trust me, the gays don’t do things by halves.

3. A bold fashion statement

IMG_2519Pre-distressed clothes are so in right now. Why should your van be any different? To ensure you retain that edgy look as you drive, and to echo the edgy tones of Greg Lauren’s Spring 2016 ready-to-wear collection as breathlessly described by Vogue Magazine, I have performed some scratch detailing on left hand side of the van so you can convey a contemporary aura to the world. Sneer at the rest of the drones with their boringly unblemished means of transport as you cruise around in this fabulous example of hand-crafted pret à porter.

4. You’re not buying a van, you’re buying freedom

In the great tradition of car marketing, here’s a photo of the van in the wilds of Kerry.
DSCF6646
Don’t you feel wild and dangerous after looking at that photo? Don’t you agree that owning this van will make you more attractive to whichever gender(s) you fancy? You’re special, you’re unique, you need this van.

5. Apparently I need an odd number of paragraphs if this is to go viral

155,000km, full Renault service history, taxed till December, tested till January. Selling because we need a 3-seater van now Sheila’s dad lives with us. I’m spectacularly bad at negotiating so you can probably buy it for a lot less than it’s worth.  Live the dream, buy my van.

Identifying Irish addresses by county

My friend Emmet called me with an interesting problem today. He had a spreadsheet with 28k rows. One of the columns was an address, sort of separated by commas. The address column was very inconsistent. Some ended in Ireland, others just had the county name, some used the form “County Limerick”, others “Co. Limerick”, and others still just “Limerick”. He needed to do some calculations by county so he needed to extract the county name for each row. As I learned doing the pubs research, Irish addresses are a pain!

I’d dealt with this sort of problem before (not with 28k rows mind!) when I used to work for national charities and it used to bug me terribly.

Emmet found a way to anonymise the data so he could send me a subset. I had a play around with a spreadsheet-based solution before breaking out the Python for a quick hack.

The script below reads in a file called “input.csv” and writes to a file called “output.csv” with the same data, but with the county name and a comma added to the start of each line (or Unknown if the script couldn’t work it out).

The script is case-insensitive, and matches the rightmost county on each line, so an address in Omeath, Co. Louth is correctly identified as being in Louth, and Dublin Rd., Athlone, Co. Westmeath matches Westmeath, not Dublin.

The script is fairly flexible about the structure of the input file, so the address data can be in different columns, or all in one.

Here’s the script:

###Usage: python parse-csv.py###
###Input file must be called input.csv###


#function definition: input_text is a string, all_ireland is a bool
def prepend_address_with_county(input_text,all_ireland):
    #prepare the county list
    counties_list = ['Carlow','Cavan','Clare','Cork','Donegal','Dublin','Galway','Kerry','Kildare','Kilkenny','Laois','Leitrim','Limerick','Longford','Louth','Mayo','Meath','Monaghan','Offaly','Roscommon','Sligo','Tipperary','Waterford','Westmeath','Wexford','Wicklow']
    #add on the six counties if we want all-Ireland
    if all_ireland == True:
        counties_list.extend(['Antrim','Armagh','Derry','Down','Fermanagh','Tyrone'])
    outfile = ''
    errorcount = 0
    linecount = 0
    #loop over each line
    for line in input_text:
        linecount += 1
        #keep track of the county we're going to feed in
        county_match = ''
        #let's keep track of the index of what we have found, we want the rightmost match
        old_find_index = 0
        #loop over all counties
        for county in counties_list:
            #look for the county, starting from the RHS
            # also convert to uppercase first
            find_index = line.upper().rfind(county.upper())
            #have we found anything? (find_index will be -1 if we haven't found anything)
            if find_index > old_find_index:
                #keep the county match
                county_match = county
                #update the rightmost index count
                old_find_index = find_index
        #have we got any matches?
        if old_find_index != 0:
            outfile += county_match+","+line
        else:
            outfile += "Unknown,"+line
            errorcount += 1
    return {"output":outfile,"errors":errorcount,"lines":linecount}




file = open("input.csv" ,'rU')
output_csv = open("output.csv",'w')
result_dict = prepend_address_with_county(file,True)
percentage_error = 100*result_dict["errors"]/result_dict["lines"]
print "%d lines processed, %d Unknown counties (%.2f%%)" % (result_dict["lines"], result_dict["errors"],percentage_error)
output_csv.write(result_dict["output"])

Escape to the pub with a Raspberry Pi, a pressure mat and push notifications

My father-in-law moved in with us two weeks ago. He is a lovely kind man in his late eighties and it’s a pleasure having him around.

He has Alzheimer’s and needs someone around him all the time during the day. We’re managing this OK while juggling the needs of the business. Unfortunately he can sometimes wake up in the middle of the night in a state of anxiety because he doesn’t know where he is.  This means that Sheila and I can’t get out to the local for a quick pint even after he’s gone to bed.

The mat of freedom, with the white cable on the top left going in to our bedroom
The mat of freedom, with the white cable on the top left going in to our bedroom

Enter the lazy programmer…

There’s nothing like the prospect of a pint to stir the motivations of a hacker!  I had a Raspberry Pi lying around the house. I’d been looking for an excuse to mess around with push notifications on the iPhone for a while, and I thought I could rig something up that would send a push notification to our phones if he left his bedroom during the night.

Internet of things mats

The pressure mat
The pressure mat

Our local electronics retailer Maplin sells a pressure mat – it’s a simple switch designed to be placed under a doormat. Hooking this up to a GPIO pin on the Pi would allow me to send a notification to our phones using Apple’s Push Notification Service. Here’s the general flow:

Pressure mat -> Raspberry Pi -> Apple Servers -> our phones

Not the most complicated of hacks by any means, but if it was going to allow us to get out for a pint it would be worth it.

Setting up the Pi

The Raspberry Pi beside the bed, with wires from the pressure mat connected to GND and GPIO pin 18 via an old telephone cable
The Raspberry Pi beside our bed, with wires from the pressure mat outside the door connected to GND and GPIO pin 18 via an old telephone cable

I bought the Pi two years ago with the aim of doing a bit of tinkering over Christmas, before realising that, although the Pi is an amazing platform at an amazing price, it’s still a Linux box and I didn’t want to be tinkering with .conf files to get things working over my Christmas holidays. But I’d been feeling vaguely guilty that this credit-card sized wonder was sitting gathering dust while kids a quarter of my age around the world were using it to achieve amazing things.

I downloaded the Raspbian Linux distribution from the Raspberry Pi website – choosing the Raspbian Jessie Lite distribution as I didn’t need any graphical niceties. I was hoping I could just boot up the Pi and get its IP address from the local network but ping 255.255.255.255 didn’t show anything up and my Apple AirPort Extreme router, although rock solid and wonderful in many ways, doesn’t show a list of ethernet clients, so I had to hook up a HDMI cable to finish the setup. Setting a static IP was a bit of a pain as the network stack changed significantly last year and most of the links I found had outdated information, but there’s a very comprehensive thread on StackExchange which explains what you need to do to dhcpd.conf (note to self, recent distros include a zeroconf implementation so you should be able to do something like ssh pi@rasbperrypi.local and it should get you in to a Pi with a fresh OS install)

Processing a push notification with an iOS device

This was actually the easiest bit of the whole process. Apple’s docs on push notifications are really good.

Here’s the entirety of the code of the iOS app, pretty much taken verbatim from Apple’s example code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // bitwise OR to include all notification types
    UIUserNotificationType types = (UIUserNotificationType) (UIUserNotificationTypeBadge |
                                                             UIUserNotificationTypeSound | UIUserNotificationTypeAlert);
    //register these notification types
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    // Register for remote notifications -- this will prompt the user to allow notifications
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    return YES;
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //triggered when user allows notifications
    //Log the token
    NSLog(@"device token: %@",deviceToken);
    // Also store the token in NSUserDefaults
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:deviceToken forKey:@"deviceToken"];
    [defaults synchronize];
}

I wrote the device token to NSUserDefaults in case I wanted to display it in the app, but I took the lazy way out and just printed it with an NSLog statement, so I could copy it into my Python script.

Sending a push notification with a Python script

Here’s my Python script that detects someone stepping on to the mat, and which sends a request to Apple’s APNS server:

import RPi.GPIO as GPIO
import time
import datetime
import socket
from apns import APNs, Frame, Payload

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# our pressure mat is connected to GPIO pin 18
button = 18

# setup the pin as input, and enable the pullup resister
# this means when the switch is pressed, it will read GND, i.e. False
GPIO.setup(button, GPIO.IN, GPIO.PUD_UP)

# insert the tokens you NSLogged from your iOS app here - long lines of hex
token_hex = ''
sheila_token = ''
# setting the payload here - we just want the default sound, and we don't care
# what the badge says so we'll just set it to 1 each time
payload = Payload(alert="Joe is on the move!", sound="default", badge=1)

# run in an infinite loop
while True:
    # if switch is pressed (reading False - see note on GPIO.setup() above)
    if GPIO.input(button) == False:
        #logging for debugging
        print str(datetime.datetime.now()), "button pressed"
        #create the push notification object
        apns = APNs(use_sandbox=True, cert_file='push-notification-cert.pem', key_file='push-notification-key.pem')
        time.sleep(1)
        # wrapping this in a try/except block as the script was occasionally
        # barfing on a socket error
        try:
            apns.gateway_server.send_notification(sheila_token, payload)
        except socket.error, (value, message):
            print str(datetime.datetime.now()),"Socket Error", message
            #recreate the apns object
            apns = APNs(use_sandbox=True, cert_file='push-notification-cert.pem', key_file='push-notification-key.pem')
        time.sleep(1)
        #we're done with Sheila's phone, now let's do the same for mine
        try:
            apns.gateway_server.send_notification(token_hex, payload)
        except socket.error, (value, message):
            print str(datetime.datetime.now()),"Socket Error", message
        time.sleep(10)

Apple recently changed their push notification protocol to a brand new version, which I tried to connect to using a Python HTTP/2 library called Hyper – it’s labelled as a ‘very early alpha’ and it may work very well but after a few hours of trying to create the HTTP/2 request I was still getting errors so I used a library that uses the old protocol called PyAPNS which worked fine although I had to insert a few sleep() statements to avoid some socket errors.  I also had to do some fandangling with the push notification certificate, splitting up the .p12 file into a certificate and key in Keychain Access to use with the script.

My Linux skills are a bit rusty so it took a while to remember to type screen then <CTRL-A> d to detach a separate terminal which would run even after I logged out of the SSH session.

It works!

Notification on my phone's lock screen when the mat is stepped on
Notification on my phone’s lock screen when the mat is stepped on

For all the ugly hacking, it seems to work! Sheila and I can nip down for a quick pint to our local knowing that we can quickly return home if her dad starts wandering.

Further work

I spliced in an old telephone cable to connect the pressure mat outside the door with the Raspberry Pi beside my bed. I was in a rush so I used sellotape! Aside from tidying that up into something a little less ugly, here’s the things I’d like to do next with the project

  1. Replace the Raspberry Pi with something like an ESP8266 module that could run off a battery, so I don’t need trailing wires. This post from Stavros Korokithakis shows how he recreated an Amazon Dash button using an ESP8266 looks promising.
  2. Using the ESP8266 would mean that I would have to handle the push notification logic on an external server, so that the ESP8266 would send a HTTP request to a Flask server which would send the request to Apple.
  3. Having the logic on the server means that I could log the data to a database, which means we could track how often the night interruptions were happening.
  4. which reminds me I should enter some logic so that the script only does push notifications and logging at night, sometimes when we’re going in and out of his room to do washing our phones go crazy!

Limerick City candidates answer my questions

I posted a list of all the candidates running in Limerick City, together with a list of questions. Only three candidates responded: James Gaffney, Jan O’Sullivan and Michael Noonan. Here are their answers.

James Gaffney, Green Party

1. How seriously should we take climate change, and what specific policy measures do you think we should take to combat climate change? I’m particularly interested in measures you think that might slow economic growth in the short term but which would have long-term positive effects for our country.

We are the first generation to feel the effects of Climate Change, and the last who can do anything meaningful about it.

The need to address long-term problems, such as climate change, is an overarching value of the Green Party. We support the enactment of national legislation to respond to climate change and transition to a low-carbon, climate-resilient economy. This will reduce our over-dependence on imported sources of fossil fuel energy. Global events related to extreme weather, such as storms and droughts, could compromise our food security and lead to increased immigration into Ireland by ‘climate refugees’.

By 2050, Ireland’s power, heat and transport systems should no longer rely on fossil fuels and our agricultural system should achieve carbon neutrality. This is technologically possible, and would result in greater employment, energy efficiency, security, an improved economy, and improved public health, in addition to contributing to a healthier climate
We need to establish ambitious but realistic binding national greenhouse gas emission reduction targets for 2030 and aim for 100% decarbonisation of the power system and an 80% overall reduction in national emissions by 2050

You mention measures that might slow economic growth in the short-term, however I believe that an Irish economy that is carbon-neutral will be a stronger one. The €5.7 billion a year that we spend on fossil fuels could be kept in our economy rather than going to oil-producing nations. We will also gain a competitive advantage from moving faster than other nations on climate change.

2. Our regional towns and cities are suffering. Here in Limerick we’ve seen our city as well as the villages in our county undermined by ribbon-development and one-off housing in the countryside. How do you think we should balance people’s desires to build where they want, with the need for better planning that avoids sprawl and strengthens our villages, towns and cities?

We need a National Spatial Plan with climate change as a foundation stone.  Any plan that relies on fossil fuels as the driver of an economy will see us falling behind, as the rest of the world switches to a cleaner renewable future. Any plan that thinks Ireland can set the course of our own destiny without an appreciation of global trends is fraught with risk.

In my manifesto I talk about the need for a Regional Authority which would have responsibility for leading on a spatial plan for the Mid-West that would focus on Limerick City as a destination for families and businesses.

The only plan that can succeed is a truly long term one.

Our new national plan puts proper spatial planning at its core. Where we think ahead and plan our public infrastructure so that people from all over Ireland can live and work where there are services and communities. Where we focus on what we can do best at home – in tourism, agri-food, energy, manufacturing and new digital services; where we restore the traditional values of banking to every part of the country so we support sustainable, well paid jobs.
Ours is an investment plan for the next generation.

This election debate is about much more than the fiscal space. It is about the public space.
Whoever is in power in the next Dáil will put resources into the areas that they value. So that’s the question people need to ask of themselves and of politicians as we near polling day.

3. Do you agree with tougher sentencing for criminals, or more rehabilitation? I’m particularly interested in your position on how we should approach drug addiction within the justice system.

We need an after prison support system, with one agency coordinating fully integrated supports for accommodation, education, employment.

We should increase crime preventative measures, e.g. increasing the age limit for the application of the Garda Youth Diversion to 18-24 year olds.

On drug addiction, I feel strongly that this is a medical issue, not a criminal justice issue.

Jan O’Sullivan, Labour Party

1. How seriously should we take climate change, and what specific policy measures do you think we should take to combat climate change? I’m particularly interested in measures you think that might slow economic growth in the short term but which would have long-term positive effects for our country.

I think climate change is one of the most serious issues facing the global population today. During my time as Minister for Trade and Overseas Development Aid I saw at first hand the damage it visits on some of the poorest communities on the planet. I was also proud to work with NGOs and Departmental officials to ensure that tackling climate change had a central role in our Overseas Development Aid policy.

Of course climate change is not just an issue that effects the developing world. Long-term analysis of data demonstrates that our climate is warming with all that this entails, including rising sea levels.

I fully support the climate change legislation that was passed (with all-party support) in the Oireachtas last December. The statutory frameworks established by that legislation (including five yearly national mitigation plans and five yearly national adaptation frameworks) will provide a clear roadmap on what we need to do to reduce greenhouse gas emissions and also the steps we need to take to plan for a changing climate.

The legislation will also establish the Climate Change Advisory Council on a statutory basis.
In relation to economic growth I don’t think the issue actually revolves around the rate of economic growth. I think that all activity needs to be sustainable and that smart, green solutions can ensure that economic growth and job creation can go hand-in-hand with good environmental practices.

2. Our regional towns and cities are suffering. Here in Limerick we’ve seen our city as well as the villages in our county undermined by ribbon-development and one-off housing in the countryside. How do you think we should balance people’s desires to build where they want, with the need for better planning that avoids sprawl and strengthens our villages, towns and cities?

The points you raise are very valid. Poor planning decisions can blight a community for decades, even generations.

Planning and development needs to be driven by a long-term vision for a community – not just the demands of one particular sector.

As a former Minister for Housing and Planning I think my track record shows I deliver on these principles.

I oversaw a process that dezoned land which could have accommodated more than 500,000 houses. This was done to limit urban sprawl and to ensure that future development is concentrated in our towns and villages.

Also, in my first nine months as Minister I used my powers under Section 31 of the Planning and Development Act on three occasions to overturn decisions contrary to good planning. The specific issues involved zoning for development on flood plains, in areas isolated from towns and zoning that threatened wildlife habitats. In the 10 years before I took office this power was only used eight times.

I also dedicated a significant amount of time and energy to tackling the legacy of unfinished housing developments across the country, a process that has resulted in a 75% reduction in the number of these estates over the past five years.

In my opinion that Development Plan is the most powerful tool to ensure proper planning and development. New planning legislation which is in the pipeline will establish a planning regulator which I fully support. In addition to its investigative functions the regulator will have an education role which I think is vital. At local authority level and in our communities we need to have the knowledge and tools to make locally-based, informed decisions about plans that will impact on our community for decades.

3. Do you agree with tougher sentencing for criminals, or more rehabilitation? I’m particularly interested in your position on how we should approach drug addiction within the justice system.

 

I support judicial discretion in sentencing. While sometimes this can be frustrating I acknowledge that judges hear all the facts of a case during trial and post-conviction details and I think that they are best placed to decide on the length of sentence.

I also fully support acknowledging the medical as well as the criminal aspect of addiction and that this needs to be tackled if individuals and communities are to get relief from the tragedy that alcohol and drug addiction can inflict.

In that regard I have supported my colleague Minister Aodhan O’Riordain’s efforts to establish safe facilities for those who are addicted to drugs where they can also come in contact with services that can assist them.

Michael Noonan, Fine Gael

1. How seriously should we take climate change, and what specific policy measures do you think we should take to combat climate change? I’m particularly interested in measures you think that might slow economic growth in the short term but which would have long-term positive effects for our country.

2. Our regional towns and cities are suffering. Here in Limerick we’ve seen our city as well as the villages in our county undermined by ribbon-development and one-off housing in the countryside. How do you think we should balance people’s desires to build where they want, with the need for better planning that avoids sprawl and strengthens our villages, towns and cities?

3. Do you agree with tougher sentencing for criminals, or more rehabilitation? I’m particularly interested in your position on how we should approach drug addiction within the justice system.

I attach a copy of the Fine Gael Election Manifesto which I trust clarifies the matters you have raised in your correspondence.

Email the General Election 2016 candidates in Limerick City

There will be a general election in February 2016.

In Limerick City, there are currently 8 people looking for our vote.

If we don’t ask questions about things that are important to us, we let the media and focus groups do the asking for us.

I know politics is boring for most people but here are 3 very quick things you can do to exercise your democratic rights:

  1. Check that you’re registered to vote (and remember to vote of course!)
  2. Take the smartvote.ie quiz which attempts to match you to candidates based on your response to certain questions
  3. Email the candidates in your constituency with questions about issues that are important to you.

Here are the email addresses of all the candidates running in Limerick City (alphabetical order!), all nicely formatted so you can paste it into your email client

James Gaffney Green Party <jamescbgaffney@gmail.com>,
Sarah Jane Hennelly Social Democrats <sarahjanehennelly@gmail.com>,
Michael Noonan Fine Gael <minister@finance.gov.ie>,
Willie O’Dea Fianna Fail <willie.odea@oireachtas.ie>,
Kieran O’Donnell Fine Gael <kieran.odonnell@oireachtas.ie>,
Jan O’Sullivan Labour <jan.osullivan@oireachtas.ie>,
Cian Prendiville Anti Austerity Alliance <cian.prendiville@limerick.ie>,
Maurice Quinlivan Sinn Fein <cllrmauricequinlivan@gmail.com>

Or, here’s an email link that should open in your email client, with the To: and Subject: fields filled out for you.

 

Even though I’ve decided on my first preference, I still have to rank everyone else from 2 to 8. I’ve done similar emails in previous elections and the responses have really helped me to decide how to vote.

Here’s my email (I’ll update this post with any responses)

Hi there,

I’m emailing you because you’re running for election in Limerick City. In case you don’t get chance to call to our house in Farranshone, I’d like to ask you a few questions (plus, this way we both get to keep warm and dry!):

  1. Climate Change:
    How seriously should we take climate change, and what specific policy measures do you think we should take to combat climate change? I’m particularly interested in measures you think that might slow economic growth in the short term but which would have long-term positive effects for our country.
  2. Our villages, towns and cities:
    Our regional towns and cities are suffering. Here in Limerick we’ve seen our city as well as the villages in our county undermined by ribbon-development and one-off housing in the countryside. How do you think we should balance people’s desires to build where they want, with the need for better planning that avoids sprawl and strengthens our villages, towns and cities?
  3. Crime:
    Do you agree with tougher sentencing for criminals, or more rehabilitation? I’m particularly interested in your position on how we should approach drug addiction within the justice system.

Thanks in advance for taking the time to answer my questions, and wishing you the very best of luck on the campaign trail,

Thomas.

Why I’m Green

Politics is a minority sport in some ways. Less than 2% of Irish people are members of a political party. I’m one of those wonks, paying my membership dues to the Irish Green Party for the last 9 years.

I blame my wife for joining. It was the day after the election in 2007, and as the early tallies were coming in, it was clear that Bertie Ahern’s Fianna Fail had won a spectacular electoral comeback. The Greens, who we’d voted for, had a disappointing election, retaining its representation of 6 Dáil seats. We were disgusted that populist politics had won out once again.  “Right, that’s it”, I was told as my wife stormed in the door. “We’re doing something about this.  We’re joining the Greens”.

I remember the first few meetings we went to in Dublin, before we moved to Limerick.  What struck me about my fellow members was the ways they were so different from each other: I remember solicitors discussing the intricacies of public transport routes with chefs: youth workers arguing about primary health care with software developers. Despite their differences I could see a huge amount in common: the commitment to evidence-based policies; the strong sense that every political change should decrease inequality; a desire to do the right thing in the long-term, even if it wasn’t popular in the short.

IMG_8987
As the Greens have no staff, we run completely on the efforts of volunteers, most of whom thankfully have more ability than the slightly hapless guy pictured above…

I stated earlier that politics is a minority sport, I also think that sometimes we treat politics too much like a sport.  Far too often media covers politics in the manner of which ‘team’ is doing better than another; partisans flood social media with reasons why their side is better than the other shower; soundbites from leaders dominate the discourse.

Yet politics can and should be about something else: the ideas which will shape the future of our society; the collective priorities we want to emphasise;  the rewarding of work and the protection of those who cannot.

And the big one: climate change – the one area where I fear the Irish political system’s tendency to short-termism and populism will lead to significant hardship for future generations.

Between local and national campaigns, next month’s general election will be my fourth time knocking on doors for Green candidates, this time for the fantastic candidate we have running in Limerick City, James Gaffney.  James represents everything I joined the Green Party for: thoughtful, respectful, not afraid to campaign on unpopular issues if they represent the right long-term vision for our country. I know there are many who are pessimistic about the power of politics to change things, but I’ll be knocking on the doors of the voters in Limerick City over the next two months with the firm belief that the Green Party offers a long term vision for a sustainable future.

Where in Ireland has the most pubs per person?

pubs2If you’re in a hurry, the answer is Liscannor, Co. Clare.  5 pubs for 129 people, or 1 pub for every 26 people. And on the other extreme, the town in Ireland with the fewest pubs is Greystones, with 4 pubs for 11,194 people, or 1 pub for every 2799 people.

The wonderful infographic was made by my friend Gimena who is an extremely talented interface designer – check out her portfolio.

There’s a lovely cycleway called the Great Southern Trail in County Limerick, and we cycled the western end of it a few weeks ago, ending in Abbeyfeale, a small town on the Limerick/Kerry border.  Growing up down the road in Adare, I remember people claiming that Abbeyfeale had the most pubs per head in Ireland.  Walking round in search of a pint to reward my cycling efforts I wondered, was this true? Barstool talk was all we had in the nineties, but surely someone had done a bit of a study since.  A half an hour of web searching later, all I could come up with was a few forum posts essentially containing the same barstool talk as I’d come across before.

Cycling back I had a bit of time to think about this.  I knew the Central Statistics Office (CSO) had the population of each town, but how to get a list of pubs?  I had been looking for an excuse to fool around with a bit of Python, and this seemed like the perfect chance to write a small web scraper to get the data.  There is a Vintner’s Association of pubs which had a membership list, and the Golden Pages (our equivalent of the Yellow Pages) had a pretty comprehensive list of businesses with a landline (every business with a landline gets a free listing).

I was all ready to write my little scraper when my friend Emmet pointed out that because running a pub is a licenced business, there was probably a public list, and there was, on the Revenue Commissioner’s site.  It was even available as an Excel file, with the address lines in separate columns!  My excitement quickly waned as I waded through the horrible morass that is Irish addresses.  My original idea was to get the data into a database so I could do some fun analysis – now I was definitely stuck in Excel as this job was 95% cleaning data. Fortunately I managed to harangue Emmet into helping me with some Excel tips and tricks.

I was reminded why we have the most amazing national statistics office here in Ireland.  Not only because they are unfailingly helpful whenever I have had cause to contact them over the years (not wanting to indulge in waste of taxpayer’s money I decided not to contact them asking for help with this particular project).  But mostly because we in Ireland are an absolute mess when it comes to addresses.  How the CSO manage to count anything in this country is a mystery.  Not only until this year we were one of the only rich countries not to have a postcode system, but consider the following points when I was cleaning up the pub data:

  • Irish is our first official language, so every address has two completely separate legal forms, both of which are equally valid.
  • Either the Irish or the English name is picked as the ‘official name’, but this has little to do with what is used in reality.
  • Dingle is officially (and slightly controversially) ‘An Daingean’ because it is part of the Irish-speaking Gaeltacht.  Yet all 38 pubs use ‘Dingle’ as their address.  Maryborough is listed as the English language equivalent of Portlaoise (not in an Irish speaking area), yet all 34 pubs use the Irish form
  • Many places cannot even agree with themselves how they are spelt.  There are 9 pubs in Louisburgh, Mayo, yet 4 spell it ‘Louisbourgh’ and one other spells it ‘Louisburg’
  • 3 pubs in Co. Limerick are in ‘Dromcollogher, 2 are in ‘Drumcollogher’, yet some of the signs on the way in to town say ‘Dromcolliher’
  • Pubs in Roosky put their address down as Roosky, Carrick-on-Shannon, Co. Roscommon.  No matter that Carrick-on-Shannon is in Co. Leitrim, that’s where their local post office is.  But I was getting a few pubs in Carrick-on-Shannon, Co. Leitrim and a few in Carrick-on-Shannon, Co. Roscommon, and they all had to be cleaned up. This is surprisingly common.
  • Sometimes locals completely ignore the official spelling for their town, for example Pallas Grean in Co. Limerick vs. Pallasgreen.
  • Many of our towns have boundaries defined in Victorian times.  For consistency, these populations are listed separately.  So there are rows upon rows of separate population entries for ‘Loughrea Legal Town’ and ‘Loughrea Environs’
  • We don’t even have a good definition for what a town is.  The CSO have their own definition, which must be a huge amount of work for them: a census town “is defined as being a cluster with a minimum of 50 occupied dwellings, with a maximum distance between any dwelling and the building closest to it of 100 metres, and where there was evidence of an urban centre (shop, school etc)”

After a large amount of address-wrangling, I got my data cleaned up somewhat.  I discarded all the local authority subdivisions of Dublin to just cater for one county of Dublin.  Out of 7,745 licenced pubs and hotels in Ireland, I managed to match up all but 990 of them to a census town, and many of these would not have a match anyway (e.g. if their address was listed as a suburb of a bigger town, like Mahon in Cork, or if they were in a settlement too small to be considered a census town)

The raw data gave the top 10 as follows:

Town Population Number of pubs Number of people per pub
Feakle, Clare 113 7 16.1
Liscannor, Clare 129 7 18.4
Lifford, Donegal 1658 55 30.1
Waterville, Kerry 232 7 33.1
Doonbeg, Clare 272 8 34.0
Castlegregory, Kerry 243 7 34.7
Cong, Mayo 178 5 35.6
Knocktopher, Kilkenny 144 4 36.0
Ballyvaughan, Clare 258 7 36.9
Sneem, Kerry 258 7 36.9

Yet it was ultimately Liscannor, and not Feakle, that I judged the winner of my ‘most pubs per capita’ award. The answer again comes down to post office locations: in rural Ireland the second-last line of your address is normally your local post office.  So even though 7 pubs had Feakle as their address, at least 3 were a long way outside Feakle in another village.  But second on my list was Liscannor: even though 2 of its 7 pubs were a small way outside near St. Bridget’s Well on the way to the Cliffs of Moher, 5 hostelries (4 pubs and 1 hotel) were definitely within the small village of 129 people, giving an incredible ratio of 1 pub for every 26 people.

Legitimate data analysis tools
Legitimate data analysis tools

I gave up at this point, satisfied that I had my winner.  But I was a bit sorry I didn’t get the data cleaned up a bit more – in particular 3rd place Lifford with an incredible 55 pubs for under 1700 people sounded fascinating – but my lack of knowledge about Donegal local geography prevented me from cleaning the data much further (I suspect some of these 55 pubs were in villages outside of Lifford).

I’ve provided the cleaned data files for both towns by population and pubs by address in case anyone else wants to have a go.  The two files can be joined in a spreadsheet with a simple COUNTIF statement or similar. I’m not sure about the copyright status of either file, the pubs file is based on publicly available data about commercial businesses, and equally the CSO data is publicly available, but I’m not sure under what licence.  Any changes I have made to the original data you may use in the spirit of finding a good place to go boozing.

Original data sources:

Getting generic Arduino boards with CH340G chips to work with OS X 10.11 El Capitan

This evening my project was to get a generic Arduino Mega board that Baz ordered from China working with my MacBook Air running El Capitan. Plugging the board in and launching the Arduino IDE yielded nothing in Tools -> Port.

After a lot of searching, it seems like the problem is the USB to serial chip used on this Arduino clone is a CH340G chip, not the usual FTDI chip that ships with official Arduino boards.  This chip handles the communication between the USB connection and the serial interface to the Arduino board. Unfortunately it is not recognised by OSX.

ch340g-arduino
Note the CH340G chip on the top left

There is a driver online, provided by a Chinese manufacturer, which provides a kernel extension (ktext) to recognise the chip. Unfortunately the ktext is not signed.  Previous versions of OS X would let you disable the requirement for ktext signing by typing a sudo command in Terminal, but with El Capitan you have to boot to the recovery partition to disable the System Integrity Protection (SIP) which prevents unsigned ktexts from running.

Disabling SIP is a really bad idea! Fortunately there is a company called CodeBender which produces a plugin for Firefox and Chrome that gives you an in-browser Arduino IDE. They have released a signed ktext for the CH340G chips so you don’t have to mess around with the security settings on your Mac. It’s not possible to download the drivers directly, but if you install their add-on in Firefox or Chrome (doesn’t work in Safari), you’ll get a link to install the drivers. When you next launch the Arduino IDE, you’ll see your generic Arduino listed in the Tools > Port menu.

Here’s the link to install the add-on.

 

Using the KYX-5461AS 4-digit 7-segment LED display with Arduino

This part came with an Arduino starter kit bought in preparation for the first Limerick Hackathon. It was really difficult to find information on the web about this part.

KYX-5461AS

The part description said that this was a common Anode display, which is wrong, it’s a common cathode. This means that you need to connect resistors to the pins driving each digit (rather than each segment pin with a common anode) to avoid blowing the LEDs.

Here’s the pinout:

1 Segment E
2 Segment D
3 Decimal point
4 Segment C
5 Segment G
6 Digit 4
7 Segment B
8 Digit 3
9 Digit 2
10 Segment F
11 Segment A
12 Digit 1

Segment labels (I can never seem to remember these):
7 segment display labeled
So to display a number 1 on the third digit you would power pins 4, 7 and 8.

To display numbers on all 4 digits, you need to introduce a delay in between powering each digit in your loop() block.

To test I rigged up a LM35 temperature sensor to an Arduino board and displayed the temperature on the display. The display was a bit dim as the lowest resistors I had were 1kΩ which were too high.

temperature-sensor

Here’s the quick code I wrote to read the temperature from a LM35 temperature sensor and display it on the KYX-5461AS display.

//reading temperature and outputting to display
int sensorPin = 0;

//display pins
int segA = 5;
int segB = 13;
int segC = 10;

int segD = 8;
int segE = 7;
int segF = 4;
int segG = 11;
int segPt = 9;

int d1 = 6;

int d2 = 3;
int d3 = 2;
int d4 = 12;

int delayTime = 900;

int counter = 0;

float temperature = 77.7;

void setup() {
// put your setup code here, to run once:
//start serial communications
Serial.begin(9600);

//set up outputs
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
pinMode(7, OUTPUT);
pinMode(6, OUTPUT);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);
pinMode(3, OUTPUT);
pinMode(2, OUTPUT);
pinMode(13, OUTPUT);
pinMode(0,INPUT);
delay(1000);
}

void loop() {

// put your main code here, to run repeatedly:

//only read temp every 100 cycles
if(counter%500 == 0)
{
// read the pin
int reading = analogRead(sensorPin);
//convert reading to volts
float volts = (reading * 5.0);
volts /= 1024.0;
// Serial.print(volts);
// Serial.println(" v");
temperature = volts * 100.0;
Serial.print(temperature);
Serial.println(" degrees Celsius");

//test output to display
// allHigh();
//reset our counter
counter = 0;
}

counter ++;

selectDigit(1);
sendDigit(tens(temperature));
delayMicroseconds(delayTime);

digitalWrite(d1, HIGH);
selectDigit(2);
sendDigit(ones(temperature));
point();
delayMicroseconds(delayTime);

digitalWrite(d2, HIGH);
selectDigit(3);
sendDigit(points(temperature));
delayMicroseconds(delayTime);
//turn point off

digitalWrite(d3, HIGH);
digitalWrite(segPt,HIGH);
selectDigit(4);
cee();
delayMicroseconds(delayTime);
digitalWrite(d4, HIGH);



}

void allLow() {

digitalWrite( 13, LOW); // A
digitalWrite( 2, LOW); // B
digitalWrite( 3, LOW); // C
digitalWrite(4, LOW); // D
digitalWrite(5, LOW); // E
digitalWrite( 6, LOW); // F
digitalWrite( 7, LOW); // G
digitalWrite(8, LOW); //point
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);

}

void allHigh() {

digitalWrite( 13, HIGH); // A
digitalWrite( 2, HIGH); // B
digitalWrite( 3, HIGH); // C
digitalWrite(4, HIGH); // D
digitalWrite(5, HIGH); // E
digitalWrite( 6, HIGH); // F
digitalWrite( 7, HIGH); // G
digitalWrite(8, HIGH); //point
digitalWrite(9, HIGH);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);

}

void one()
{
digitalWrite(segA, LOW);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, LOW);
digitalWrite(segE, LOW);
digitalWrite(segF, LOW);
digitalWrite(segG, LOW);
digitalWrite(segPt, LOW);

}
void two()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, LOW);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, LOW);
digitalWrite(segG, HIGH);
digitalWrite(segPt, LOW);

}
void three()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, LOW);
digitalWrite(segF, LOW);
digitalWrite(segG, HIGH);
digitalWrite(segPt, LOW);

}
void four()
{
digitalWrite(segA, LOW);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, LOW);
digitalWrite(segE, LOW);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
digitalWrite(segPt, LOW);

}
void five()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, LOW);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, LOW);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
digitalWrite(segPt, LOW);

}
void six()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, LOW);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
digitalWrite(segPt, LOW);

}
void seven()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, LOW);
digitalWrite(segE, LOW);
digitalWrite(segF, LOW);
digitalWrite(segG, LOW);
digitalWrite(segPt, LOW);

}
void eight()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
digitalWrite(segPt, LOW);

}
void nine()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, LOW);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
digitalWrite(segPt, LOW);

}
void zero()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, HIGH);
digitalWrite(segG, LOW);
digitalWrite(segPt, LOW);

}

void cee()
{
digitalWrite(segA, HIGH);
digitalWrite(segB, LOW);
digitalWrite(segC, LOW);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, HIGH);
digitalWrite(segG, LOW);
digitalWrite(segPt, LOW);
}

void point()
{
digitalWrite(segPt, HIGH);
}

void selectDigit(int d)
{
/*
digitalWrite(d1,HIGH);

digitalWrite(d2,HIGH);
digitalWrite(d3,HIGH);
digitalWrite(d4,HIGH);
*/

switch (d)
{
case 1:
digitalWrite(d1, LOW);
break;
case 2:
digitalWrite(d2, LOW);
break;
case 3:
digitalWrite(d3, LOW);
break;
default:
digitalWrite(d4, LOW);
break;
}
}

void sendDigit(int x)
{
switch(x)
{
case 1:
one();
break;
case 2:
two();
break;
case 3:
three();
break;
case 4:
four();
break;
case 5:
five();
break;
case 6:
six();
break;
case 7:
seven();
break;
case 8:
eight();
break;
case 9:
nine();
break;
case 10:
cee();
break;
default:
zero();
break;
}
}

int tens(float x)
{
float divided = x/10.0;
return (int)divided;
}

int ones(float x)
{
float divided = x - (10.0 * tens(x));
// Serial.print(divided);
// Serial.println(" ***ones***");
return (int)divided;
}

int points(float x)
{
float divided = x - (10.0 * tens(x)) - ones(x);
divided *= 10;
return (int)divided;
}

Paying for water is a good thing

Vartry Reservoir
Vartry Reservoir, a large public works project of the 1800s which helped combat cholera in Dublin. Image from Wikimedia Commons.

We Won’t Pay. That’s the slogan of the Right2Water movement, who are opposed to any water charges for residential households. Thousands of people marched in Dublin recently under the this banner, one of a series of protests since Ireland announced it was going to be one of the last rich countries to introduce water charges. It is clear that the introduction of water charges has made people very angry indeed.

I’ve spoken to friends of mine whose opinions I deeply respect, who plan not to pay their water charges. I’ve read the arguments of people who think water charges are wrong, and although they are wide ranging (fears about privatisation, claims that we already pay for water, accusations of waste), they can all be summarised under the effectively concise slogan: “We Won’t Pay”.

I think they’re wrong. And that is a deeply unpopular thought to have.

I don’t think there is a single person who would agree that the current system introduced is problem-free. But I find the “We Won’t Pay” mantra deeply troubling. It represents such a depressing and nihilistic view of what we can accomplish together.

Most people agree that our water infrastructure is pretty awful in this country. We were cutting off the water supply in our capital city because reserves were so low. The water supply has been undrinkable in certain parts of the country for years. There’s a phrase that pops up with depressing regularity in Irish politics: “decades of underinvestment”, which is certainly true of our water supply. I think the reason for this comes down to our attitude towards the State and its capacity to make things better for its citizens.

Rewind to 1977, when we had a General Election. The party then in opposition, Fianna Fáil, didn’t think that it had a chance of winning thanks to some creative gerrymandering of constituencies by the Fine Gael/Labour government (christened the Tullymander). Perhaps because of this, their manifesto was deeply populist and fiscally irresponsible. Included were commitments to abolish local taxation (‘rates’) and motor tax, resulting in a massive and unexpected majority for Fianna Fail. Because this resulted in a large loss of income for local authorities who were responsible for, amongst other things, water supply and sewerage, we are left now with a water system that is not fit for purpose. Of course the difference could have been made up at any time in subsequent decades by an increase in investment at a national level, successive governments ignored long-term infrastructure in favour of policies that would directly increase the cash in voters’ pockets.

It is pretty much universally acknowledged that the 1977 Fianna Fáil manifesto was a disaster for the country. But forty years later we are still holding the same attitudes, which are neatly summed up as “We Won’t Pay”: receive the most you can from government, and pay the least. This is reinforced by an attitude that government is filled with corrupt, venal individuals who must be trusted as little as possible.

“We Won’t Pay” strikes me as appallingly reductionist. It gives us no hope that we can work together as a country to improve equality in this generation, and improve opportunity for future generations. We are so focused on paying as little as possible that we give up so many opportunities to make things better.

Paying for water is a good thing. It allows us to spend more on our water infrastructure, preventing waste in the mains supply. The introduction of domestic metering has allowed us to identify waste inside our homes, as well as providing valuable employment across the country. Could we pay for water in a better way? Of course. Personally I’d like to see greater incentives for conservation, and an investigation of ways that we can make water charges less regressive to people on low incomes. But to dismiss the very concept of charging for water with the phrase “We Won’t Pay” means we’re left with a peculiarly right-wing (pay less taxes and charges, don’t trust the government) view of the world which leaves us with leaks, contamination, and the unappealing prospect of draining water from the River Shannon to meet the water needs of our capital.

The attitude of “We Won’t Pay”, means that we will get governments who prioritise the short term over the long term, who will pursue populism over justice, and who will continue to store up problems for future generations to deal with. Deeply unpopular it may be, but I believe that paying for water is a good thing.