Django: How to filter using "not equals" and "or" case

One thing I loved about Django is its ease for writing reusable queries.

However, it didn't take long before I ran into the problem of "how do I do not equals?".

Take for example the SQL query:

SELECT * FROM model WHERE id != 3

To make that work in Django filters, we'd use the Q object.

from django.db.models import Q

YourModel.objects.get(~Q(id = 3))

Like in C++, the ~ will negate the operation.

The next issue I ran into was how to create the "OR" filter. Normally, chaining filters will use the "AND" operator which is sufficient for most queries in your system.

But sometimes you need the "OR", and with that Q comes to the rescue again.

Say for example, this time you want to this SQL query:

SELECT * FROM model WHERE (name LIKE "Montgomery" OR name LIKE "Smithers")

In Django using Q, it'd be written like:

YourModel.objects.get(Q(name = 'Montgomery') | Q(name = 'Smithers')

You can also mix up Q objects and keyword arguments, but you have to ensure that Q object filters are all defined BEFORE any keyword arguments. Refer to the documentation for a proper example of this.

[ Documentation ]

Android: Create a URL using Uri.Builder().build() with port numbers works quite well with normal URLs, but it fails with port number support.

The easiest way that I discovered to make it support port numbers was to make it parse a given URL first then work with it.

Uri.Builder b = Uri.parse("").buildUpon();

b.appendQueryParameter("arg1", String.valueOf(42));

if (username != "") {
b.appendQueryParameter("username", username);

String url =;

And there you have it, a customisable URL with support for port number and queries.

Python: Convert a list/tuple/dictionary into JSON

Django has a nice serializer library for models, but for a simple way of dumping primitive types straight out to JSON would be to use json.

If you try to use Django's serializer on primitives you'll get this error:

AttributeError: 'str' object has no attribute '_meta'

Instead, use Python's built in library support.


Python 2.5 has "simplejson", so to make sure you import the right one, just use this import statement.

import json
except ImportError:
import simplejson as json

[ Source ]

Python: How to use MD5 checksum?

import md5

mystring = ""

print md5.md5(mystring).hexdigest()

That's it. Nice and easy, just like most things in Python.

[ Source ]

PHP: Parsing SimpleXML nodes with namespaces

SimpleXML is one of the easiest parsers to use, but when it comes to namespaces, things get just a little bit tricker.

You'll run into them when you're parsing media RSS feeds such as:

  • FlickR (media:thumbnail, media:category, media:content)
  • YouTube API (yt:duration, yt:statistics, gd:rating, gd:comments)
  • or Yahoo Weather (yweather:location, yweather:astronomy)

They might be a bit gay to deal with, but luckily it isn't too much harder.

Namespaces, almost as gay as this guy.

The trick is having to gather the namespace children before pulling the element you want.

Using this short sample XML from FlickR.

<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
<media:thumbnail url="" height="75" width="75" />

You can use this PHP code to extract the "media:thumbnail" elements from the RSS item.

$entries = simplexml_load_file('');
$namespaces = $entries->getNamespaces(true);

foreach ($entries->channel->item as $feeditem) {
$thumbnail = $feeditem->children($namespaces['media'])->thumbnail;
$attr = $thumbnail->attributes();

echo '<pre>';
echo "URL = {$attr['url']}, width = {$attr['width']}, height = {$attr['height']}\n";
echo print_r($attr, true);
echo '</pre>';

The code was based off the source from PHPFreaks, but modified to avoid using the URI of namespaces as it makes the code ugly.


[ Source ]

Android: Using the GUI editor to change text size

I found it a bit baffling when I entered in a number into the text-size field and the control just disappeared. At first I was annoyed, wandering why such a stupid feature wasn't tested properly.

Then when I looked it up, I realised it needed a little bit more information from me. The way that text resizing on the user interface was implemented in Android was intended to be flexible, and inherently a little more complicated.

The text-size attribute (much like margin and padding attributes) require values and units.

If you enter in "20px", it'd be a fixed 20 pixel size. Not quite helpful when you work with various pixel densities and screen sizes.

A much more suitable measurement unit would be "20sp", which is 20 density independant pixels (dips), but scaled to suit the user's font size settings.

There are other units such as:

  • in (inches)
  • mm (millimeters)
  • pt (point - font size)
  • dp (density independant pixels)
  • sp (density independant pixels, scaled to user's font size preferences)

Alot of tutorials will focus mainly on px and dp, which aren't entirely the best way of going about creating a multi-device compatible code.


Django: Change the prefix in the error notification errors

When a server 500 error occurs, its handy to get a notification error from Django.

But when you have more than one Django powered site running, its kinda hard to see which site the error is ocurring on at a brief glance.

Luckily, there is a simple option to change that. In your settings file, add this:


That's it! Now your emails will have that in front instead of the generic "[Django]" label.

[ Source ]

Android: How to hide a view and collapse the view's allocated space

When you call View.setVisibility(View.INVISIBLE), you'll notice that view is still taking up space on the screen but not being drawn.

To prevent the view from leaving a big empty gap, simply use View.GONE instead of View.INVISIBLE.

To bring it back, just use View.VISIBLE.

[ Source ]

Android: Refer to "localhost" from Android simulator

This was a bit tricky but it makes sense.

When writing your code, keep in mind that "localhost" refers to the device which the code is running on; the mobile phone or tablet which is using Android.

If you want to refer to the computer which is running the Android simulator, use the IP address "" instead.

This will direct the simulator to the simulator host.

[ Source ]

Samsung Galaxy S i9000: Fix the slow GPS signal

After getting frustrated with the flaky GPS connectivity which doesn't connect most of the time and supremely slow GPS lock-in delay, I decided to try the fix that's been floating around on the net for a while.
Obviously he's also very angry about the crappy GPS signals.

Note: The Android 2.2 Froyo update for the Samsung Galaxy S/Vibrant/Captivate fixes these issues, but I'm keeping it on 2.1 for dev purposes.

Apparently the Froyo update has GPS which connects almost immediately, so that might be worth checking out.

Update 3/7/2011: Apparently not. There's still a lot of complaints about the GPS after installing Froyo/Gingerbread.

To make your GPS connect quicker

Please use the following instructions to speed up the GPS "lock in" time.

*update 3/7/2011*

While reading dangrayorg's lengthy and technical post about how the GPS works, he linked to Da_G's highly successful tutorial with GPS daemon hacks.

That clever bastard has managed to port over the firmware for the GPS from the Nexus S to the Samsung Galaxy S i9000.

He's even figured out some of the settings and tweaked them to be as accurate as possible.

All you really have to do is download it for phone!


To follow this guide, you will need to know the exact model of your phone, the firmware you're running and be comfortable enough to use the command prompt/terminal "black screen" to type in commands.

It involves replacing the GPS driver files on your phone, which may or may not work and could potentially (although the chance is quite slim) brick your phone.

I've tested it for a week before posting this. The test were done in my car, on a train, on a bus and in the house under a roof. This worked for me with an 80% success rate of connectivity, which was far better than the 10% before fixing.

And lastly, I do not take any responsibility for you messing up your phone.


Backup your files!

Of course, any hack of this sort will require you to back things up in case shit goes wrong. We've all been there, we've all had the horrible sinking feeling when something goes awry and there is no way of reverting it. Don't make the same mistake again.

Using adb, follow the steps below to make a backup of files which are about to be changed.

mkdir /sdcard/gps_backup
mkdir /sdcard/gps_backup/system
mkdir /sdcard/gps_backup/system/etc
mkdir /sdcard/gps_backup/system/bin
mkdir /sdcard/gps_backup/system/bin/gpsd
mkdir /sdcard/gps_backup/data
mkdir /sdcard/gps_backup/data/gps

busybox cp /system/etc/jupiter.xml /sdcard/gps_backup/system/etc/

busybox cp /system/bin/gpsd/glgps_samsungJupiter /sdcard/gps_backup/system/bin/gpsd/

busybox cp /data/gps/secgps.conf /sdcard/gps_backup/data/gps

This will make a folder called "gps_backup" on your phone and then back up the files there. Once that's done, you should copy them to your PC for safe keeping.

Note for Eclair (Android 2.1) users

If for some reason you're weird (like me) and have stuck to the slower Android 2.1 Eclair for development reasons instead of upgrading to the faster Froyo/Gingerbread releases, then you'll need to make the following changes to "".

In the zip file, you'll need to modify "system/etc/jupiter.xml". Extract it, replace the following lines:


Replace with:


Add it back into the archive, replacing the old file. Check it to make sure it's been modified.

Preparing the hack

  • Rename "" to ""
  • Copy it over to the root folder of your phone memory under "/sdcard"
  • Using adb, set your phone into recovery mode by typing:

adb reboot recovery

You should now see a screen full of yellowish writing.

  • Using the volume up/down buttons, select "Apply"
  • Select it using the home button
  • It should now install and reboot your phone
  • When you get back into the recovery mode screen, just select "Reboot system now" to complete the process.


If you're seeing the "installation aborted" error message, make sure you have CWM (ClockworkMod recovery bootloader) installed.

  • Install "ClockworkMod Rom Manager" from the app market
  • Get root access
  • Grant it superuser access
  • Flash the recovery bootloader with whatever matches your model
  • Select "Reboot into recovery" to get into recovery mode and try the installing "".


When you're back into your phone, you'll still have some things to configure.

  • Go to "Settings" > "Location & Security"
  • Uncheck the option "Use Wireless Networks"

You'll also have to first clear your old GPS data. Otherwise, the GPS icon will appear for half a second then disappear as it stops trying to connect.

  • Get into "LBSTestMode" by going to the phone dialer and pressing
    • *#*#1472365#*#* (Eclair)
    • *#*#3214789650#*#* (on Froyo onwards)
  • Click on "Delete GPS Data" to wipe out the old cache
  • Go to "Application settings" and use the following settings


    • Session Type: Tracking
    • Test mode: S/W Test
    • Operation Mode: Standalone
    • Start Mode: Hot start
    • GPS Plus: ON
    • Dynamic accuracy: ON
    • Accuracy: 80 (meters, not percentage)
    • Use SkyHook: OFF
    • Use PC Tool: OFF


  • Press back and get into SUPL/CP settings
  • Use the following settings


    • Server FQDN Type: Custom config
    • Server:
    • Server Port: 7276
    • SUPL Secure Socket: OFF
    • AGPS Mode: SUPL





  • This should now be enough to get you up and running with the GPS.
  • First start, enable 3G or WiFi and wait for it to connect
  • Enable GPS
  • In LBSTestMode, open up "Get Position Test"
  • "Satellite Informations" should disappear once the satellite information has been downloaded from the SUPL server.
  • After that, it should take a moment to connect to the satellites.
  • Wait for a lock-in.

That's it. Restart and try it out with Google Maps. I managed to get a signal from my room, so I tested it by watched it track me walking from the back of my house to the front door.

Old method which does not work

Ignore the stuff below, it was from the original post. This was back when I first got the phone and was trying anything from the internet to tweak the settings.

  • Go to "Settings" > "Location & Security"
  • Uncheck the option "Use Wireless Networks"
  • Go back to the menu and open up your dialer.
  • Key in *#*#1472365#*#*
  • It should take you straight to the hidden configuration screen. If it doesn't, check the code or press the "DIAL" button
  • In the LBSTestMode app, select "Application Settings".
  • Change "Operation Mode" from "Standalone" to "MS Based"
  • Change "Accuracy" from "50" to "100"
  • Press the back button.
  • Now go to "SUPL/CP Settings"
  • Ensure that "Server" and "Port" are "" and "7276" respectively.
  • Press back to get back to the LBSTestMode menu.
  • Go to "Get Position Test" and let it run until it picks up 10 satellites.
  • Press back to get back to your phone menu.
  • Restart the phone.
  • Re-enable "Use Wireless Networks" (it uses your mobile cell area to approximate it first)

My GPS signal now connects in approximately 10 seconds. Still rather slow, but much more reliably and faster than before (either took 30 seconds or timed out after 60 seconds).

*edit 12/01/2011* Re-enabling the "Use Wireless Networks" makes GPS lag again. I turned it off and it worked much better.

*edit 07/02/2011* Added note about testing the positions

*edit 3/7/2011* Added information on how to use Da_G's daemon replacement hack. After a week of testing, this is definitely the best fix to date and actually makes the GPS usable!


PSP: Load homebrew and ISO images off the memory stick with official firmware 6.31 and 6.35

*update 06/02/2011* If you're on 6.35, there is a MUCH EASIER way of doing this. I've written a guide for running HEN directly from the XMB menu. It's totally worth upgrading to 6.35 for this!


Its been a long wait since when I bought my PSP till Total_Noob released his homebrew enabler (HEN) for official firmware (OFW) 6.20.
Now its been ported to v6.31 and v6.35! This isn't the same HEN which Total_Noob is working on, but it'll do for now.

Essential ingredients

Now depending on which firmware you have, select one of the following:
You may also need to upgrade your firmware. I chose 6.31, because its more likely to have exploits that 6.35 doesn't have. Find the right firmware here.

How it works

While you're waiting for the downloads to finish, here is some light reading without the technical details. The idea is much like the Twilight Princess hack which got the Wii homebrew community started.
It involves crafting a special save game file which triggers an exploit in a certain game. Fortunately this time "Minna no Sukkiri (demo)" is a free demo rather than a full game you have to pay for.
Once the exploit starts, it loads a special set of files which enable homebrew on your PSP. It then automatically restarts your PSP back to the menu with homebrew functionality enabled.
You can then run any homebrew software, including ones which load ISO images ;)

How to do it

If you haven't done so already, put your memory stick into the PSP and format memory stick using the PSP's menu.
  • Go to "Settings"
  • "System Settings"
  • "Format memory stick"
Now take the memory stick (ms) out and plug it into your PC for some prep work.
  • Make a new folder on your computer somewhere and call it "MSCARD".
  • Extract all the files from "" into that folder.
  • Extract "EBOOT.PBP" from "" (or and move it to "MSCARD\hbl\menu\", replacing the one from HBL.
  • Create a folder called "MSCARD\ISO".
  • Create a folder called "MSCARD\PSP\GAME".
  • Create a folder called "MSCARD\PSP\SAVEDATA".
  • Create a folder called "MSCARD\PSP\UPDATE".
  • Extract the contents of "minna no sukkiri" into "MSCARD\PSP\GAME\NPJG90047".
  • Extract the contents of "" (found inside minna no sukkiri and extract it to "MSCARD\PSP\SAVEDATA\UCJS10094".
  • Extract the contents of "" to "MSCARD\PSP\GAME\Prometheus_Iso_loader".
This is what your directory structure should now look like.
Once you've checked that everything is right, move all the stuff from this folder into the root folder of your memory stick.
Homebrew games go into "ms:\PSP\GAME" while ISO files go into "ms:\ISO".
(Optional: How to update the PSP firmware)
If you're running firmware lower than 6.31, you'll need to update it.
  • Extract "EBOOT.PBP" from "PSP Firmware 6.31 Update (" into "ms:\PSP\GAME\UPDATE".
  • Go to your PSP menu
  • "Settings"
  • "System Update"
  • Follow the steps.

Running the homebrew!

Alright, time for the test run! This is the process to enable homebrew every time you turn off the PSP (by holding the power switch for a second or two, not hibernating it). If you hibernate it, you can still load the homebrew from the XMB.
  • In the PSP menu, go to "Game".
  • "Memory Stick"
  • "Minna no Sukkiri demo"
  • Wait for a bloody long time until you get to the main menu.
  • Select the bottom option.
  • It should display some whacky Japanese error message for a moment and then reboot back into the menu.
If it does not reboot and shuts down instead, you're missing the h.bin file and "hbl" folder from the root of your memory card.
If it boots into a funky menu with some lightning dude where you can select "Prometheus ISO loader", you've forgotten to replace the EBOOT.PBP file with the appropriate HEN file for 6.31 or 6.35.
  • After the PSP has restarted back into the menu
  • Go into "Game" again.
  • "Memory stick"
  • Select "Prometheus ISO Loader"
  • Select your game and enjoy!
If the screen blacks out, change the "Current ISO mode" between "M33 driver" and "NP9660" by pressing SELECT on the ISO loader screen.
I forgot what the default was, but just change it and see what happens.
Don't worry about any memory leak messages, its normal.
This is working well on my Japanese PSP 3000, but since we all run the same firmware it should be fine for all.
A big thanks to everyone who contributed to the homebrew scene to get it all working this well!


Navman s45: Change or delete "My Home" address

By God I had so much trouble figuring this one out. Navman user interfaces are pretty frustrating!

At first I thought it an option in the preferences. Nope.

Then I tried the useless 270mb heavy NavDesk software. Nope, it ain't nothing but a store front for maps.

Finally, I had to resort to reading the FAQs on the Navman support site.

To remove or edit your home address, you have to first REMOVE it from your favourites.

Navman logic makes me want to cry!

  • Tap the bottom left to enter the menu
  • Favourites
  • "My Home"
  • Confirm with "Yes"
  • Click "My Home" again...
  • Enter in the new address
  • Save it.
  • Sell the GPS on eBay and use that money to buy something better.

[ Source ]

TomTom: Activating Maps using tt7_keygen.exe

Plug the TomTom device or SD card into the PC.

  • Find the file "ttnavigator.bif" and read it using Notepad to get your DeviceID.
  • Create "Meta.txt" and paste in the 2 lines for the maps file.
  • Save this where the map files are.
  • Copy "tt7_keygen.exe" to the maps folder.
  • Run the keygen using this syntax: "tt7_keygen.exe ./ deviceID"
  • It should give "OK" instead of "There is no such map in keyfile 'Meta.txt'"
  • Delete "Meta.txt" and the keygen.
  • Move the map files to either:
  1. StorageCard:\My Documents\<YourMapFolder>\
  2. StorageCard:\<YourMapFolder>\
  • Safely remove the device and test it out.

Navman: Unlock your Navman GPS unit (Navman s45)

The unit I have is called the Navman s45 (S-series n207) but this method works for a bunch of other GPS units too.

Unlocking the unit disables the autostart on the operating system, revealing to you that its only running WindowsCE v5.00!

Now that you got control of the system before it starts up Navman's Smart ST software, you can do some nifty stuff like install a media player or games.

  • First, download
  • Connect your GPS unit to the PC. 2 new drives should appear.
  • Optional: Make a backup of the files (just using Windows Explorer)
  • Leave the files there!
  • Extract and run "Setup.exe"
  • Click "Install Desktop"
  • Close the program
  • IMPORTANT! Safely remove the Navman before unplugging it!

There you have it, now you can access the start menu and the system settings. It's a bit tricky to control, but I find it easier with the DS stylus.

[ Source ]

Room Cleanout 2010!

Some of you might remember the last time I did a major cleanup 3 years ago when I threw out gave away a bunch of stuff.

(Scroll down for the list of stuff)

free stuff anyone ...  - Windows Live
Back in 2007...

Well, its happening again!

First of all, I'm sorry to those who gave me presents which are being given away. I'm just running out of room so stuff just has to go! Don't take it personally, I mean there's some stuff here from over 2 decades ago just collecting dust.

If you want something, just leave a comment or contact me on Facebook/IM and we'll work something out.

First come first served. If nobody claims it then it'll go on eBay. If its not sold I'll just put it up on Gumtree or palm it off to little nieces/nephews.

Another note, if you want something but you're from overseas, just pay for shipping and I'll post it off to you (in a box of course).

IMG_0219 IMG_0220
The give-away

Stuff that is not free

  • $30: Guitar Hero 1 on Wii (with game and guitar) Nimol Yol
  • $20: NetComm NB5Plus4W (ADSL2+ modem with 11g wireless)
  • $10: Sound Blaster Vibra 128 PCI sound card
  • $15: Resident Evil Collection Tin Case (No movies! Fits 3)
    (pic #14)
  • $10: Spiderman 3 Tin Case (No movie! Fits 1) (pic #15)

Stuff that IS free


  • Keyring finder (with batteries) Nimol Yol
  • Screen guard for 4" screens
  • Wall-E rubix cube Thi
  • Pin point impression (pic #6) Jennatools
  • Mazda "Zoom Zoom" yoyo (lights up when spun) Raechel
  • Phone case for Nokia phone
  • Looney Tunes and Marvel tazo pieces and Sonic the Hedgehog glow-in-the-dark slammer (pic #1) Raechel
  • 3 bow hair-ties (I think they're Helen's?) (pic #2) Thienticles
  • Expandable colourful thingy (pic #17) Thienticles MUM!
  • Pokeball with Pokemon inside (pic #18) Thienticles MUM!
  • Sonic the Hedgehog games (x2) (pic #18) Elaine
  • Sonic the Hedgehog candy dispenser (pic #18, on the right) Elaine
  • Yellow Robot thingy (pic #18) MUM!
  • Purple Zizzle (pic #18) MUM!
  • Bionicle (pic #18, black thing) Thienticles MUM!
  • Naruto figurines: Neji, Rock Lee, Naruto x2, Gaara, Kakashi, Sasuke, Sakura Bien MUM!
  • Bag of marbles Jennatools
  • A Halloween candy container (pic #22, the big one) MUM!
  • Small McDonalds Halloween pumpkin MUM!

Soft toys

  • Graduation teddy (pic #3, left) Vania
  • Polar bear (pic #3, middle) Vania
  • Me 2 U bear (pic #3, right) Elaine
  • 3 fishies Vania
  • Small brown teddy with movable limbs (pic #5, left) Vania
  • Fluffy teddy bear (pic #24, right) Vania
  • Looney Tunes - Road Runner Bien
  • Little Miss something (pic #5, third from left) Veronica
  • That little Kangaroo from Winnie the Pooh (I think?) (pic #5, right) Vania
  • M&M plush toy Tammy or Veronica
  • Giraffe plush toy (very soft) Veronica


  • 1.2gb PATA harddrive
  • Canon ixus i5 (Shutter is stuck, if you can fix it then you have a perfectly working camera) Bien
  • USB infra-red adaptor
  • CD writer (24x write, 10x rewrite, 40x read) Jessi-Guitar
  • Dynalink ADSL1 modem
  • ASUS EN7300GT Silent PCI-E graphics card
  • White Speakers (pic #12) Studster Keou
  • Logitech R-20 speakers (Power button needs to be replaced, then you have a perfectly working set of speakers) Thi
  • Doraemon phone dangly thing (lights up when you get a call) (pic #21) Jaja


  1. IMG_0306
  2. IMG_0310
  3. IMG_0311
  4. IMG_0312
  5. IMG_0313
  6. IMG_0314
  7. IMG_0317
  8. IMG_0319
  9. IMG_0320IMG_0321
  10. IMG_0322
  11. IMG_0323
  12. IMG_0324
  13. IMG_0330IMG_0331
  14. IMG_0332
  15. IMG_0333
  16. IMG_0337
  17. IMG_0340
  18. IMG_0342
  19. IMG_0345
  20. IMG_0346
  21. IMG_0347
  22. IMG_0348 

Sony Xperia X10: Delete all contacts

Let me get this straight, I'm glad I didn't pay for this piece of shit phone. It's frustrating to use, the buttons are tiny, its laggy and its confusing.

Not to mention, this fairly simple task was a bloody difficult one to figure out. I don't understand why there isn't a multiple select on contacts.

Anyway, to delete all contacts, you have to select:

  • Settings
  • Applications
  • Manage Applications
  • Contacts Storage
  • Clear data

This will delete all the contacts off your phone (not SIM as that was copied over).

[ Source ]

Android: How to load an XML layout onto your layout instead of Activity

For Android activities, they have a very hand function called setContentView() which accepts the layout ID as a parameter.

I found myself having to use a layout instead of an activity to create a settings screen, but layouts aren't fortunate as activities to have a helper function. Luckily, it doesn't make it much harder to do so!

When defining your layout, simply use the following 2 magic lines to get layout XML to inflate onto your layout.

public class SettingsScreenLayout extends LinearLayout {
public SettingsScreenLayout(Context context) {

LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.settings, this);

The LayoutInflater will automatically unpack the XML file and place the objects onto your layout.

[ Source ]

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog