Mounting a USB Stick in Linux

Here is a quick way to mount a USB thumb drive in Linux. Most distros will recognize the USB stick when you plug it in, but it case they don't then this command comes in handy:

sudo mount -t vfat /dev/sdf1 /mnt/cruzer/

Now you can access and browse the contents of the usb stick by change the current directory to /mnt/cruzer/ . Your mileage may vary and your Linux distro may have a different file system hierarchy.

Errors with the prepopulate_from SlugField parameter in Django 1.2.1

I recently upgraded to Django version 1.2.1 and I immediatelly noticed that some of my models were broken with the following error:


C:\test>python manage.py syncdb
Traceback (most recent call last):
  File "manage.py", line 11, in 
    execute_manager(settings)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\__init__.py", line 438, in execute_manager
    utility.execute()
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\base.py", line 217, in execute
    self.validate()
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\base.py", line 245, in validate
    num_errors = get_validation_errors(s, app)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\validation.py", line 28, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\loading.py", line 146, in get_app_errors
    self._populate()
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\loading.py", line 61, in _populate
    self.load_app(app_name, True)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\loading.py", line 78, in load_app
    models = import_module('.models', app_name)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\utils\importlib.py", line 35, in import_module
    __import__(name)
  File "..\tso\blog\models.py", line 50, in 
    class Category(models.Model):
  File "..\tso\blog\models.py", line 53, in Category
    slug = models.SlugField(unique=True, prepopulate_from=('title',), help_text='Used in the category URL. Must be unique')
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\fields\__init__.py", line 988, in __init__
    super(SlugField, self).__init__(*args, **kwargs)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\fields\__init__.py", line 542, in __init__
    super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'prepopulate_from'

So I did a little bit of research on this problem and I found the following explanation for what is going on:

Changed prepopulate_from to be defined in the Admin class, not database field classes

As of [4446], the prepopulate_from option to database fields no longer exists. It's been discontinued in favor of the new prepopulated_fields option on class Admin. The new prepopulated_fields option, if given, should be a dictionary mapping field names to lists/tuples of field names. This change was made in an effort to remove admin-specific options from the model itself. Here's an example comparing old syntax and new syntax:


# OLD:
class MyModel(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    slug = models.CharField(max_length=60, prepopulate_from=('first_name', 'last_name'))

    class Admin:
        pass

# NEW:
class MyModel(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    slug = models.CharField(max_length=60)

from django.contrib import admin

class MyModelAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('first_name', 'last_name')}

admin.site.register(MyModel, MyModelAdmin)

The above is taken from the Django wiki page that talks about the newforms-admin branch.

This is why the command line will never die

A while back I wrote about the address line of the browser being the new command line. It turns out I was wrong. The command line itself is the new command line.

I ran into this Google Code project today via my tweeter feed. GoogleCL allows the nerd in me to interact directly with several Google services from a shell prompt. It includes interfaces to Blogger, Picasa, Calendar, Contacts, Docs, and YouTube. You can find several scripting examples under the project's Wiki.

The fact that this is a python script and it's open source is really interesting to me. I am thinking that I need to integrate all of this into an Emacs mode.

CSharp: Testing a Generic Class

I just posted this question to StackOverflow and I am repeating it here for posterity as the pastebin code expires after a month:

More than a question, per se, this is an attempt to compare notes with other people. I wrote a generic History class that emulates the functionality of a browser's history. I am trying to wrap my head around how far to go when writing unit tests for it. I am using NUnit. Please share your testing approaches below.

The full code for the History class is at pastebin.com: http://pastebin.com/ZGKK2V84. A full version of the code is also available below:


using System;
using System.Collections.Generic;

namespace Gorauskas.DataStructures {

    /// 
    /// A history data structure that provides the same functionality
    /// as a browser history, but allows you to use any type
    /// 
    /// The type parameter
    public class History<T> {

        private Stack<T> _forward = new Stack<T>();
        private Stack<T> _backward = new Stack<T>();

        private T _current;

        public History() { }

        /// 
        /// This contructor set the Current pointer to an initial object of type T 
        /// 
        /// An item of type T
        public History(T item) {
            this._current = item;
        }

        /// 
        /// Returns the current item that it is pointing to
        /// Pushes the state of the current pointer into the backward stack
        /// and sets the new current item. If the forward stack has items in it
        /// then clear that too.
        /// 
        public T Current {
            get {
                return this._current;
            }

            set {
                if(this.CanMoveForward)
                    this._forward.Clear();

                if (!(this._current == null))
                    this._backward.Push(this._current);

                this._current = value;
            }
        }

        /// 
        /// Tells if the current pointer can be moved forward in history.
        /// 
        public bool CanMoveForward {
            get { return this._forward.Count > 0; }
        }

        /// 
        /// Tells if the current pointer can be moved backward in history.
        /// 
        public bool CanMoveBackward {
            get { return this._backward.Count > 0; }
        }

        /// 
        /// Moves the current pointer one item back in history
        /// 
        /// The current item
        public T Back() {
            if (this.CanMoveBackward) {
                this._forward.Push(this._current);
                this._current = this._backward.Pop();
            }

            return this._current;
        }

        /// 
        /// Moves the current pointer one item forward in history
        /// 
        /// The current item
        public T Forward() {
            if (this.CanMoveForward) {
                this._backward.Push(this._current);
                this._current = this._forward.Pop();
            }
            
            return this._current;
        }

        /// 
        /// Adds the entire history in chronological order to a list of T
        /// 
        /// A ordered list of history items
        public List<T> Dump() {
            List<T> l = new List<T>();

            if (this.CanMoveForward) 
                l.AddRange(this._forward.ToList<T>().Reverse<T>());

            if (!(this.Current == null)) 
                l.Add(this._current);

            if (this.CanMoveBackward) 
                l.AddRange(this._backward.ToList<T>());

            return l;
        }
    }
}

Automating Emacs Build and Install from Source

A little while back I wrote up my notes on how to build and install Emacs from souce on Ubuntu.

I have now automated the task in the form of the crude script provided below. The script takes one parameter: gui. This parameter tells the build whether you intend to do a GUI or command line only build of Emacs. It also writes out some messages to a file called emacs-build.log ... Enjoy!

#! /bin/bash
echo "Building @`date`" | tee -a ~/emacs-build.log
mkdir ~/emacs-src
cd ~/emacs-src

echo "Installing pre-requisites" | tee -a ~/emacs-build.log
apt-get -q -y install build-essential gcc git-core texinfo libncurses5-dev 

if [ "$1" = gui ]; then
    echo "Installing GUI pre-requisites" | tee -a ~/emacs-build.log
    apt-get -q -y install libgtk2.0-dev libtiff4-dev libgif-dev libjpeg62-dev libpng12-dev libxpm-dev
fi

echo "Cloning Emacs Git Repo" | tee -a ~/emacs-build.log
git clone git://git.savannah.gnu.org/emacs.git

cd ./emacs

echo "Configuring build" | tee -a ~/emacs-build.log
if [ "$1" = gui ]; then
    ./configure
else
    ./configure --without-x
fi

echo "Building source code" | tee -a ~/emacs-build.log
make
echo "Installing emacs" | tee -a ~/emacs-build.log
make install
echo "Clean up" | tee -a ~/emacs-build.log
cd ~/
rm -rf ~/emacs-src
echo "All Done!" | tee -a ~/emacs-build.log

Generate .NET Assemblies from Iron Python

The other day I was talking to a fellow programmer and the question of compiling Iron Python code into .NET assemblies came up. So what if you have an Iron Python script that you want to run and then have the ipy interpreter output an assembly that you can run on other machines. How do you do that?

There are several ways to approach the problem. One way is to use an IDE, but IDE support for Iron Python is still a bit lacking. One IDE that provides Iron Python great support is SharpDevelop. In SD you can create a Iron Python project, write your code as you normally would and then build your project. The compile assemblies can then be found in the build output folders for that project.

The other way to do this is through a tool that ships with IronPython called Pyc or the Python Command-Line Compiler. If you installed the latest version 2.6 of IronPython, then pyc.py will be available at C:\Program Files (x86)\IronPython 2.6\Tools\Scripts or wherever you installed IronPython on your system. If you have earlier versions of IronPython then pyc.py will be available as a separate download in the samples package.

With pyc.py you can create console or Windows assemblies from your python scripts. Basic usage looks like this:

ipy pyc.py /out:myprogram.exe /main:mainfile.py /target:exe 
    program.py support.py
The above will generate an assembly called myprogram.exe (/out) which is a console application (/target) and will execute the code in mainfile.py first (/main) and will also include code from program.py and support.py in the assembly.

Postel's Robustness Principle

Interesting comment from the trenches:

After much testing, it's clear that Postel's advice to protocol designers ("be liberal in what you accept, and conservative in what you send") invites a natural-law repercussion for JS as "protocol":

"If you are liberal in what you accept, others will utterly fail to be conservative in what they send."

Found here: http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp#1464 while looking at SpiderMonkey source code.

VMWare Server Doesn't Start After Upgrade

I have a Xubuntu 9.04 machine that is hosting some VMs running on VMWare Server. I recently upgraded a bunch of packages on the host machine and then I noticed that the VMWare Server was not starting automatically anymore. I tried running it manually and I got the error message: vmware is installed, but it has not been (correctly) configured for this system.

What happened is that one of the upgraded packages was the Linux Kernel and a new Kernel version will break VMWare because it originally compiled for the previous Kernel version that was on the machine. To fix this I had to run the /usr/bin/vmware-config.pl script to reconfigure and recompile several components. After running the script, VMWare server started up again as normal.

Let me know if you had this problem before.

Building and Installing Emacs from Source on Ubuntu

Every so often I have to setup a web development server and one of the first things I have to have on that server is Emacs. As an Emacs fanatic, I need to have the very latest bleeding-edge version. In order to ensure that, I clone the official git repository into my home directory and then I compile and build from there. Most of the time I will be performing the steps below on a Ubuntu Server distribution (these work on versions 8.10, 9.04, and 9.10) without X installed.

  1. I will assume you already have your Ubuntu server up and running.
  2. Install some packages needed for the build by running the following command:
  3. 
        sudo apt-get install build-essentials gcc git-core texinfo \
        libncurses5-dev 
    
  4. Clone the latest Emacs from the GNU git repository by running this:
  5. 
        git clone git://git.savannah.gnu.org/emacs.git
    
  6. Configure, compile and install Emacs by running the following commands:
  7.     
        cd ./emacs
        sudo ./configure --without-x
        sudo make
        sudo make install
    

Some notes: The need for the build-essentials, gcc, and git-core are pretty obvious; the texinfo package is needed for the makeinfo dependency; and the libncurses5-dev is needed for the termcap.h dependency.

The above will also work on a desktop distro, but you will be limited to a terminal version of Emacs. In order to install a graphical version of Emacs you will also need to install the following extra packages:

   
    sudo apt-get install libgtk2.0-dev libtiff4-dev libgif-dev \
    libjpeg62-dev libpng12-dev libxpm-dev

The above line will also install a bunch of other dependencies needed by the libraries. Don't forget to also remove the --without-x parameter and run just this line:

   
    sudo ./configure

Let me know how it works for you.

Some Notes on Serializing Objects in Python

I was playing with .NET serialization at work the other day and got curious about how Python does it. Serialization is a little confusing in the .NET world, but it's not an insurmountable task to grasp it. For one, there is more than a single implementation of serialization within the .NET base class library, or namely, System.Xml.Serialization and System.Runtime.Serialization, which respectively implement XML and binary serialization. The techniques used in each implementation are also disparate, having the binary serialization make heavy use of class attributes, while the XML implementation uses a method call to XmlSerializer.Serialize.

The Python implementation of serialization is much simpler, concise and easier to understand. It is implemented as a Standard Library module called Pickle. The actions to serialize and deserialize classes are implemented as simple function class and there is no need to put attributes on classes. Let's see how it works.

First import the pickle module and then declare a class called Person as in the code below:


  import pickle

  class Person(object):
    
      def __init__(self, first_name=None, last_name=None, age=None):
          self.first_name = first_name
          self.last_name = last_name
          self.age = age

Now create two instances of the Person class above and place them in a list.


  p1 = Person('Jane', 'Doe', 26)
  p2 = Person('John', 'Hancock', 33)
  people = []
  people.append(p1)
  people.append(p2)

Next serialize the list to a file and then read it back into a new list. First serialize the list:


  fname = 'peoplelist.dat'
  f1 = open(fname, 'wb')
  pickle.dump(people, f1)
  f1.close()

Finally, read the contents of the serialized file back into a new list and print out the name and age of each person:


  f2 = open(fname)
  new_people = pickle.load(f2)
  for person in new_people:
      print '%s %s is %d years old.' % (person.first_name, person.last_name, person.age)

That's it... Serialization in Python is just too easy!