Start headless vbox on windows

start-process ‘C:\Program Files\Oracle\VirtualBox\vboxheadless’ ‘-s yourVMNameHere‘ -WindowStyle Hidden

This powershell command will start your virtualbox machine. We’re going to set things up so you can do it by clicking on an icon.


Your Mileage May Vary: The stuff below worked great at work, but I’ve yet to work out why it doesn’t on my machine at home..

VBoxHeadless.exe: error: Code E_FAIL (0x80004005) - Unspecified error (extended info not available)
Context: "PowerUp(progress.asOutParam())" at line 1138 of file VBoxHeadless.cpp

A while back I posted about starting a virtualbox virtual machine without having the console, or the vbox manager, or a dos box hanging around. It’s a strangely popular post?! I just want to click an icon and my virtual machine starts and I don’t see it. Either it just does it’s thing, or I ssh into it; like a real server. Seems I’m not alone. That method is long in the tooth. This works for me on Windows 7…

1. The powershell script


Start -> Notepad

and put the following into the file. Substitute “myVMNameHere” for the name of your virtual machine (as it appears in bold in the virtualbox manager):

start-process 'C:\Program Files\Oracle\VirtualBox\vboxheadless' '-s myVMNameHere' -WindowStyle Hidden

Save to your desktop with the filename extension of “.ps1″. eg: “myVMName.ps1″

2. Set powershell scripts executable

You only need to do this once, perhaps not at all. By default windows does not permit users to execute their powershell scripts. You probably need to have permission to set the permission.


Start -> powershell -> right click -> run as administrator

And type in:

Set-ExecutionPolicy RemoteSigned

And say “Y” for yes.

3. Right-click -> “Run with Powershell”

To run it right click on the icon and you should get a “Run with powershell” option. Do that.

Trouble

  • If you have the virtualbox manager open, the preview is updated realtime so you can sort of see what is currently on the machine console.
  • If the machine won’t start open the script (right-click -> edit) replace the “-WindowStyle Hidden” option with “-RedirectStandardError filename”. Then run it. The error output will appear in a new file named ‘filename’ on your Desktop.
  • Looking at the error output generally told me nothing useful. Problems are probably permissioning issues. Run powershell as administrator and see what happens when you type the command in manually. I’ve had a dialog from Windows Firewall come up and need clearing on some machines.
  • open the task manager and look for, and/or kill, the “vboxheadless.exe” process.
Posted in geek | Leave a comment

“Don’t Play” videos on smh.com.au

The smh.com.au website has an annoying habit of putting videos at the top of their “news” articles. That is: 15 seconds ads appear on many of the pages followed by the news story. The only way to avoid the ad is to locate and hit the “Don’t Play” button within 5 seconds.

Drives me nuts. So I got proactive and knocked up a little chrome extension to simply remove the video altogether. If you have Chrome, click on this, say “yes, I trust you John” and you can read the latest “news” annoyance free.

http://programmerforhire.com.au/dontplay.crx

Tested only on Chrome v11.0.696.65 beta-m

The five websites it applies to are:

  • smh.com.au
  • theage.com.au
  • watoday.com.au
  • brisbanetimes.com.au
  • businessday.com.au

The code inside is really simple…

$(document).ready(function(){
    $('#video-player-content').empty()
})

If I get excited one night I’ll bother to narrow it down to just reversing the playing functionality – so that we still have the option of watching the ad/story if we choose.

Posted in life | Leave a comment

Razer Gaming Products = spam

Just a little bitch and moan.

I purchased a Razer Lachesis and accompanying mouse mat about 3 years ago (from a retailer).

Initially I had some very annoying problems with the mouse; it had a glitch which caused the cursor to jump to the top-right of screen. Often enough and irritatingly enough to invest time into researching the problem. Sure enough I wasn’t the only one and eventually they released a firmware upgrade which reduced the problem but didn’t fix it.

The other complaint was that their branded mouse mat – marketed as the perfect accompaniment to optimize usage of the mouse – was complete rubbish and the mouse actually worked better without it – on the bare table. That’s when it wasn’t jumping to the top right of screen unpredictably.

So, after overspending an embarrassing amount of money on this stuff I gave up and flogged it all to some poor sod on eBay for mere pennies.

But the real cause for complaint, and the motivator for this post, is I have been getting spammed by Razorzone ever since. For the first couple of years the “unsubscribe” link just said “you are unsubscribed” – yet I still received the spam. But still I try. On 18/10/2010 I actually got an email “You are unsubscribed”. Yet clearly I’m not. Today the “unsubscribe” link is completely broken.

Which all speaks a lot about how competently the company is run.

Incompetent people.
Shit products.

Avoid.

Posted in geek | Leave a comment

[django] Creating dynamic lists of radio buttons from arbitrary classes and with long descriptions

I was looking for a way to put a lot of text next to the radio buttons in a django form. I also needed the list of radio buttons to automatically populate and vary according to the situation.

After the documentation for django being so awesome everywhere else; there is currently bugger all for this corner of the world: the radio widget. Fat lot of use that is.

It seems like django isn’t set up to do much to help you at first; but at second glance (ie: after wandering down vastly more complicated paths for hours) the solution in front your nose does work; with a bit of sourcery of course.

The second element of the tuple is presented inside the “label” tag – so any inline elements are permissible; for example:

The desired result

Or something like it

    <ul>
      <li><label for="id_ticket_0">
          <input type="radio" id="id_ticket_0" value="PARTTIME" name="ticket"/>
          <em>Part Time</em> Valid on Friday Night and Saturday Only
      </label></li>
      <li><label for="id_ticket_1">
          <input type="radio" id="id_ticket_1" value="DAYTIME" name="ticket"/>
          <em>Casual</em> Valid on Saturday Only
      </label></li>
      <li><label for="id_ticket_2">
           <input type="radio" id="id_ticket_2" value="EARLYBIRD" name="ticket"/>
           <em>Early Bird</em> Valid on Friday, Saturday, and Sunday. $15 discount for booking before 1am January 3rd, 2011
       </label></li>
    </ul>

The simple example

The trick is to “mark_safe” the content of the description then stuff whatever you need into:

    from django.utils.safestring import mark_safe
    choices = (
      ('1', mark_safe(u'<em>One</em> | This is the first option. It is awesome')),
      ('2', mark_safe(u'<em>Two</em> | This is the second option. Good too.'))
    )

The complex example

So in this example we:

  1. assemble the choices into a list (any iterable structure will do)
  2. pass the structure to the form’s __init__ to create our radio options on the fly
  3. use a comprehension list to create an extended description for each radio option
  4. The data structure:
    Tickets are my own classes and they have attributes:

    • tickets.code – as in a ticket code
    • label – a pithy short description
    • help – a longer description

    But more about that later. First lets create some instances:

        from mymodule import ticket
        # so lets create a few
        fulltime = ticket('FULLTIME',160,'Full Time',
                      "Valid Monday to Friday inclusive")
        parttime = ticket('PARTTIME',110,'Full Time',
                      "Valid outside of business hours only")
        daytime  = ticket('DAYTIME',70,'Day Time',
                      "Valid only on weekends and public holidays")
    
        # and put them together in a list any way you like
        available_tickets = [fulltime, parttime, daytime]
    
        # now create the form
        OrderForm(tickets=available_tickets)
    

    That probably happened in your *view* code. Now to see what happens in the *form*

        class OrderForm(ModelForm):
    
            def __init__(self, *args, **kwargs):
                self.tickets = kwargs.pop('tickets')
                super(OrderForm, self).__init__(*args, **kwargs)
    
                choices = [(t.code, mark_safe(u'<em>%s</em> %s' % (t.label, t.help)))
                        for t in self.tickets]
                self.fields['ticket'] = forms.ChoiceField(
                    choices = choices,
                    widget  = forms.RadioSelect()
                )
    
Posted in geek | Tagged | Leave a comment

Is there a Django template tag that lets me set a context variable?

The answer is buried inside the more complex current_time example in the documentation.

Problem

You want to add a variable to the context. But you don’t want to go back and add that variable to all the views which call all the templates which invoke the tag. You just want a tag which can add some data to the context wherever its wanted. I’m looking for this kind of thing when rendering those random distractions which get dropped into sidebars and aren’t specifically related to the work of the main view, for example.

Method

To inject a variable to the context you need access to the context. To do that your custom tag will inject a node which added the data to the template context.

Example

This example adds a “coming_events” queryset to the context then loops over each result. It does that by declaring a custom tag which renders a node which adds a queryset to the context.

from django import template
from apps.events.models import Event
register = template.Library()

@register.tag
def coming_events(parser, token):
    return EventNode()

class EventNode(template.Node):
    def render(self, context):
        context['coming_events'] = Event.objects.all()
        return ''

You’d use it like this:

{% load events %}
{% coming_events %}
{% for event in coming_events %}
<div class="eventItem">
   <p>{{event.title}} {{event.data}}</p>
</div>
{% endfor %}

Extra Credit

If you’re really keen to be able to name the variable arbitrarily eg {% coming_events as events %} then look closely at the example in the documentation and note how they split the token into what’s before the ‘ as ‘ and what’s after and use the latter part to name the context variable. You’d have to implement that.

Note that if I wound up putting the HTML for each event into its own dedicated template then I’d be better off just following the standard inclusion tag example in the documentation. This solution is suggested for when you want the data without any baggage.

As posted to http://stackoverflow.com/questions/2566265

Posted in geek | Tagged | Leave a comment

Civilization V Review – First Impressions

Civ V (or “Civilization 5″) is a “God” strategy computer game where you rule a country and attempt to take over the world. Although when put under such harsh light the fun of bludgeoning all whom you meet into submission does come into question, so there are a couple of alternative ways to “win” for the lesser megalomaniac.

These are my first impressions of playing the latest release – Version Five – released yesterday.

Ultimately there is nothing new. The gameplay is Civilization IV with a new, shiny UI and a bunch of tweaks. You still spend all your time pushing units around and building stuff in your cities. If you’re expecting exciting new toys, twists, turns, anything radically different to get your teeth into you’ll be disappointed. I dare say it feels a lot like the transition from Windows XP to Window 7… nice to have, but not essential.

Positives

Military units don’t “stack” anymore. I’m actually liking this because it makes warmongering more tactical: you can form a “front”, turn flanks, and generally do battlefield maneuvers.

Units can walk on water! It took me a little while to discover this, but now I’ve found it I like it. None of that mucking about getting units to a ship and boarding and sailing and disembarking… Now your units can just step onto the water and make their own way to places. I think this could be big.

Not Sure

The civics have changed substantially in implementation, but not in essence. You still follow the threads of being a democratic, autocratic, or whatever government trait, but at first I thought you just went about collecting all eight (ten?) traits and that was all there is to it. But no, each one has about 5 sub-elements which can be worked through giving depth. I need to replay to learn the value of going down the tree rather than across.

City-States are still a bit of a mystery to me. I’m little like “what’s the point”. On the one hand it seems a blight on the landscape to have foreigners sitting in the middle of my empire – why wouldn’t I just invade and have them as native cities? On the other hand why bother? They don’t seem to be much of a threat. The value of the city states is not black and white yet. However I did take note that a civ on the other side of the planet can ally with a city-state irrespective of geographics and gain some critical resources. They might make for interesting pawns in multiplayer games.

Negatives

Mostly just issues with the UI:

The map has left and right edges, which was rather irritating, as I can’t watch my boat sail west around the world; instead I set sail west, then have to roll the map far east to see where it went.

You can zoom in and out, but not rotate the board. I rather liked getting things from a different perspective.

Managing lots of cities is as hard as ever; I can’t get a solid picture of food, production, culture of each city relative to one another. For example, which city has the most production is hard to establish – the ‘sort by production’ feature sorts by unit in production – not how much the cities are producing. Flicking through cities still jumps you all over the board in no apparent order making it impossible to focus on a specific region of the board.

I spend a fair bit of time just scouring the board looking for the icon which represents some elusive resource. The resource view becomes so cluttered it’s impossible to find anything. Just needs to be able to filter some things in/out.

Conclusion

Civ 5 is an incremental improvement. They’ve taken care to keep everything pretty much the same, just newer.

Posted in life | Leave a comment

Django widget renderer render

I got a little frustrated trying to find the ‘simple’ answer to change the html which is generated by the various form field widgets.

In this case the RadioSelect field generates radio buttons wrapped in an unordered list. It was annoying, and whilst I could resort to writing the html directly in the html; that’s not ideal.

The solution is not hard, just not well documented.

We need only write a “render” routine to return the string we want. Then override the default widget with our renderer, and finally specify all that in the form field definition:

from django import forms
from django.forms import ModelForm
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode

FULFILMENT_CHOICES = (
    ('Post','Post'),
    ('Pickup','Pickup')
)

class MyRadioRenderer(forms.widgets.RadioFieldRenderer):    """Render radio buttons without the <li>"""
    def render(self):
        return mark_safe(u'\n%s\n' % u'\n'.join([u'%s'
                    % force_unicode(w) for w in self]))

class OrderForm(ModelForm):
   fulfilment = forms.ChoiceField(
              widget=forms.RadioSelect(renderer=MyRadioRenderer),
              choices=FULFILMENT_CHOICES)

Produces:

<div class="orderValue">
<label for="id_fulfilment_0"><input type="radio" id="id_fulfilment_0" value="Post" name="fulfilment"/> Post</label>
<label for="id_fulfilment_1"><input type="radio" id="id_fulfilment_1" value="Pickup" name="fulfilment"/> Pickup</label>
</div>
Posted in geek | Tagged | 1 Comment

How to complete the BAS Online

The Australian Tax Office (ATO) have a very tiresome mandatory requirement for all business’s to submit a form every 3 months. The effect of the “Business Activity Statement” (BAS) is to tell the ATO how much they should bill you for; and they will chase you hard for the money that you’ve just told them that you owed them, so be prepared to pay it.
Continue reading

Posted in life | Tagged | 6 Comments

How to configure an open samba share

I’m always battling to expose my linux virtual machines to my windows desktop. Here is a sample smb.conf which completely exposes a directory to a specific IP address:


security = share
hosts deny = ALL
hosts allow = 192.168.1.99

[www]
path = /var/www
available = yes
browsable = yes
public = yes
writable = yes
force user = www-data
guest account = www-data
guest ok = yes

Posted in geek | Tagged | Leave a comment

[Django] How to replace an image using ModelForm

I have a user profile model which holds their ‘mugshot’ image. I’m using modelForm to to present a profile update form. It was easy to build a working form, but now I need a couple of tweaks to the image:

1) it saves with the filename that the user provides; I rather dictate the filename to use. I thought I’d just use the PK of the model, and the same file extension eg: “443.jpg”

2) it should replace the existing image, not append an underscore like “443___.jpg”.

Here’s my model and form:

class Member(models.Model):
    home_phone      = models.CharField(max_length=10, blank=True)
    image           = models.ImageField(upload_to='members', default="default.png")
    ...

class MemberProfileForm(forms.ModelForm):
   home_phone      = AUPhoneNumberField(required=False)

   class Meta:
       model = Member
       exclude = ('email','password','create_date','last_login','is_active')

This seems to solve it by altering the filename and deleting the existing file prior to the form save.

form = MemberProfileForm(request.POST, request.FILES, instance=request.member)
if form.is_valid():
    if form.cleaned_data['image']:
        (path, extension) = os.path.splitext(form.cleaned_data['image'].name)
        form.cleaned_data['image'].name = ('%s%s' % (request.member.id, extension))
        request.member.image.delete()
    form.save()

… excepting that most people probably want ‘request.user’, where I have ‘request.member’.

Posted in geek | Tagged | Leave a comment