Our Voting System Is STILL Broken!

Please take a moment to look at these two maps, especially if you voted in the recent General Election (#GE2017).

Just as I did for the UK General Election two years ago in 2015, I’ve taken it upon myself to analyse the results and highlight the differences (and imbalance) between the First Past the Post and Proportional Representation (D’Hondt) systems.

Again, after looking at the results of the General Election in some detail it is still apparent  that our voting system in this country is very, very broken! Just to remind everyone, we don’t actually vote for parties (and therefore governments), we simply vote for our local representative. The total number of votes a party receives is not taken into consideration at all, which seems a little strange, particularly when you consider that all through the election campaigns we hear ‘Vote Conservative’ or ‘Vote SNP’, not ‘Vote Bob Smith, your local MP’.

So, as I am still a tremendous geek, I got my hands on all the numbers, created a database and generated some maps!

The first image is the results as you will have seen them using the First Past the Post method. I merely created this one for reference.

First Pas the Post 2017

The second image is the same numbers, this time evaluated using the D’Hondt method for calculating Proportional Representation. This method quite literally calculates the number of seats a party should get based on their proportion of the overall votes cast. I then assigned constituencies to each party (largest first) based on the constituencies in which they received the most votes, thus insuring that (for the most part and where possible) the local representative reflects the local preference.

Interestingly, the constituency of the Na h-Eileanan an Iar (Western Isles) in Scotland ended up with an MP from the Ulster Unionist Party… who only stand in Northern Ireland! This shows two things:

  1. It is not appropriate for local issues parties to stand in a country wide election (IMHO).
  2. My method for seat distribution under D’Hondt PR may be somewhat simplistic!

D'Hondt Proportional Representation 2017

As can be seen, the difference is astounding! The Liberal Democrats would have 48MPs not 12, UKIP would have 12MPs not 0, the Green Party would have 10MPs not 1, the SNP would have 20MPs not 35! Most importantly, The Conservative Party would have had a much harder time finding an ally to form a minority as they would have had 38 less seats and only 16 more than second party Labour.

Seeing these results, I still really don’t understand how anyone can argue against the fact that, using PR, we would have a balanced, fairer and more representative government.

Please like and share this if you agree. Lets make ourselves heard.

Also, consider getting involved by liking or joining the Electoral Reform Society (Scotland) and by lobbying your local representatives at Council, Local Assembly and Governmental level. Check out TheyWorkForYou to find out who they are!

NB. these images were made for demonstration purposes only, assumptions are made and errors happen, so if something is wrong its not intentional! These image were made my me (Rob Kent) using the Python programming language, PostgreSQL, NumPy and matplotlib with data from BBC News, the Office for National Statistics and the Ordnance Survey and OpenDataNI.

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2017/06/10/our-voting-system-is-still-broken/
RSS
Follow by Email
SHARE

Anet A8 Printer – Modifications Round 1

Anet A8 - Modifications Round 1

The first round of modifications made to my Anet A8 3D Printer

Mechanical:

Electrical:

Firmware:

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2017/06/03/anet-a8-printer-modifications-round-1/
RSS
Follow by Email
SHARE

Putting Raspbian on a diet!

Are you having problems with storage space on your Raspberry Pi? Me too!

I was recently attempting to compile OpenCV on a Raspberry Pi 3 with an 8GB SD card when it crapped out complaining of a lack of disk space. Now, OpenCV does need a lot of room to compile, but come on 8GB? Err, no. As it turns out, as the Pi has become more popular and Raspbian has evolved its picked up quite a lot of (very good) default application along the way. This is great for the Pi’s primary purpose of education, but for those of us with more advanced ambitions and aspirations it can become a problem.

Fear not dear reader, there is a solution!

You can reclaim >1.1GB of your SD Card simply by removing a whole host of programs and associated packages that are installed by default and that you probably never use. For example I run the following commands from the console:

$ sudo apt-get purge wolfram-engine libreoffice libreoffice-* nodered \
  bluej greenfoot scratch sonic-pi minecraft-pi -yq
$ sudo apt-get autoremove -yq

This removes all of LibreOffice, all of the Java IDE’s (Java? When you have Python?!), Wolfram (over 600MB!), Scratch, Sonic Pi and Minecraft. And, Voila! I can now compile OpenCV and get on with taking over the world!

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2016/10/17/putting-raspbian-on-a-diet/
RSS
Follow by Email
SHARE

Setting Up Digital Signage with a Raspberry Pi

Introduction

For a while now I’ve had some Raspberry Pi‘s (Version1, Model B) running as 3 digital signage installations. They are basically mounted on the back of two 55″ and one 32″ LG TV’s and use the USB socket on said TV’s for power and are connected via HDMI. Nice, easy and simple. Recently I decided it would be good to replace the Pi’s with the new Model 3 to take advantage of the far more powerful CPU and the integrated WiFi. This post is simply a log (mostly for myself) of how to set them up.

Method

1. Install Raspbian Jessie via NOOBS

I bought three SanDisk 8GB Class 10 Micro SD Cards from a high street retailer (they were on offer!). I then downloaded the latest version (1.9) of the NOOBS offline installer from the Raspberry Pi website, unzipped the archive and copied the contents to each of the SD Cards after the had been named and formatted using the SD Formatter 4.0 tool (I did this bit on a MacBook Pro). I then connected then connected each Pi in turn to its TV along with a keyboard and mouse, fired it up and let NOOBS do its thing WRT to installing Raspbian.

2. Setup the WiFi

The first thing I would usually do when installing a Linux system for the first time is update it, however, as I didn’t yet have a network connection, I had to setup the WiFi first. Just to make things more amusing, the available WiFi network uses a security method (PEAP-MSCHAPV2) not (yet?) automatically supported by the Pi’s WiFi utility, so I had to set this up manually. If you’re connecting to a home network you can probably just connect using the GUI utility by putting your password in.

Anywho, I had to enter the following into /etc/wpa_supplicant/wpa_supplicant.conf:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB

network={
    ssid="<SSID>"
    priority=1
    proto=RSN
    key_mgmt=WPA-EAP
    pairwise=CCMP
    auth_alg=OPEN
    eap=PEAP
    identity="<USERNAME>"
    password=hash:<PASSWORD HASH>
    phase1="peaplabel=0"
    phase2="auth=MSCHAPV2"
}

Just replace <SSID> with your network name, <USERNAME> with your username and <PASSWORD HASH> with the hash string generated using the following command:

echo -n '<PASSWORD>' | iconv -t utf16le | openssl md4 > hash.txt

Replacing <PASSWORD> with your actual password. The hash string will be saved in a file called hash.txt.

Now reboot you Pi and when it comes up, it should automatically connect to your network.

3. Update and Upgrade

Now its time for the afore mentioned updating and upgrading which I achieved using the following commands:

sudo apt-get update -y
sudo apt-get dist-upgrade -y
sudo reboot

4. Install the Unclutter package

I’ll use the unclutter package later to auto-hide the mouse pointer when its not moved (i.e. almost always). We simply install the package as follows:

sudo apt-get install unclutter -y

5. Set the Hostname

The only way I’ll be able to interact with my Pi’s once they are installed is via SSH over WiFi. On my network I have a dynamic DNS which allows me to find them via nice URL rather than IP address. For this to work, I needed to give my Pi’s a unique hostname which I did using the raspi-config tool (sudo raspi-config). Select to option 9 ‘Advanced Options’, then select option ‘A2 Hostname’, OK the resulting dialog and then enter the desired hostname. The select ‘OK’, ‘Finish’ and when asked if you’d like to do so, reboot the Pi.

6. Auto-starting the Digital Signage Application

Note: I performed the rest of these steps over SSH now that I had a hostname to contact.

My Digital Signage Application is actually just a website so what I want to do is start a web browser automatically when the Pi boots and point it at the desired page. This is done by creating an autostart desktop entry for LXDE (the window manager). First we create the necessary directory as follows:

mkdir -p ~/.config/autostart/

And then we create the file ~/.config/autostart/epiphany-browser.desktop and add the following content:

[Desktop Entry]
Name=epiphany-browser
Exec=epiphany-browser -a --profile /home/pi/.config http://www.google.co.uk
Type=application

This will launch the Epiphany Web Browser in kiosk mode and point to Google (just as an example).

7. Disable the Screensaver and Hide the Mouse Pointer

We don’t want our application going to sleep on us or the screen saver kicking in after a few minutes. Also we don’t want to see the mouse pointer sitting in the middle of our beautiful web page! So we edit the /etc/xdg/lxsession/LXDE/autostart file to read as follows:

@lxpanel --profile LXDE
@pcmanfm --desktop --profile LXDE
@xscreensaver -no-splash
@unclutter -idle 0.1 -root
@xset s noblank
@xset s off
@xset -dpms

Edit: I also seem to need to modify /etc/lightdm/lightdm.conf to stop the screen blanking as follows:

...
[SeatDefaults]
xserver-command=X -s 0 -dpms
...

8. Auto-hide the Panel

the final thing we want to do is hide the task bar, or Panel as its referred to, at the top of the screen. This is simply done by right-clicking on the panel and selecting Panel Settings. In the resulting dialog, select the Advanced tab, navigate down to the Automatic hiding section and check the ‘Minimise panel when not in use’ option. Also, set the  ‘Size when minimising’ option to 0. Ok the dialog and reboot the Pi.

Conclusion

You should not have a Pi that when booted automatically connects to WiFi, opens a web browser and points it at your favourite web page, all the while decluttering the screen and stopping the screen saver from kicking in.

Hope this useful to someone, like and share 🙂

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2016/04/30/setting-up-digital-signage-with-a-raspberry-pi/
RSS
Follow by Email
SHARE

Dropping things on app icons with Qt

I’ve spent the last year or so attempting to improve the users experience of the application I spend my (working) life developing and maintaining. This has involved many new and exciting changes, but the biggest one is the ability to just drop data and files onto the applications icon and windows rather than using dialogs to locate and import things. To do this with a Mac OSX application developed with Qt requires two steps:

  1. Subclass QApplication and reimplement the event() method
  2. Update the applications Info.plist to register associated file types

So, step 1 is relatively simple:

application.h

#ifndef APPLICATION_H
#define APPLICATION_H

#include <QApplication>

class Application : public QApplication
{
    Q_OBJECT
public:
    Application(int &argc, char** argv);
    ~Application();
protected:
    bool event(QEvent *);
private:
    void loadFile(const QString &fileName);

};

#endif // APPLICATION_H

application.cpp

#include "application.h"

#include <QFileOpenEvent>
#include <QDebug>

Application::Application(int &argc, char **argv) : QApplication(argc,argv){}
Application::~Application(){}

bool Application::event(QEvent *event){
    switch(event->type()){
    case QEvent::FileOpen:
        loadFile(static_cast<QFileOpenEvent *>(event)->file());
        return true;
    default:
        return QApplication::event(event);
    }
}

void Application::loadFile(const QString &fileName){
    qDebug() << "File Name:" << fileName;
}

You can then use this in place of QApplication, obviously after doing something more useful in the loadFile() method.

Step 2 simply involves inserting the following somewhere in your Info.plist file:

...
    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>txt</string>
            </array>
            <key>CFBundleTypeIconFile</key>
            <string>application.icns</string>
            <key>CFBundleTypeMIMETypes</key>
            <array>
                <string>text/plain</string>
            </array>
            <key>CFBundleTypeName</key>
            <string>Text</string>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
            <key>LSIsAppleDefaultForType</key>
            <false/>
        </dict>
    </array>
...

And you’re done! To automatically update the Info.plist file after the application has built rather than (forgetting to) update by hand, see my previous post about running scripts from Qt project files.

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2015/10/22/dropping-things-on-app-icons-with-qt/
RSS
Follow by Email
SHARE

Running a script post Qt build

Just sometimes you want/need to run a script after building your application to modify the output in some way (copy resources into a bundle for example). Qt of course has a way of doing this which I just discovered. I need to modify a Mac OSX bundle’s Info.plist file after compilation (I’ll explain why in my next post) and if I don’t automate it, I’ll just forget and spend hours trying to work out what I’ve (not) done! So, add the following to your Qt project file:

QMAKE_POST_LINK += $$quote($${PWD}/fix_plist.sh $${OUT_PWD} $${TARGET})

All fields that start with $$ are macros that Qt will replace with the relevant information. The $$quote bit just makes sure the command is appropriately quoted for the target OS. $${PWD} is the projects working directory where the application’s source (and my script fix_plist.sh lives), $${OUT_PWD} is the build output directory where the output bundle will live and $${TARGET} is the name of the application. The last two are passed to my script as command line arguments so I can find the app bundle and thus its Info.plist by relative path.

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2015/10/22/running-a-script-post-qt-build/
RSS
Follow by Email
SHARE

So, I just bought this on Honeymoon…

Trinette the valve trombone

Just after purchase at a Nice flea market…

DSC_0049 DSC_0048 DSC_0046

11221786_10206754730963350_4155012209397789748_n

Giving the trombone a hot bath in an effort to remove the 2nd, 3rd, 4th and tuning slides.

11855817_10206755050171330_3358973339338113136_n

All slides finally removed, its time for polishing.

Much Brasso and Vaseline later!

Much Brasso and Vaseline later!

Much Brasso and Vaseline later!

Much Brasso and Vaseline later!

Much Brasso and Vaseline later!

Much Brasso and Vaseline later!

Much Brasso and Vaseline later!

Much Brasso and Vaseline later!

 

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2015/08/11/so-i-just-bought-this-on-honeymoon/
RSS
Follow by Email
SHARE

Maths is pretty!

The below image is a collage of 48 individual images of the same Mandelbrot set drawn six different ways with eight different colour palettes.

Mandelbrot Collage

A collage of Mandelbrot set images using different colour palettes and drawing techniques.

I hope you’ll agree that some of them are truly beautiful. In fact I’m gonna create some much larger versions of a few of them because the detail and patterns are gorgeous. Just need to find a wall to hang them on…

Anywho, they were generated by me using a custom Python algorithm. I may well package this up with a GUI at some point so other people can play with the parameters and create there own pretty and unique images, but until then you’ll have to enjoy these.

Like and share 🙂

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2015/06/04/maths-is-pretty/
RSS
Follow by Email
SHARE

Python Enums as Flags

I’m a big fan of enumerated types. As someone who started there HLL programming life with C++ (my first love 🙂 ) I’ve always enjoyed how we can safely limit a variable to a range of known, named values. No more magic numbers! Also, particularly as a Qt devotee, I love how we an use enumerations like flags and create masks from them which we can then test using bitwise operators. A good example is Qt’s Alignment flags for positioning elements on screen, which might be implemented and used as follows:

#include <iostream>
using namespace std;

namespace Qt {
    enum Alignment {
        AlignLeft     = 0x0001,
        AlignRight    = 0x0002,
        AlignHCenter  = 0x0004,
        AlignJustify  = 0x0008,
        AlignTop      = 0x0020,
        AlignBottom   = 0x0040,
        AlignVCenter  = 0x0080,
        AlignBaseline = 0x0100,
        AlignCenter   = AlignVCenter|AlignHCenter
    };
    inline Alignment operator|(Alignment a, Alignment b){
        return static_cast<Alignment>(static_cast<int>(a)|static_cast<int>(b));
    }
}

int main(int argc, char *argv[]){
    Qt::Alignment align=Qt::AlignLeft;
    align=Qt::AlignTop|Qt::AlignHCenter;

    if(align&Qt::AlignTop) cout << "Align Top" << endl;

    return 0;
}

As a Python evangelist it had long been a disappointment to me that the language had no concept of enumerated types. So much so that I actually went away and designed my own! Thankfully, in Python 3.4 we now have the enum package! Yay! It’s even been back ported to Python<=3.4 as enum34! Unfortunately, this doesn’t provide support for bitwise operations, however we can easily add them. The following example shows how to implement the Alignment flag C++ example from above in Python:

from enum import Enum as _Enum

class EnumMask(object):
    def __init__(self, enum, value):
        self._enum=enum
        self._value=value

    def __and__(self, other):
        assert isinstance(other,self._enum)
        return self._value&other.bwv

    def __or__(self, other):
        assert isinstance(other,self._enum)
        return EnumMask(self._enum, self._value|other.bwv)

    def __repr__(self):
        return "<{} for {}: {}>".format(
            self.__class__.__name__,
            self._enum,
            self._value
        )

class Enum(_Enum):
    @property
    def bwv(self):
        cls=self.__class__
        idx=list(cls.__members__.values()).index(self)
        return 2**idx

    def __or__(self, other):
        return EnumMask(self.__class__, self.bwv|other.bwv)

    def __and__(self, other):
        if isinstance(other, self.__class__):
            return self.bwv&other.bwv
        elif isinstance(other, EnumMask):
            return other&self
        else: raise

if __name__=="__main__":
    class Qt(Enum):
        AlignLeft     = 0x0001
        AlignRight    = 0x0002
        AlignHCenter  = 0x0004
        AlignJustify  = 0x0008
        AlignTop      = 0x0020
        AlignBottom   = 0x0040
        AlignVCenter  = 0x0080
        AlignBaseline = 0x0100
        AlignCenter   = AlignVCenter|AlignHCenter

    align=Qt.AlignLeft
    align=Qt.AlignTop|Qt.AlignHCenter
    if align&Qt.AlignTop: print("Align Top")

This takes advantage of the fact that the enumerations are stored in order (using OrderedDict) so we can always get a unique bitwise value (bwv) for each enumeration element based on its position. EnumMask simply acts a wrapper for combinatorial values of Enums.

Hope this helps out someone else, please feel to ask questions or for more detailed explanations etc.

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2015/05/20/python-enums-as-flags/
RSS
Follow by Email
SHARE

Our Voting System Is Broken!

Please take a moment to look at these two maps, especially if you voted in the recent General Election (‪#‎GE2015‬).

After looking at the results of the General Election in some detail over the past few days it has become more apparent than ever to me that our voting system in this country is very, very broken! We don’t actually vote for parties (and therefore governments), we simply vote for our local representative. The total number of votes a party receives is not taken into consideration at all, which seems a little strange, particularly when you consider that all through the election campaigns we hear ‘Vote Conservative’ or ‘Vote SNP’, not ‘Vote Bob Smith, your local MP’.

So, being a tremendous geek, I got my hands on all the numbers, created a database and generated the following two images.

The first image is the results as you will have seen them using the First Past the Post method. I merely created this one for reference.

First Past the Post

The second image is the same numbers, this time evaluated using the D’Hondt method for calculating Proportional Representation. This method quite literally calculates the number of seats a party should get based on there proportion of the overall votes cast. I then assigned constituencies to each party (largest first) based on the constituencies in which they received the most votes, thus insuring that (for the most part and where possible) the local representative reflects the local preference.

D'Hondt Proportional Representation

As can be seen, the difference is astounding! UKIP would have 83MPs not 1, the Green Party would have 25MPs not 1, the SNP would have 31MPs not 56!

Seeing these results, I really don’t understand how anyone can argue against the fact that, using PR, we would have a balanced, fairer and more representative government.

Please like and share this if you agree. Lets make ourselves heard.

Also, consider getting involved by liking or joining the Electoral Reform Society (Scotland) and by lobbying your local representatives at Council, Local Assembly and Governmental level. Check out TheyWorkForYou to find out who they are!

NB. these images were made for demonstration purposes only, assumptions are made and errors happen, so if something is wrong its not intentional! These image were made my me (Rob Kent) using the Python programming language, SQLite, NumPy and matplotlib with data from BBC News, the Office for National Statistics and the Ordnance Survey.

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2015/05/12/our-voting-system-is-broken/
RSS
Follow by Email
SHARE