Python code snippet - creating enums in python
chmarr
There's a ton of "enum" implementations for python, using named tuples, or a special class, or other things. I wanted something that looked as much as possible as an integer, but it was easy to create new instances using a symbolic name, have it print out (repr format) with that name, but otherwise be treated like any other integer.

Here's my implementation, which uses the "type" function to create a new type, inherited from "int", with all the functionality one would expect of a decently-functional enumerated type

import inspect
def enum ( name, print_str_as_name=False, **kwargs ):
	def strfn ( self ):
		try:
			return self._rev_mapping[self.real]
		except KeyError:
			return str(int(self))
	def reprfn ( self ):
		try:
			return "%s.%s" % ( name, self._rev_mapping[self.real] )
		except KeyError:
			return "%s(%d)" % ( name, int(self) )
	revmapping = dict ( [ (v,k) for (k,v) in kwargs.iteritems() ] )
	newenum = type ( name, (int,), dict ( _mapping=kwargs, _rev_mapping=revmapping, _as_name=strfn, __repr__=reprfn ) )
	# We want instances of this type to appear to be created in the caller of this function, so
	# we get the calling frame's module name, and stick it on to our new type
	try:
		frame = inspect.currentframe()
		newenum.__module__ = frame.f_back.f_globals['__name__']
	finally:
		del frame
	if print_str_as_name:
		newenum.__str__ = strfn
	for k, v in kwargs.iteritems ():
		setattr ( newenum, k, newenum(v) )
	return newenum


And Here's some example usage:


>>> Status = enum ( "Status", waiting=0, running=1, complete=2 )
>>> s = Status.running
>>> type(s)
<class '__main__.Status'>
>>> s
Status.running
>>> print "Status is", s
Status is 1
>>> print "Status is", s._as_name()
Status is running
>>> print "Status: %r" % s
Status: Status.running
>>> s == Status.running
True
>>> s == 1
True
>>> s == Status.complete
False
>>> int(s)
1


Turning an integer back into the enum type is easy.

>>> s = Status(2)
>>> s
Status.complete


If you would rather the "str" representation to show the name, rather than the integer, create the enum as follows. Note that this may break applications that expects to have the "str" turn out as an integer. Eg: web frameworks.


>>> Status = enum ( "Status", print_str_as_name=True, waiting=0, running=1, complete=2 )
>>> s = Status.running
>>> print "Status is", s
Status is running


And it pickles efficiently, since all instances of the enum are really references to the pre-constructed enum instances, which themselves are integers. There's a one-time overhead for the enum (about 60 bytes), then a smaller one-time overhead for each unique value of the enum that's pickled (about 20 bytes), then just 4 bytes for each object (same as a bare int).


>>> s1 = Status.waiting
>>> s2 = Status.running
>>> s3 = Status.complete
>>> pickle.dumps ( (s1,) )
'(ccopy_reg\n_reconstructor\np0\n(c__main__\nStatus\np1\nc__builtin__\nint\np2\nI0\ntp3\nRp4\ntp5\n.'
>>> pickle.dumps ( (s1,s2,s3,s1,s2,s3,s1,s2,s3) )
'(ccopy_reg\n_reconstructor\np0\n(c__main__\nStatus\np1\nc__builtin__\nint\np2\nI0\ntp3\nRp4\ng0\n(g1\ng2\nI1\ntp5\nRp6\ng0\n(g1\ng2\nI2\ntp7\nRp8\ng4\ng6\ng8\ng4\ng6\ng8\ntp9\n.'


Edit: added frame introspection, so object pickling will work correctly. Note that any enum type must be declared outside of any class definition, which is a restriction on the pickling process.

The yearly "out of the blue" post.
chmarr
I'm in the middle of a chat with [info]normanparamedica friend of mine who's serving in Iraq at the moment, and has some great mural photos up on his site. The discussion has prompted me to post some of my thoughts here:

Terrorists are not our – the human race - current worst enemy. The media is. The media cause us to hate and anger and fear, and thus fight and blame and seek retribution and justice, rather than work together for what's possible for our world community.

The media's fundamental interest is power and money. They achieve this by keeping our attention on what they're saying, how they're spinning the world, what they're focussing our attention on. They achieve this by installing fear and anger against "others" and against our own governments. Governments that, if we could empower then rather than resisting them, could be the focal point for the sheer power of the human race.

With just a little focus, we put men on the moon... back in 1969! Imagine what we could do NOW with the technology and human resources we have. Yes, we have, all of us, done bad things in the past that we need to acknowledge and apologise for. This, however, should come secondary to creating what's possible for our future.

The media can, but has no interest in playing any part in this, and is being the worst possible detriment. The media, in its current form, needs to be shunned.

OMFG Totally Epic Hang-gliding Weekend!
flying
chmarr
In this thread:

* Site tour of Marina Beach and first time coastal soaring
* Nearly 2 and half hours of mountain soaring at Ed Levin in a single flight!
* Some more google earth flight tracks!
Details of awesomeness under cutCollapse )

Google Earth flight-track of my Ed Levin flight.
chmarr
My sole, single, lonely, one-of-a-kind, Ed Levin flight. Well, the single one off the 1750' launch, anyway.

Clicky

Super Ball
chmarr
So, I heard there was this big sporting event going on on Sunday. What was that all about?

Anyways, I've never been all that interested in watching sports, but I do find the progression of the Super Bowl logos from year to year fascinating.

I've compiled them all for your viewing pleasureCollapse )

Flying days.
flying
chmarr
Had a day off on Tuesday to attend for a few things, but they were all in the late afternoon to evening so... lets try going gliding in the morning!

Unfortunately, while the weather was great, the wind direction was not cooperating, so no opportunity to fly from the 1750-foot launch at Ed Levin.

So, a short, 2-minute flight from the 600-foot, in minimal lift, was in order. Worth-it, though, since one of the requirements for a hang-3 rating is to have 30 "flying days", and I only have 15 or so, so far; I'm more likely to reach my "10 hour" requirement, first, so getting in a flying day, even for a 2-minute flight, is worth it.

Keeping up the regular flying, to stay proficient and honed, is also worth it :)

Transportation and Storage
flying
chmarr

Glider freedom ... finally. Glider freedom ... finally.
The Vibe carries my glider for the first time. Previously I've been having friends and glider instructors get the glider out of storage and haul it up to the gliding site (wherever it may be). Given that I can now fly some cool places without instruction, having to make transportation arrangements became really inconvenient for everyone. Now, I'm free as a bird! That is, until I get to the site... I still need someone with a 4WD to hall me up the mountain :)
Storage at Home. Storage at Home.
I've built a hoist storage system in my garage with rope and pulleys (and a borrowed - for the moment - ladder).


No Hang-Gliding Today
chmarr

No Hang-Gliding today. At the top of Ed Levin County Park (near Monument Peak, California). Morning fog is thick and has not yet burned off. The wind is bitterly cold, and coming from the North East, making hang-gliding unlikely at any time today.


The last video from Hollister for a while
flying
chmarr
... I promise!

If your link and computer can handle it, click on the video itself to go to YouTube directly, then click "Watch in HD". Yeah, YouTube can actually deliver good-looking video :)
More DetailsCollapse )

Helmet-mounted camera!
flying
chmarr
Just added another camera to the arsenal... this little thing is a GoProCamera "Helmet Hero". Tiny little thing.



And, yes, I know the exposure kinda sucks. No way to adjust it, so I think I'll have it pointed more downwards in the next shots, and perhaps process these shots with some software.

?

Log in

No account? Create an account