Matplotlib, shared axes and formatters

I Just spent quarter of an hour or so being perplexed an annoyed by matplotlib.

It turns out that if you use the sharex property when creating subplots, plotting on these later plots will override any
previous formatter set on the other plots. (This in a way makes sense – since all the plots axes must be redrawn to take account of the facts that the axis might have grown).

This means that if you want to set a formatter (or a tick locator) this must be done after the final plot that shares an axis.

Bad:

plot1 = subplot(121)
plot(stuff)
gca().xaxis.set_major_formatter(CrazyFormatter)

subplot(122, sharex=plot1)
plot(other_stuff) # destroys the first formatter

Good:

plot1 = subplot(121)
plot(stuff)

subplot(122, sharex=plot1)
plot(other_stuff) # destroys the first formatter
gca().xaxis.set_major_formatter(CrazyFormatter)

Relevant links:

Ticker api
Pyplot api

Add comment February 6, 2010

Nvidia twinview – changing the screen order

This took me a while to get working. I couldn’t seem to get nvidia-settings to do what I wanted to do, though I may have just been being inept.

The procedure I used was as follows:

  • Backup up your xorg.conf (/etc/X11/xorg.conf)
  • Open xorg.conf in a text editor as root
  • Find the “metamodes” option in the “screen section”
  • Switch around the offsets until you think you have the right settings. (Offers look like +x+y)
  • Restart x (you can do this with Alt – SysRq – K (and on some systems Ctrl-Alt-backspace)

There is documentation about this here:
http://http.download.nvidia.com/XFree86/Linux-x86/1.0-8178/README/appendix-g.html

Add comment January 26, 2010

Getting emacs to behave more like vim

Although the viper mode does not provide a lot of vim’s motions e.g diw and similar. The vimpulse plugin (http://www.emacswiki.org/emacs/download/vimpulse.el) does extends viper to provide several of these.

Supported commands in include

diw, ciw, yiw, di”, da”, ci”, ca”, yi”, ya”,
di(, da(, ci(, ca(, yi(, ya(,
di’, da’, ci’, ca’, yi’, ya’,

(take that google)

I find these vim text objects fairly useful.

Add comment November 22, 2009

Making viper mode in emacs use C-[ for escape rather than escape

Pressing the actual escape button is far too much effort, so my brain seems to have decided to learn to us C-[ in vim in preference to escape.

To get this working in viper add the following line:

(setq viper-ESC-key “\C-[“)

To your emacs init file before you have required viper. Note that this variable cannot be set in your .viper file or changed after you have loaded viper, or rather it can but it has no effect.

1 comment November 18, 2009

viper-want-ctl-h broken when set in .viper

This happens in the emacs viper vim emulation mode shipped with ubuntu 9.10 in November 2009.

There is a work around by setting viper-want-ctl-help-h in your emacs init file after viper has been imported.

This bug occurs because viper-set-expert-level which is called as part of loading viper tramples on various viper settings. However it does need to set those settings which have not been overwritten in your .viper file.

As a workaround in viper one could do one of the following:

i) Make viper-set-expert-level only set those settings which are not already set if dont-change… is set to true
ii) Load the .viper file twice once after calling set-expert-level (hackish but it works)
iii) Do something crazy so as to have shadowed variables, where the set-expert-level only sets the value that is shadowed.

However, I am not going to change any of this at the moment.

Add comment November 18, 2009

Why might a set API be useful

Why use a set api rather than a list API if one doesn’t care about performance

In most languages in built set classes have better performance than lists. But suppose one doesn’t care about performance – why would you use a set rather than a list.

Broadly speaking a set is distinguished from a list by the lack of

a) Ordering
b) Duplication of elements.

How can these properties be useful. In a sense it isn’t true that sets don’t have an ordering, since in most languages you can iterate over the members of a set – rather they just don’t have a very good ordering. So this is not really of any use to us.

So the only thing that could be useful about a set api is that it allows one to avoid duplication of items without writing any code to do this. This will be useful for any problems in which you explicitly want to avoid duplication, examples of this include:

* Only wanting to email a number of people once
* Only wanting to rerun tests once
* Only wanting to list each result once (but having an algorithm that generates duplicates).

This concept of avoiding duplication can be generalised

A dictionary allows one to avoid duplication of parts of an object. That is, if we consider two objects to be near enough identical only parts of them match then we can use these parts as keys in a dictionary – and thereby avoid duplication.

In fact we can encapsulate this behaviour in an equivalence set – a collection with ensures uniqueness up to some equivalence function (if our elements are immutable we could use the following).

class EquivalenceSet(object):
def __init__(self, getRepr):
self.getRepr = getRepr # get representation of equivalence class
self.mapping = {}

def add(self, el):
self.mapping[self.getRepr(el)] = el

def __iter__(self, el):
return self.mapping.itervalues()

This assumes that out “uniqueness” can somehow be represented by a function such that f(x) = f(y) implies x and y are equivalent . However, sometimes we have more interesting notions of not “unique” for example if we are representing objects in a plane – two objects might only be considered “unique” if they do not intersect. If we are in this situation it may not be clear what we should do when elements are not unique.

Add comment August 3, 2009

Javascript: keyCode versus charCode

Javascript key press events have both a keyCode and a charCode property. These are mutually exclusive – whenever one is non-zero the other is zero.

Which one is set depends on the type of event: keydown and keyup events give one events with keyCode set (they produce corresponding character) whilst keypress events give one events with charCode set.

Add comment July 26, 2009

Automatically loading a truecrypt share at startup

I’m toying with the idea of moving all of my data into the cloud, or rather, keeping all of my data dropbox so that I can access if from 2 different machines and have those changes synced without thinking, and so that I’m less dependent on any single piece of hardwire.

However, although I want some data to be present on all the machines I use, I don’t want all data to be present on every machine I use, and I don’t think I can easily have several dropbox shares.

One solution is to keep some of the data in a truecrypt volume which is automatically mounted on some machines but not on others.

For this purpose I adapted the following bash init script from here. This takes a truecrypt file, reads a password from disk and mounts the file in my home directory. I’m suspicious that there might be problems with conflicts when dropbox updates the truecrypt file whilst it is already mounted… but we’ll see. (dropbox has version control so I should be moderately safe).

Note that this approach may place your volume password into the list of processes – so you might prefer not to use this on shared machines. Also, you probably would want to change the umask and the owner of the share.

#!/bin/bash
#
#   /etc/rc.d/init.d/truecrypt
#
# Mounts the /home partition with truecrypt.
#
# chkconfig: 2345 90 10
# description: Truecrypt

# processname: truecrypt

[ -x /usr/bin/truecrypt ] || (echo "truecrypt can't be found" ; exit 1)

RETVAL=0
prog="truecrypt"
desc="Truecrypt" 

start() {
   echo -n "Mounting encrypted volume..."
   uid=$(cat /etc/passwd | grep moment | cut -d ':' -f 3)
   truecrypt -t --fs-options='umask=000,user' --non-interactive VOLUMNE_FILE VOLUME_MOUNT_POINT -p "$(cat PASSWORD_FILE)"
   RETVAL=$?
   [ "$RETVAL" == "0" ] || (echo "FAIL" ; exit 1)
   echo "OK"
}

stop() {
   echo  -n  "Unmounting encrypted volume..."
   truecrypt -t -d /home/moment/cryptshare
   RETVAL=$?
   if [ "$RETVAL" == "0" ]; then
        echo "OK";
   else
      echo "FAIL";
   fi;
}

case "$1" in
  start)
   start
   ;;
  stop)
   stop
   ;;
  restart)
   stop
   start
   RETVAL=$?
   ;;
  condrestart)
        [ -e /var/lock/subsys/$prog ] && restart
   RETVAL=$?
   ;;
  *)
   echo $"Usage: $0 {start|stop|restart|condrestart}"
   RETVAL=1
esac

exit $RETVAL

Not sure whether this is a good use of time…

Add comment May 22, 2009

Reading files in factor

Working code for the impatient

The following factor code reads and counts the number of words in the file “/etc/fstab”

USING: io.encodings.ascii io io.files prettyprint splitting sequences ;
"/etc/fstab" ascii file-contents " \n\t" split length .

See also

Official api docs.

Add comment April 10, 2009

De-nesting decorators in python

Definitions of decorators are quite nested

def decorate(f):
    def patched(*args, **kwargs):
        # do stuff involving f
    return patched

About 25% I also forget to write the final “return patched”.

One way to work around this is to write a ‘denest decorator decorator’ so you can write the following as an alternative to the above:

@denest
def decorate(f, *args, *kwargs):
    # do stuff involving f

This has the disadvantage that you can’t perform operations at the time of decoration – but it simplifies code slightly for the standard case (at the cost of making your code less idiomatic).

The denest decorator is defined like this:

def denest(func):
     def decorate(f):
           def patched(*args, **kwargs):
               return func(f, *args, **kwargs)
            return patched
     return decorate

Example usage:

A decorator that converts converts a function which could raise an Excpetion into a function which returns None on error.

@denest
def makeIntoTry(f, *args, **kwargs):
    try:
        return f(*args, **kwargs)
    except Exception:
        return None

Add comment April 6, 2009

Previous Posts


Meta

Facets

Add new tag AOP apt aspect oriented programming assumes knowledge autiobiographical bash scripts bell books clarity code samples configuration console emacs for the benefit of google functional programming graphical design hacks higher-order functions howtos intention revealing programming keyboard links linux note to self opinions parsing patterns philosophising philosophizing programming python random ideas refactoring removing packages stories succinct svn systems stuff theoretical philosophizing typing vim viper work ethic you probably don't want to read this

Archives

Pages

 

February 2010
M T W T F S S
« Jan    
1234567
891011121314
15161718192021
22232425262728