Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Sunday, 22 November 2009

'If at first you don't succeed', or 'why I'm not renewing my subscription to Let's Knit!'

Started over on my Fair Isle project on Friday. Not for any reason related to the fact that this is my first such project or through any other error on my part. My gauge was spot on, I'd spotted some glaring errors in the charts before I got to them and things were altogether going quite well, until... I let someone who wasn't me try the item on. I am a rather small person and the item in question is a gift for a normal sized person. Much like anything I knit from this particular magazine, the item was correctly sized in one direction (in this case, length) but not in the other (width).

Ripped back the whole thing, made a few adjustments to the pattern to fix the sizing issue (I hope, I haven't got that far yet) and took the opportunity to fix the roll on the stocking stitch edge. I've also redrawn the chart without the mistakes (finding another three incorrectly drawn stitches as I did) and with the colours inverted so the white boxes represent the lighter yarn and the dark boxes the darker yarn. I couldn't get this online chart maker to play nicely enough not to drive me mad so ended up drawing the chart in a combination of editors (GIMP, MSPaint and Paintshop - a Mac imitation of MSPaint). Very pleased with the finished result but time consuming, so the lovely Hobnob is making me my own in-browser chart maker; he is good to me :)

Anyway, here is the reincarnated Fair Isle as it stands at bedtime this evening (or yesterday evening, I'm not sure how I refer to a time that has quite clearly passed me by - I blame Hobnob, he's in the coding groove).

Thursday, 9 July 2009

Dynamic Module Loading using Python

Suppose I have a number of supported database engines which I keep in a dictionary like so:

db_libs = {
space0: 'psycopg2.psycopg1',
space1: 'psycopg',
space2: 'MySQLdb', 3: 'sqlite3'
}


My user can then select the engine they prefer to use and I now want to import the appropriate library. I could, of course, do this...

if user_choice == 0:
spaceimport psycopg2.psycopg1
elif user_choice == 1:
spaceimport psycopg
...

Made even more verbose than it would be in any other language because of the absence of a switch statement in Python.

Clearly this is not a great solution. Everytime I add support for something new then I must write another elif clause - not cool! After I bit of playing around with eval, I got to...

Database = eval("__import__('{0}')".format(db_libs[user_choice]))

And after a little further investigation I also discovered the imp module:

from imp import find_module, load_module
fp, pathname, description = find_module(
db_libs[user_choice])
Database = load_module(
db_libs[user_choice], fp, pathname, description)

More code, but it feels a bit safer for those cases where the dynamic element is coming from the user more directly.

---
#EDIT (July 10th) - imp.find_module() doesn't seem to support the two part module name (e.g 'psycopg2.psycopg1') although it works for my other examples. The eval works fine even in this case.

Tuesday, 7 July 2009

Using the Enumerations provided by VirtualBox's SDK with Python and XPCOM

Because this was surprisingly difficult to find out - thanks to Benjamin who provided the answer :o)

So... the VirtualBox SDK allows you to control VirtualBox programmatically. In particular from a selection of languages using either XPCOM or SOAP. I've been working with Python using the XPCOM method, which looks a bit like this...

vbox = xpcom.components.classes["@virtualbox.org/VirtualBox;1"].createInstance()
session = xpcom.components.classes["@virtualbox.org/Session;1"].createInstance()

default_id = "00000000-0000-0000-0000-000000000000"
mach = vbox.createMachine("my_new_vm_name", "Ubuntu", None, default_id)
vbox.registerMachine(mach)

All good so far... and indeed for quite a long while. Still, this last week Hobnob and I have been pushing the SDK a little bit futher and discovered a need to use some of the built in enumerations. For example, to register a hard disk within VirtualBox using the SDK you'll need the openHardDisk() method provided by the IVirtualBox interface. This takes, as one of it's parameters an enum AccessMode (which does the obvious), the documentation tells you that this is provided in VirtualBox.idl and looks something like this:


Looking good? Well almost. It's just a shame that there's no good examples around to show you how to do this. After some experimentation, Hobnob and I settled for looking up the values and then dropping them into the code I was trying to write:

AccessMode_ReadWrite = 2
hd = vbox.openHardDisk("/vm_disks/mydisk.vdi", AccessMode_ReadWrite, False, "", False, "")

Clearly this is not the way this was meant to be done. So how do you use the built in enums? Answer... like this:

ifaces = xpcom.components.interfaces
hd = vbox.openHardDisk("/vm_disks/mydisk.vdi", ifaces.AccessMode.ReadWrite, False, "", False, "")

Easy when you know how, huh :) So now I can remove these lines from my code:

AccessMode_ReadWrite = 2
HardDiskType_Immutable = 1
HardDiskVariant_Standard = 0

And replace them with:


ifaces.AccessMode.ReadWrite
ifaces.HardDiskType.Immutable
ifaces.HardDiskVariant.Standard

And it turns out I wasn't using HardDiskType_Immutable anymore anyway :) You never know what you'll find with a quick code tidy.

Monday, 1 June 2009

VRDP/RDesktop-cli

Using VirtualBox v2.2.2, I've got a VM with a plain boring Ubuntu install. Standard setup with no extra magic except that I've turned on VRDP (Settings->Remote Display->Enable VRDP Server. So that's the server side.

On the client side I'm using a Nokia N810 device, rdesktop-cli v1.6.0 and (attempting to use) PyRDesktop 1.5.

Firstly PyRDesktop is slow to start. That aside, I enter the IP of my host, and hit 'connect' - it does. Seemingly satisfied I close the window. Coming back to it a while later to see how *well* it works I start to notice a significant problem - my touch screen interactions seem to be totally mismatched with the resulting output. Imagine a display that just really wasn't calibrated right: I touch the screen in the top left and drag down - a selection starts to be made in the centre of the screen, I touch in the centre and I can just see my selection falling off the bottom right corner... not so useful.

Curious.

So, I figure I'll leave PyRDesktop out of the equation for a moment at try RDesktop without the 'pretty' (it isn't) Python GUI. Starting out with the reasonably simple "rdp myip" (having aliased the rather stupidly named rdesktop-cli to rdp - surely it should either be rdesktop or rdesktop-client not some weird middle ground?) I find the same problem occurs. Fine, so what's next? Try forcing the thing to use RDP 4 "rdp -4 myip" but that just doesn't work at all, I can't connect that way. Try a bit of a fiddle with compression and caching, neither of which alter anything (did I expect them to?) and then reread the usage information.

Usage: rdp [options] server[:port]
-g: desktop geometry (WxH)

Ah-ha. That looks kind of useful. Try it first with some arbitrary values:

Nokia-N810-43-7:~# rdp -g 480x220 169.254.10.32
Autoselected keyboard map en-gb
WARNING: Remote desktop changed from 480x220 to 800x600.

This doesn't 'fix' the problem, but it does seem vastly improved. Quickly look up the resolution for the N810 on the magic Internets and try again:

Nokia-N810-43-7:~# rdp -g 800x480 169.254.10.32
Autoselected keyboard map en-gb
WARNING: Remote desktop changed from 800x480 to 800x600.

Much better. Curious about the warning though - if it hasn't actually used the resolution I've told it to then 1) why not? 2) why has this helped?

Monday, 25 May 2009

All in the Balance

I spotted this cache today when looking for things local to the area in which I planned to spend the day (I visited the Cathedral of Learning - more later). Remembered it when I got back in the evening and thought I'd attempt to solve it.

The first parts were reasonably easy once I remembered what the involved. I'm pretty confident in my S, K and F.


The next part, I continue to struggle with. I've got as far as:


I know that 1 mole of nicotine is 162.26g and 1 mole of O2 is 32 grams.

I think then that:


Update - Writing this just made me notice a mistake I made right at the end. I just solved it (@22:42)!! (Well, I have an answer that passes the verification).

I'll carry on now...

So I need to balance that with the appropriate ratio of oxygen. The number I have on a scrap of paper here is:


...but I think I've now just doubled that to get the answer? Hmmm... not sure how confident I am in my final answer now :) All these numbers on my paper make for a confused Saffy.

Using the fact that 1 mole = 32g. I can calculate that the above number of moles (doubled) times 32 gives me the weight of O2 in grams. Convert that to milligrams and lose the decimal places to get a three digit number for the cache coordinates:


Anyone care to check my chemistry/maths? It's a long time since I've done anything like this! A good challenge - did I actually once know how to do this stuff?

Thursday, 21 May 2009

More Hugin

Did a bit more work on my Hugin script yesterday so thought I'd take some slightly better pictures to test it. The images aren't quite taken from the same place but they're as close as I can manage by myself.


And there it is - my desk!

So, what changes did I make the the script since last time?

Well:
  • It now takes n images - previously it took two
  • It attempts to find the hFOV in the first photos EXIF data - previously an arbitrary value of 30 was assumed (it'll still fallback to this value if nothing is found)

Not sure about anything else, because I can't quite remember what I had put into the script last time I posted. It prunes the control points now which it probably didn't do before.

Wednesday, 1 April 2009

OpenStreetMap

As part of the Ubicomp Spring School I've been attending this week in Nottingham, I spent this afternoon looking at Locative Gaming using Mscape. Looking at their last few blog posts, I spotted this:

mscape at State of the Map 2008

"For my latest adventure around the world with mediascapes I went off to the OpenStreetMap Foundation’s second annual conference, entitled State of the Map. This year the conference was held in Limerick, Ireland - cue an obligatory limerick competition (the winner of which I unfortunately didn’t write down).

For those you haven’t already heard, the driving force behind the OpenStreetMap idea is that the online maps that many people believe are free, such as Google or Yahoo maps, are actually far from that. Yes, you can look at them for free, and can build mashups where your own data is overlaid on top, but you cannot extract the maps images and use them offline in any way, you can’t print them in paper brochure and you cannot add, update, or alter them without falling foul of the licence restrictions all of these sites include. That is, all of them except for OpenStreetMap.

Essentially it’s the wikipedia of online mapping, built using crowd-sourcing - a large-scale online collaboration where anyone can add to the map, or fix errors they find. The way it is done is that people cycle around with a GPS that logs their path, and record the street names, locations of parks, pubs, shops or restaurants they pass using using a camera or pen-and-paper. Back home they upload the GPS log and use one of OSM’s mapmaking tools such as potlatch or JOSM to draw in the streets, paths, & junctions over their route, and enter in the other point-of-interest data.

We first looked at OpenStreetMap a couple of years ago but found that the data was so sparse that the maps really were not all that useful. Fast-forward to the present though, and the 46000 registered users have done an amazing job so that the quality of maps in major cities like Bristol is often more detailed and up-to-date than the equivalent Google map..."

(from the mscape blog, read the rest of this post here)


They then go on to present the following side-by-side example:







It does look quite good. I think I may have to take a look at my local area and see what the data is like.

Wednesday, 3 September 2008

Standard Deviation in a Single Pass - Hurrah!

Amazingly I got from a Google search for "standard deviation on the fly", round a few twists and turns, to...

Calculate standard deviation in one pass

Exactly what I was looking for!

Thursday, 14 August 2008

Shared Memory... explanation?

I'm trying to justify why I'd implement RPC over message-passing in a distributed architecture. To get round to this bit I need to suggest alternative methods... the main one being shared memory. Only problem is I then have to assemble some sensible words suggesting what shared memory actually is - something more informative than "it's memory, shared between multiple devices". Hmmm....

I've got a nice picture though, 1000 words and all that (I really don't need any more 1000s of words!).

Wednesday, 13 August 2008

C# Books

Stu's just asked me about C# programming books. When I last did any C# it was version 1.1, just, I started my project at version 1.0 and finished up using version 1.1. Still, the book I used was the first edition of what is now this book: The C# 3.0 Programming Language. I'm glad to see the book has continued because it was by far the best when I was looking for something to learn from/reference. Like the K&R C book, it provides the specification, it's nice and clear and it's not full of specific useless examples - hurrah.... maybe one day I'll find the need to come back to C# and have a look at the new edition... once it's available.

Wednesday, 6 August 2008

Pseudocode?

Is it pseudocode or pseudo code? Wiki seems to say it's one word but Microsoft Word is not convinced. Also, finding the Wiki article using EasySearch works for both "pseudo code wiki" and for "pseudocode wiki", but the second leads to a reccomendation that you try the first so maybe they need convincing at EasySearch's engines too. I think I prefer it as one word... either way I've been writing lots of it :)

I've been using this nice little style guide thing which seems to suit me quite well subject to a few alterations (though the style guide also seems to think it's two words).

I feel like I'm sort of making progress with this write-up stuff now but it does take such a long time. I think my structure's kinda there though.

Wednesday, 16 July 2008

Nearly There

On one bit of my project at least. I've mostly implemented RPC for my PICs - The remote bit works, I have a task going from one place to somewhere else which is lovely. Only thing is that nothing seems to happen when it gets to where it's going :(

Anyway, I'm giving up for today to go and get to Chancellors in time to eat before Guides and maybe do some write-up.

Also, Ewwww.

Sunday, 8 June 2008

An Excellent T-Shirt

If I sold geek clothing I'd sell t-shirt (and pyjamas) with the text:

while (1) {
sleep();
}

or:

while (1) sleep();

Or whatever your preferred language/syntax might be.

Sunday, 1 June 2008

Mm... beautiful

I've put some nice shiny AJAXness into the new cinema site - here's the XML my PHP script returns:

<xmlresponse><playdate>There Will Be Blood(Cert. 12A)&lt;br /&gt;01 Jun 2008 7:30pm - Runtime 158 minutes<br /&gt;&lt;br /&gt;&lt;b&gt;House Manager:&lt;/b&gt; &amp;lt;&lt;i&gt;available&lt;/i&gt;&amp;;gt;.&lt;br /&gt;&lt;b&gt;Projectionist:&lt;/b&gt; Lancaster University Cinema.&lt;br /&gt;&lt;b&gt;Steward:&lt;/b&gt; &amp;lt;&lt;i&gt;available&lt;/i&gt;&amp;gt;, &amp;lt;&lt;i&gt;available&lt;/i&gt;&amp;gt;.&lt;br /&gt;&lt;b&gt;Trainee Projectionist:&lt;/b&gt; &amp;lt;&lt;i&gt;available&lt;/i&gt;&amp;gt;</playdate></xmlresponse>


Beautiful!

---

And it all had to be escaped again to get it to show up here correctly :)

Monday, 31 March 2008

Identifying Colours (revisited)

Today Hobnob and I took a look at the whole colour identification thing and now my application seems to work a lot more sensibly. Discovered the following things:

* That copy-and-paste errors will seemingly always be prevelant in my applications. If I code my application to recognise reds as pink then that's what it'll do even if I did mean to change it to say red after I pasted it.

* That the difference between the RGB values within greys can vary up to around 6% and still look grey.

* That if I return an RGB value between 0 and 1 then checking to see if it's greater than 225 will not generally return true.

Those three combined with adding some extra weighting to the middle section of an image (assuming that most people taking a picture of something will aim to have it in the middle of the picture) seem to have mostly fixed my code!

Friday, 28 March 2008

Identifying Colours

I've almost finished my Tamagotchi app. I have something that's alive for a bit getting hungrier, dirtier and older and can be fed, played-with and cleaned by taking pictures. The pet demands that you take a picture of something that is a specified colour to successfully play/clean etc. Unfortunately its colour matching seems slightly flawed - I've just taken pictures as follows:

Took Blue - Identified Blue
Took White - Identified Yellow (but reflection from green wall/shadows?)
Took Red - Identified Blue
Took Green - Identified Green
Took Black/Blue - Identified Red

Clearly something is not so great in my colour matching. I'm currently going through all the pixels in the image and identifying them as one of: black, white, grey, red, yellow, green, cyan, blue and magenta. I keep a count of how many pixels are of each colour and say that the picture is whatever the modal colour is. If two or more values are equally common then I return whichever of the most common colours appear first in the list of colours.

I guess I shall have to try a few more methods and see what works best.

Thursday, 27 March 2008

That Tamagotchi Application

Having taken a break with all the chaos that's come up recently I've now finally got back to my Tamagotchi-style phone application. It's gettting kinda neat now, I persuaded it to take photos which is good so that just menas I need to call my function to work out what colour they are!

Tuesday, 18 March 2008

CustomItem Preferred Size

I've been coding a tamagotchi app for the Nokia N95 with MIDP 2.0. I'd been working on the Sun emulator until last night when I copied it to the phone. Running it on the phone was a bit deperessing because all the nice images in my custom status screen overlapped. It seemed slightly odd as I'd gone out of my way to ensure I calculated the height and width of all the bits and used them to get an overall minimum and preferred height e.g.

Class MyItem extends CustomItem {

byte height;
byte width;

public MyItem() {
this.width=part1.getPreferredWidth();
this.width+=part2.getPreferredWidth();
this.height=Math.max(part1.getPreferredHeight(), part2getPreferredHeight());
}

protected int getMinContentHeight() {
return this.height;
}

protected int getMinContentWidth() {
return this.width;
}

protected int getPrefContentHeight(int width) {
return this.height;
}

protected int getPrefContentWidth(int height) {
return this.width;
}

}

However, whilst this works in the emulator, it turns out I need another line to make it work on the phone. Adding the following:

this.setPreferredSize(this.width, this.height);

at the end of my constructor fixed my problem and now it all looks pretty great! :)

Wednesday, 12 March 2008

RGB to Hue

Today I've been trying to convert RGB values to a hue value in Java. It would be easy using Java SE but there's not a 'does the job for you' function in ME (I hope).

It was all going a bit wrong for most of the day but then Hobnob came home and made it work! Hurrah!

Monday, 10 March 2008

Custom Java ME Gauge (Revisited)

Woo, I've now managed to get three of my custom gauges together to make a status menu. The icons sit very nicely on top of each other (though I need to write the code to make the gauges update from the menu) but are still in completely the wrong place on the screen.

Lunch and library time!

LinkWithin

Related Posts Plugin for WordPress, Blogger...