Linux: Disable the default keyring dialog when automatically logging into wireless network

keyring1

This was more annoying than the Vista UAC popups.

Every time I turned on my laptop, the network manager applet try automatically to access my encrypted wireless network.

Every time it tried it would show this stupid message!

The solution?

Well if you don't mind saving the password for all users on the computer, then this is how to fix it (in Gnome)

  • Right click on the Network Manager icon
  • "Edit Connections"
  • "Wireless"
  • Select the connection you want to work with and click "Edit"
  • Check "Connect Automatically"
  • Check "Available to all users"
  • Log out and log back in

If all went well, it should connect to your wireless network automatically without sexually harassing you.

1300152395676

[ Source ]

LinuxMint: Remove the terminal fortune messages

When I first used LinuxMint, I thought it was a nice touch to have random messages greet you when you open a new terminal window.

It was different, witty or funny. Four to five releases later, they just don't seem as funny anymore.

Screenshot-twig@twigmint^% ~So, how to get rid of them? I couldn't find any specific setting in the Terminal program.

So, off to the forums I went and found this:

sudo vim /etc/bash.bashrc

Go to the end and remove the line that says:

/usr/games/fortune

And then remove it:

sudo apt-get remove fortune

*update 2/6/2011*

Ok, if you were silly like me and followed forum instructions to remove fortune, then DONT! It'll make your login screen black.

To bring it back, do the following:

sudo apt-get install fortune-mod fortunes-husse fortunes-min mint-artwork-common mint-artwork-gnome mintsystem

QXKRz
A minor setback. You go and continue being awesome!

[ Source ]

Linux: Computer temperature docklet

For Windows, I use SpeedFan to display my CPU/graphics card temperature.

Since I use a Gnome based LinuxMint distro, there's a neat little desktop applet called... Computer Temperature Monitor.

All you gotta do is open up a terminal and type:

sudo apt-get install computertemp

Once that's done, right click the tray panel and add a new widget.

Select "Computer Temperature Monitor" and it'll work straight away.

[ website ]

Dual boot Mac OSX and Linux (LinuxMint 10 Julia)

This was done on my Asus EEE PC 1005HA running Mac OSX but I'm assuming it's possible on pretty much any machine with a similar setup using Chameleon 2.

Before doing this, MAKE A BACKUP OF YOUR COMPUTER! I take no responsibility for any accidents (and Billy Jean is not my lover!)

image

Install rEFIt

Since Mac OS X uses an EFI file system to direct its boot loader. rEFIt tweaks this a little and installs some extra stuff so it knows about other partitions such as Linux and Windows.

To install rEFIt, download the package and mount it. Run it and then:

  • Click "Continue"
  • "Continue"
  • "Agree"
  • "Continue"
  • "Customise"
  • Tick "rEFIt File System Drivers" (so it knows about Linux formats ext2, ext3 and ReiserFS)
  • "Install"

Once that's done, reboot. You should still see Chameleon as your boot loader and be able to get back into Mac OSX without any problems.

Installing Linux

Depending on the distro you're installing, this may vary a little but the usual steps are still the same.

If you don't have an optical drive, prepare Linux on a USB drive.

When you get up to the screen where you select which partition you want to put Linux on, make sure you choose manually!

Main things to remember are:

  • Leave EFI and Mac OSX partitions alone!
  • Select the partition or empty space which you want to install Linux on and set it to one of the formats that rEFIt supports (such as ext3, since rEFIt won't be able to detect ext4)
  • Remember to give yourself some swap space, about 1gb will do (if you're bothered)
  • Install the Linux boot-loader on the same partition that you're installing Linux! Chameleon has been tweaked to work with the hacked Mac OSX kernel so you need to keep it. Not to mention that Chameleon's interface is much prettier than GRUB.

2011-05-27 00.27.47

If all went well, during your next boot you should be able to choose between Mac OSX Snow Leopard or Linux on the Chameleon boot-loader.

Test if both operating systems work properly!

Changing the default operating system in Chameleon

This started to annoy me after a while because Snow Leopard was the default OS and I don't particularly have a use for it.

So to change the default operating system, you'll need to know the partition details to point to. If you're not sure, reboot and check what Chameleon says by pressing TAB.

Typically it'd be hd(0,3) because it's on the first harddrive and third partition (EFI is 1st partition, Snow Leopard on the 2nd so 3rd is Linux)

IMG_1323

In Mac OSX, go to the console and type in:

sudo vim /Extras/com.apple.Boot.plist

Go into edit mode (press "i" on the keyboard and use the arrow keys to navigate). Add in:

<key>Default Partition</key>
<string>hd(x,y)</string>

Press ESC then ":wq" to save and exit.

Reboot and it should load the default OS you've selected.

Sources

Ubuntu/LinuxMint: Update to Firefox 4

The software repository is a pretty nifty thing, but sucks when there's something new you really want and it isn't there.

To install it, go to the terminal and type:

sudo add-apt-repository ppa:mozillateam/firefox-stable
sudo apt-get update
sudo apt-get install firefox

This should replace your current Firefox with the latest stable version.

[ Modified from Source so it doesn't upgrade EVERYTHING ]

Mac OSX: How to take a screenshot

Bloody hell, this garbage ain't user friendly at all!

1283777253457

These save an image the desktop:

  • Command + Shift + 3
    Take a screenshot of the whole screen
  • Command + Shift + 4, then select an area
    Take a screenshot of the selected area
  • Command + Shift + 4, then Spacebar, then click a window
    Take a screenshot of a window

To copy it to the clipboard, use the Shift key with the combinations above.

In Leopard and later, the following keys can be held down while selecting an area:

  • Space
    Move the selected region
  • Shift
    Resize only one edge of the selected region
  • Option
    Resize the selected region with its center as the anchor point

[ Source ]

Install Apple Mac OS X Snow Leopard (10.6 / 10.6.7) on Asus EEE PC 1005HA

Installing Mac OS X on other netbook/laptops

It shouldn't be too hard to re-jig this tutorial so it works on other devices such as the HP Mini or Dell Mini. For those drivers, you should look at kexts.com for relevant files.

Note that you should have a solid understanding of what hardware is in your machine before attempting the install.

Heads up

I warn you now, this is not a quick task. Things may or may not work for you due to the wide variety of hardware used in the Asus EEE PC 1005HA.

You will also need to set aside at least 3 hours for this to finish. That's just the install time, not including time to copy stuff over or to download the necessary files.

Last note, do NOT reboot when the computer asks you to. If you do, most of the time you'll end up in tears and have to restart the process.

This process took me about 4 attempts to get right from 3 different blogs, so here is my version with as much detail as I could pack in to help you avoid the problems I ran into.

What you'll need

Hardware:

  • USB drive (8gb minimum)
  • A computer running Mac OSX (Friend's mac or VMware)
  • USB mouse
  • USB keyboard

Software:

Creating the installer

Since Apple creates their OS to be installed specifically on Macs, there is a little magic required to get Mac OSX to install on your Asus.

First, fire up your friend's Mac PC (yes, Macs are personal computers) or your VMware image of Mac OSX. I used OSX 10.5.5 and it worked fine.

The reason why we need one is because we need the USB drive to be formatted a certain way.

Stick in your USB drive and make sure there's no important data on it, because you'll lose it all.

1. Partition the USB:

  • Start up "Disk Utility" via Spotlight (the find icon in the top right) or via "Applications" > "Utilities" > "Disk Utility"
  • Select your USB drive
  • Click on "Partition"
  • Click "Options" and select "GUID Partition Table" (GPT)
  • Name it "SnowLeopardUSB" for identification purposes (trust me, the USB bit at the end helps)
  • Select "1 partition" with the format "Mac OS Extended (Journaled)"
  • Click "Apply" to begin. This will take a few minutes.

image

2. Copying the image over

  • After the partitioning is done, click on the "Restore" tab
  • Select your "retail Snow Leopard install DVD image" as the source
  • Drag the "SnowLeopardUSB" partition from the left tree into the destination textbox.
  • Click the "Restore" button to image onto your USB (takes about 40 minutes)

If you get the following error:

"Restore Failure - Could not find any scan information. The source image needs to be scanned for restore."

You'll need to

  • Click on the "Images" menu
  • "Scan Image for Restore"
  • Select your retail installer file
  • Wait for it to finish

image

3. Tweaking the image

This alone is not enough for the installer to work it's magic. You'll have to run "myHack" so it installs Chameleon 2 as your USB bootloader and some drivers for your hardware.

  • Extract the contents of the "Snow Leopard 1005HA Installation Kit" (SLIK) to your desktop.
  • Go to the "myHack" folder and run "myHack_Installer_1.1.mpkg"
  • Click "Continue"
  • "Continue"
  • "Continue"
  • "Agree"
  • "Change location" <-- IMPORTANT!
  • Select your USB drive, not your friend's hard drive!
  • Click "Continue"
  • Click "Customize"
  • Unselect everything except:
    • Core (always selected)
    • com.apple.Boot.plist
    • EvOreboot.kext
    • FakeSMC.kext (always selected)
    • NullCPUPowerManagement.kext
    • SleepEnabler.kext
  • Click "Install"
  • Wait for it to finish up and close it

As a final preparation step, copy the SLIK files over onto your USB to save time.

image
Your finished USB drive should look like this.
I don't know why folder sizes aren't consistent on Mac. Retarded.

Preparing the 1005HA

  • Plug the USB into your EEE PC
  • When the netbook first boots up, press F2 quickly to get into the setup menu
  • Go to "Boot"
  • Select "Hard Disk Drives"
  • Press "-" to push the harddrive down so the USB takes priority.
    Note: that this gets reset every time you start up the netbook without the USB drive plugged in.
  • Press ESC
  • Go to "Boot Settings Configuration"
  • Ensure that "Quiet Boot" is disabled (it gets annoying, you can turn it back on after you're done)
  • Press ESC
  • Go to "Exit"
  • "Exit & Save Changes"

Now you're ready to install!

Installing Snow Leopard on your EEE PC

With all your ingredients pre-mixed and the oven warmed, let's bake!

If all goes well and the USB boots, you should see the Chameleon boot loader counting down on your screen. Either wait for it or select the "SnowLeopardUSB" drive.

Once you see the language selection dialog, you're in business. Press Enter to select because your screen is too small to click the button.

Formatting your hard drive

Mac OSX won't be happy unless it is running on it's own file system. Once again, use "Disk Utility" (accessible via the "Utilities" menu) to prepare your HDD.

We'll be using the same settings as before

  • Select your HDD from the left
  • Click on "Partition"
  • Click "Options" and select "GUID Partition Table" (GPT)
  • This time name it "SnowLeopard" so we can tell it apart from the USB drive.
  • Select "1 partition" with the format "Mac OS Extended (Journaled)" (Choose more partitions if you want to dual boot)
  • Click "Apply" to begin. Again, this will take a few minutes.

Once that's done you're ready to carry on.

Installing Mac OSX

Thankfully this is pretty straight forward.

  • Select the drive where you want Snow Leopard to install
  • Click on "Customize" at the bottom left (I keep forgetting to click this!)
  • Unselect all the languages you don't care about. All up they take up about 1.2gb and takes forever to install!
  • Printer stuff is optional
  • Make sure you tick "Rosetta" (for Intel chipset compatibility)
  • Now you're ready to click "Install"
  • This usually takes about an hour for me
  • Reboot the machine

By the end of it, it'll typically display an error. Ignore the error, it's normal.

Install Failed

Mac OS X could not be installed on your computer.

The installer could not start up the computer from the disk "xxx".

2011-05-23 20.37.54

First boot

Keep an eye on your first boot. Since the BIOS is still configured to load the USB before your HDD, be ready to press a button once it hits Chameleon.

Before you begin...

  • Boot from the HDD rather than USB.
  • Plug in your USB mouse (it won't let you continue without it)
  • When the keyboard setup begins, click the button with your mouse to proceed
  • Then tap "Z" on your keyboard
  • Followed by "/"
  • Follow through the setup instructions
  • You can ignore Apple ID registration
  • Do NOT transfer data from an existing account/computer
  • Create yourself a user account
  • Cast your eyes upon your OSX desktop for the first time! YARR!

Just remember, do not reboot until later! We've still got more work to do!

Chameleon Bootloader

We've gotta set up the Chameleon bootloader on your computer now so it can load Mac OSX without the USB drive.

  • Open up your USB drive (it should be a "SnowLeopardUSB" icon in the corner of your desktop)
  • Run "myHack_Installer_1.1.mpkg" from your USB.
  • Click "Continue"
  • "Continue"
  • "Continue"
  • "Agree"
  • "Change location" <-- IMPORTANT!
  • Select your HDD, not your USB! <-- This is different!
  • Click "Continue"
  • Click "Customize"
  • Same as before, unselect everything except:
    • Core (always selected)
    • com.apple.Boot.plist
    • EvOreboot.kext
    • FakeSMC.kext (always selected)
    • NullCPUPowerManagement.kext
    • SleepEnabler.kext
  • Click "Install"
  • This will take longer than last time.
  • While you're waiting, copy over the SLIK from your USB onto your desktop.

When that's all done, you're ready to replace some files. This will require some user-friendly navigation skills which I (obviously) lacked after all my years using Windows/Linux.

Finder

Finder is bloody useless with default settings. I feel so lost and useful information is hidden from me whilst useless stuff is propped in my face.

Some tips when setting up Finder:

  • Enable the f***ing path bar
  • Use column view, it makes more sense
  • Disable previews by clicking "View" > "Show view options" and then unticking "Show preview column" (it just gets in the way)
  • Your HDD is on the left under "Devices"

Screen shot 2011-05-27 at 11.18.46 AM

Drivers

Onwards with our cake, we've gotta prepare some icing!

Note: You'll need to type in your password quite often during these steps.

  • Open up SLIK and copy the contents from "Extra"
  • Open up a new Finder window (right click on the dock icon)
  • Go to your HDD and then open "/Extras"
  • Paste stuff there and replace whatever is existing
  • Now go back to the SLIK window and copy all the drivers from "Kexts/Library/Extensions"
  • Go to your HDD window and open "/System/Library/Extensions"
  • Paste and replace
  • Go back to your SLIK folder and open up "Sound/VoodooHDA.prefPane"
  • An error will pop up, click "OK"
  • A few seconds later another error will pop up. Just click "Ignore"
  • Time to open up the Terminal app. Go to "Go" > "Utilities" and run "Terminal" manually (Spotlight should still be indexing your system so it won't let you search yet)
  • Type in "pfix" and enter your password.
  • Press the number corresponding to your HDD and press Enter.
  • This tool (installed by myHack will rebuild your drivers so Mac OSX won't reject them.
  • pfix will take a while, so while you wait copy the Mac OSX 10.6.7 combo update onto another USB so it's ready for later.

You're might see error messages appear while you wait saying:

System extension cannot be used
The system extension "System/Library/Extensions/xxx.kext" was installed improperly and cannot be used.

Just click them away, it's fine. pfix will register them correctly and they'll work upon next reboot.

  • When pfix is done, unmount your USB drive and take it out.
  • You're finally ready for your first reboot =)

Second boot

If it loaded back into Mac OSX without any problems, then good work! You can now unplug that USB mouse and keyboard.

Check if you have ethernet and/or WiFi working. If you do then you're one of the lucky ones!

Note! Wireless N (802.11n) does not work! It is a problem with Mac OSX and the AR9285 chipset in your EEE PC.

Most people just change their router to use Wireless G (802.11g) instead.

I've tried many fixes (see below) but none of them seem to work.

If not, you'll need to update (to at least 10.6.4) but heck, lets just go straight to 10.6.7 to save you the trouble later when you need to upgrade.

  • Copy the Snow Leopard 10.6.7 combo fix to your desktop
  • Make a new folder on your desktop called "Backup"
  • Go to your HDD "/System/Library/Extensions/"
  • Copy "AppleIntelGMA950.kext" and "AppleIntegratedFrameBuffer.kext"
  • Return to "Backup" and paste it there.
  • Mount the combo fix image and install it
  • When it's done, do not reboot! Leave it open!

As of 10.6.2, Intel Atom support has been dropped. That means the setup has just removed support for your EEEPC CPU!

  • Go to SLIK and copy "Mach_kernel/10.6.5/mach_kernel_atom" to your desktop
  • Time for some more Terminal shinanigans. Open it up via Spotlight (press Windows button + Space, then type in Terminal)

sudo -s
cd /
mv mach_kernel mach_kernel_old
mv ~/Desktop/mach_kernel_atom ./mach_kernel
chown 0:0 mach_kernel

  • Now it's ok to go back to the update installer and click "Restart"

Lookin' good, the icing is on the cake =)

Third boot

Almost there! Just some sprinkles left.

Once you're back to your desktop, you'll notice that the screen might look funny. That's ok, since you're not using the right graphics driver.

  • Copy AppleIntelGMA950.kext" and "AppleIntegratedFrameBuffer.kext" from "Backups"
  • To your HDD "/System/Library/Extensions/"
  • Copy "SLIK/Wireless/IO80211Family.kext"
  • To your HDD "/System/Library/Extensions/" as well

If you want the Asus function hotkeys (change volume, brightness, etc) you can grab "AsusHotKeys.kext" from Optimisations OSx86. Throw it in the system extensions folder before the next step.

  • Open up Terminal and run "pfix" again for the last time.
  • Once it's done, reboot!

Fourth boot

This is it, your cake is sliced and ready to eat! Everything should now be working.

CPU, sound, ethernet, wireless (Up to 802.11g only), webcam, touchpad, keyboard, graphics, memory card reader and USB ports.

image
Enjoy your cake =)

That was one hell of a tutorial! Time to celebrate with some quality Mac-Guy bashing!

dodgeBallWrenchBashFlash-is-dying

Next post will be about dual booting Mac OS X with Linux.

Battery Percentage X Fix

This is due to the fact the 1005HA has 1gb of memory instead of 2gb. Apparently you have to modify some strings in the DSDT file.

There is some information about it here but I haven't tried it.

Wireless N fixes

If you feel confident enough, give them a shot and let me know how it goes.

The following fixes supposedly work on the Atheros AR9285 chipset with 802.11n (Wireless N) for some people, but not for me.

Sources

There were many other links or forum posts which attributed to knowledge or understanding of the lingo, but these were the main ones.

Updates

*29/05/2011*

  • Added a link to kexts.com

*29/05/2011*

  • Added link to dual boot post

*2/10/2011*

  • Added battery X percentage information

MacOSX: Display current path or folder structure in Finder

Having 2 folders of the same name opened caused made me want to cry because I had no idea what I was looking at.

image
A simple example, but what if the contents were similar?

Coming from a Windows and Linux background, I was shocked to see this is what people consider to be so called "user friendly".

Where is the structure? The logic? What a piece of shit.

gintama

So I figured that for this to be remotely useable, that useful piece of information had to be hidden away somewhere so the Mactards would feel slightly computer literate.

Lo and behold, I found it! Go to "View" > "Show Path bar".

image

This should now appear.

image

Now you've got something retarded like the Windows 7 breadcrumbs, but hey at least its better than nothing.

Python: Find the number of days in a month

To figure out the month range, you can use a built-in function from the calendar library.

from calendar import monthrange

range = monthrange(year, month)
(4, 31)

The result will be a tuple, the first value containing the index of the first day of the month and second value holding the number of days in the month.

*update 31/05/2011*

The first value is used to know what day of the week the first day of the month is.

  • 0 = Monday
  • 1 = Tuesday
  • 3 = Wednesday
  • ...
  • 6 = Sunday

It will correspond with the values in the "calendar" library.

calendar.MONDAY = 0, calendar.SUNDAY = 6

[ Source ]

Install Linux from USB drive

With the smaller netbooks which are too small to have a DVD drive, you often have no choice but to install from LAN or USB.

Good thing for us that there's a handy tool called LiLi (LinuxLive USB Creator) to create a bootable Linux installation on USB.

Install LiLi on a Windows machine and it does the rest for you.

Honestly, it doesn't get much simpler than this!

fishfighter

Python: How to render a Calendar month (including days from surrounding months)

It's nice to have a calendar that displays all the days in a month, but sometimes its handy to also display the extra days padding the month so you don't end up with blank spots.

image image
Left has no padding. Right has padding dates in grey.

I like to have more information when possible. So, to get those extra days you just have to use a simple method already built into the calendar system.

from calendar import Calendar, SUNDAY def generate_date_range(year, month): # Process the calendar month to get the proper start/end dates
cal = Calendar(SUNDAY) # Make Sunday first day of the week
days = [ day for day in cal.itermonthdates(year, month) ]
return days

Another thing you may find helpful is to split the days into weeks for display in rows.

def split_days_to_weeks(days):
weeks = []

for i in range((len(days) / 7) +1):
weeks.append(days[i * 7 : (i+1) * 7])

return weeks

[ Source ]

git: Cherry-pick code fragments from base revision (partial revert)

If you've made a mistake on part of a file and want to only revert portions of it rather than the whole file, you can do that using:

git checkout -p the_filename.ext

The -p flag allows you to step through each code chunk and actively select or ignore changes you want to undo since the last commit.

[ Source ]

Belkin - Flawed by Design

image

This is what a Belkin Double N+ Wireless Router (F6D6230au4) modem looks like when it decides to become a brick.

By design, there is no way to manually set the date on your router. It has to connect to the internet and update the time from an NTP server.

Problem is, if it thinks the time is currently the Unix epoch (1st January, 1970), your ADSL provider probably wont let you connect. Mine certainly didn't.

So spending a few hours chatting to Belkin's passive aggressive customer service representatives came up with nothing. All their solutions assumed that I was able to connect to the internet.

Updated the firmware to an alpha release, no dice. Date still epoch.

Afterwards I spent another hour scouring the net for hidden pages in the admin website in the hope something existed. There was nothing.

I Even looked at connecting to the router via SSH to set the date (as my previous Netcomm and Netgear routers allowed) but the damn thing wouldn't let me connect!

Whoever it was that thought it was clever to implement this little catch-22 should reconsider revisiting this decision.

I'm taking this shit back. I don't want this pretty little paperweight and I'm putting this up on the Belkin head office door.

2014

Django: Filter by aggregate Count using annotate

A very simple problem in SQL made a little unclear by the Django modelling system.

Thankfully, like the rest of Django it's quite easy to use.

qs = Category.objects.filter(user = current_user)
qs = qs.annotate(num_items = Count(items'))
qs = qs.filter(num_items__gt = 0)

In this example, we're able to filter prior to grouping using annotate(), then using the annotated field name "num_items" to filter out any categories without items.

The reason why we use annotate() rather than aggregate() is because annotate() will simply create an alias for the Count (or Avg, Min, Max, etc).

The aggregate() function on the other hand will execute the QuerySet and return the results, not making it possible to do further filters.

brick-wall-corner-fixed-with-legos
Another building block for knowledge.

Sources

Django: Run the development server in multi-threaded mode

If you were to have content in your template which displayed content from an RSS feed hosted by your dev server, it would time out.

The reason why this happens is because the standard Django dev server does not support concurrency natively.

That means the first request to your template page would stay open while the tag opens a secondary connection to your RSS feed.

Because the dev server is single-threaded, it would keep waiting until the first request is finished before allowing the RSS thread to be parsed.

Eventually it times out and gives up, giving you an error.

Luckily, to get around this you don't have to modify the core Django files.

A user at github named James Aylett (jaylett) has created an excellent Django command called runconcurrentserver which allows you to start the server using an alternate command instead of "runserver" while still supporting the same arguments.

To use it:

  • Simply grab the files off his git repository or download using the browser.
  • Extract (if you downloaded the archive)
  • Move the files from "concurrent_test_server" and save it in "your_project/django_concurrent_server".
  • Add it to your INSTALLED_APPS settings
  • Now you can run it using:

python manage.py runconcurrentserver

Easy as pi.

tumblr_lcmt12RuJb1qai0xlo1_250 
Now you can continue being awesome.

Sources

django: Easy way for template tags to add information to template context

I've been seeing a pattern emerging with Django template tags that I've been writing and it's starting to annoy me.

Example usage:

{% some_tag by request.user as context_var %}
{% for item in context_var %} ... {% endfor %}

The template tag would be:

from django.template import Library, Node, Variable

register = Library()

@register.tag
def some_tag(parser, token):
bits = token.split_contents()
tag = bits.pop(0) # pop tag
context_var = None

if len(bits):
context_var = bits.pop(0)

user_var = Variable(bits.pop())
return SomeTagNode(context_var, user_var = user_var)

class SomeTagNode(Node):
def __init__(self, context_var, user_var = None):
self.context_var, self.user_var = context_var, user_var

def render(self, context):
context[self.context_var] = SomeModel.objects.filter(user = self.user_var.resolve(context))
return ''

As you can see, there is some fluffing involved with creating a new class for something that could be done easily. The trick is finding a way to make it easier to re-use.

I found it annoying that registering tags using Library.simple_tag() automatically parses the context values (but did not allow access to it) and Library.inclusion_tag() supported the use of takes_context but the regular Library.tag() didn't.

Place this code in a re-usable file.

from django.template import Node

class ContextNode(Node):
def __init__(self, func):
self.func = func

def render(self, context):
return self.func(context)

Now if you want to create a new tag:

from django.template import Library, TemplateSyntaxError, resolve_variable

register = Library()

@register.tag
def some_tag(parser, tokens):
bits = token.split_contents()
tag = bits.pop(0) # pop tag
context_var = None

if len(bits):
context_var = bits.pop(0)

user_var = bits.pop()

# This is a wrapper function to accept the context variable
def some_tag_wrap(context):
context[context_var] = SomeModel.objects.filter(user = resolve_variable(user_var, context))
return ''

return ContextNode(some_tag_wrap)

This makes life much simpler if all you want to do is add a variable to the context.

Also, note the use of resolve_variable(), which gets rid of the repetitively annoying use of Variable.resolve().

Now you can go back to doing things in life that matter.

2602541719_cffba86acc_z

Portal 2: Wheatley does not shoot bombs at you

In the battle against the final boss, there is a glitch that seems to have hit quite a few people.

I was enjoying hearing him ramble for about 3 minutes, then realised the game had a bug.

I tried a few times to trigger the shooting mechanism but nothing seemed to work.

On the odd occasion when he would shoot a bomb out, it'd either hit the over-zealous shield or drop right onto me (if I was below him).

So, the only solution I could find was to create a new game and continue from the start of Chapter 9.

It doesn't take long to get to the final boss if you know what you're doing.

Great game, that was the only major glitch I ran into after patch 2 was applied. Everything else worked wonderfully, great work Steam!

image

Python: Decorators with support for variable args and keyword arguments (kwargs)

This took a while to wrap my head around. Why the hell do people always nest their decorators like Osama Bin Laden's cave structure?

For example we have this function, decorated with the decorator "@varnish".

@varnish(max_age = 9000)
def blah(request, id):
return HttpResponse("Hi there")

It turns out that's an necessary evil because of the way arguments are passed.

def varnish(use_esi = False, max_age = 0):
def wrap(func):
def wrapper(*args, **kwargs):
response = func(*args, **kwargs)
esi(response, use_esi = use_esi, max_age = max_age)
return response

return wrapper

return wrap

The first method varnish() takes in the arguments for the decorator. This is simple enough.

The second method wrap() takes in the function being decorated and nothing else. This was the bit which was causing me grief as I was expecting more arguments.

The third method wrapper(), which I thought was unnecessary, receives the original arguments which should have been passed to the decorated function.

So by the third level of nesting you'll have yourself the actual body of the decorator. Annoying huh?

Now that you've figured it out, show em who's boss!

1302670108541

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