Wednesday, 7 November 2012

AAAAAAAAAA

A AAAA AAAAAA AA AAAA AAAA AAA AAAAAAAAAAAAAA.

    >>> def AAAAAAAAAA(s):
    ...     import re
    ...     return re.sub('\w', 'A', s)
    ...
    >>> AAAAAAAAAA('I want to know what Guido eats for breakfast.')
    'A AAAA AA AAAA AAAA AAAAA AAAA AAA AAAAAAAAA.'
    >>> AAAAAAAAAA("I have found a new way to encode messages. But it's irreversible.")

    "A AAAA AAAAA A AAA AAA AA AAAAAA AAAAAAAA. AAA AA'A AAAAAAAAAAAA."
    >>> AAAAAAAAAA("You have a way with words.")
    'AAA AAAA A AAA AAAA AAAAA.'
    >>>

AAAAA AA AAA AA AAAAAAAAAAAAAA AAAA.

And a thousand pointless points are given to whoever decodes this post.

Tuesday, 6 November 2012

Periodic table of HTML5 elements

A very interesting and helpful link from Josh Duck:

http://joshduck.com/periodic-table.html

It contains all HTML5 elements, formatted in a table that looks much like the Periodic Table of the Elements. It is very nice and informative to look at all of them, grouped into categories.

Find out a couple of new elements, and use it as reference, since every element in the table has links to helpful documentation on MDN and the formal declaration in W3C when you click them.

The little form on top lets you count elements used in any published website. Detect divitis!

Monday, 5 November 2012

Practical example of str.split's optional argument. Config file parser

Taking my little fun discovery for a ride. Used it to create a simple config file reader together with itertools.

    >>> lines = iter(open('config.cfg'))
    >>> import itertools
    >>> splitonce = lambda s:s.split('=',1)
    >>> trim = lambda s:s.rstrip('\n\r')
    >>> trimmed_lines_generator = itertools.imap(trim, lines)
    >>> split_lines_generator = itertools.imap(splitonce, trimmed_lines_generator)
    >>> settings = dict(split_lines_generator)
    >>> settings
    {'ConfigSetting3': '  Allow leading+trailing spaces!   ', 'eqsign': '=', 'ConfigItem2': 'Settle for no "=" signs!', 'Con
    figItem1': 'Configured'}
    >>>

This of course wouldn't work if I hadn't applied the optional argument to str.split, which I talked about in my previous post. It helps me split the file lines into keys and values by the equal sign, and not worry that the values might include equal signs of their own.

I am getting ahead of myself. In case you are not familiar with CFG files, here is the file I used in the above example. The settings file config.cfg:

    ConfigItem1=Configured
    ConfigItem2=Settle for no "=" signs!
    eqsign==
    ConfigSetting3=  Allow leading+trailing spaces!

Stripped out of the interpreter into cleaner code:

    from itertools import imap

    with open('config.cfg') as fp:
        lines = iter(fp)
        def splitonce(s):
            return s.split('=', 1) # split limit
        def trim(s):
            return s.rtrim('\n\r')

        trimmed_lines_generator = imap(trim, lines)
        split_lines_generator = imap(splitonce,
            trimmed_lines_generator)

        settings = dict(split_lines_generator)

I have used itertools.imap. Using iterators and chaining them together will make larger config files use less memory than if I used list(fp) to get a list of lines. This of course is more of a concern in larger config files.

Saturday, 3 November 2012

Timetable selection snippet.

I have put together a simple timetable snippet for helping keep track of time, or to do time allocation of some resource.

Check it out on jsfiddle:

This is a jQuery plugin. It works by converting a table with checkboxes inside each td into a time planner. It does this by moving the checkboxes away from their td containers into a div inserted below the table.

Here is that DIV's HTML. As you can see it has all the checkboxes from every cell.

    <div style="display: none;" class="timeplanner-checkbox-dump">
        <input type="checkbox" checked="checked" name="0-0">
        <input type="checkbox" name="1-0">
        <input type="checkbox" name="2-0">
        <input type="checkbox" che...

Then it routes the events of each td into its containee checkbox. This is done by using an annonymous function for each td. In a jQuery.each loop I declare var checkbox_here, (so it is different for every closure) and then just do $(checkbox_here)-click() in the click event handler for the td.

Python's string formatting syntax

As you are surely aware of, you can use python's % operator to do string formatting. It's part of the reasons why the language is so good at text processing.

The left operand is the format string, the right operand is a single format argument, or an iterable of format arguments. In the format string, you can use %s to insert a string, %d to insert an integer, %f for a float, etc. It's much like C's printf family of functions.

    >>> '%s %d' % ('a string', 123)
    'a string 123'

This you almost surely know. You might not know that the string can take a %r argument which calls repr on the arguments. Now that's useful!

    >>> 'a repr: %r' % ['', ""]
    "a repr: ['', '']"
    >>> 

Or that the format parameters can be in a dictionary.

    >>> '%(a_string)s %(an_int)d' % {'a_string':'a string', 'an_int': 123}
    'a string 123'
    >>> 

If the parameters were passed as a dictionary, the format string will not raise exceptions for extra parameters. So you can use locals() on your (trusted) format string, and format it easily. In a class method, self.__dict__ would also be useful.

    >>> a_number = 3
    >>> '%(a_number)d' % locals()
    '3'

String formatting parameters will also take their own parameters. The parameters are decimal characters (and an optional separation dot) between the % sign and the character indicating the type.

Here is an ugly syntax representation. Bear with me.

% [0|-][leading/trailing character count][An optional dot][Truncation](Type character)

That's all, I think. Be careful to add no spaces. The only characters allowed between % and the type indicator are [0-9\.\-]

  • First, the usual percentage sign.

  • Then, add a single zero if you want to fill the string with zeroes (you specify how many characters you would like to fill the string with in the next argument). If you want the string to have trailing spaces instead of leading spaces, add a minus sign.

  • After that, add the number of characters you want to fill the string with. You can skip this.

  • If you want to use the truncation argument (explained below), add a dot here.

  • Add the truncation argument, which is an integer.

For obvious reasons, you can't have trailing zeroes in anything.

The "Truncation" argument is used to left-truncate a string to that size, to grow (only grow) an integer string by zero-filling the left to that size, or to use that many decimal digits in a float.

Here are some examples with %s. %s doesn't let you put leading zeroes on your string. You can use str.zfill() for that.

    >>> s = '1234'
    >>> '%.1s' % s
    '1'
    >>> '%.4s' % s
    '1234'
    >>> '%.6s' % s
    '1234'
    >>> '%10s' % s
    '      1234'
    >>> '%10.2s' % s
    '        12'
    >>> '%10.4s' % s
    '      1234'
    >>> '%10.6s' % s
    '      1234'

%f examples:

    >>> f = 10.123
    >>> '%f' % f
    '10.123000'
    >>> '%.4f' % f
    '10.1230'
    >>> '%4f' % f
    '10.123000'
    >>> '%20f' % f
    '           10.123000'
    >>> '%20.2f' % f
    '               10.12'
    >>> '%020.2f' % f
    '00000000000000010.12'
    >>> 

%d can also be told to have leading zeroes or leading spaces. As mentioned above the "Truncation" part of the parameter can only make it grow. It wouldn't make sense to let it shrink, since that would shrink the number's value.

    >>> i = 10
    >>> '%d' % i
    '10'
    >>> '%.1d' % i
    '10'
    >>> '%.4d' % i
    '0010'
    >>> '%4d' % i
    '  10'
    >>> '%4.1d' % i
    '  10'
    >>> '%4.3d' % i
    ' 010'
    >>> '%4d' % i
    '  10'
    >>> '%04d' % i
    '0010'
    >>> 

As you know, in python, characters are indeed strings with len() of 1, so if you want to represent a character you just use %s. But you can also use %c. %c will raise an exception if the input string is not a character, and the extra assertion might prove a little useful. You can add leading and trailing spaces to this parameter too.

Finally, it's worth something to note that python has a newer formatting syntax. I haven't seen it used much, and don't use it either. It's not so practical as the one I described.

More information on string formating can be found in the python documentation

This has hopefully been a thorough dissection of python's string formatting syntax. Now go out and enjoy the sun!

Monday, 15 October 2012

Python Discovery: Named Tuples

I had known of the named tuple idiom for ages. It is used sparingly in some python API's, and I feel it is very pythonic, practical, and simple to read and code with.

It's used like this (this example is for the timetuple in datetime.datetime, which is a namedtuple, or looks a lot like one):

>>> tt = datetime.datetime.now().timetuple()
>>> tt
time.struct_time(tm_year=2012, tm_mon=10, tm_mday=15, tm_hour=20, ...)
>>> tt.tm_year
2012
>>> tt[0]
2012
>>> tt[3]
20
>>> tt.tm_mon
10
>>> 

And it's iterable.

>>> list(tt)
[2012, 10, 15, 20, 24, 8, 0, 289, -1]

It's basically a tuple which has attributes accessible through dot notation.

The timetuple idiom is perfect for API design, and for those times where a class is what you want, but a tuple would be okay too. For example, 2D dimensions. You could store them in a class with height, width attrs, or in a tuple.

I thought it was just some pythonic pattern, but today I needed to automate it because I found myself making dumb __init__ methods like these:

def __init__(self, left, right):
    self.left = left
    self.right = right

It is a useful pattern. It's pythonic. It's implementable in pure python with just a little metaprogramming. It could be in the standard library, I thought.

I opened up my python interpreter and entered import collections and dir(collections) looking for NamedTuple or something. namedtuple was there. It wasn't just a coincidence.

collections.namedtuple is a factory for creating namedtuple types, which you can then use. The resulting classes include methods like _asdict, _fields, index and _replace.

>>> a = collections.namedtuple('a', 'b, c')
>>> a(1,2)._asdict()
OrderedDict([('b', 1), ('c', 2)])
>>> a(1,2)._fields()
('b', 'c')
>>> a(1,2).index(1)
0
>>> a(1,2).index(2)
1
>>> a(1,2)._replace(b=3)
a(b=3, c=2)
>>> 

It is hashable, unlike a dict, and pickleable.

Here is how you create one:

>>> collections.namedtuple('SomeNamedTuple', 't1 t2')

The first argument is the name of the output class, and the second argument is the list of parameter names, whitespace - and/or comma - delimited.

This creates a named tuple with the __name__ SomeNamedTuple, and the attributes t1 and t2.

Extend it

When you need more stuff out of your namedtuple you should really subclass. Keep in mind that it is immutable, so you should return a copy of it in every method.

class Dimensions(collections.namedtuple('DimensionsTuple', 'height width')):
    pass

>>> Dimensions(10, 30).height
10
>>> Dimensions(10, 30).width
30

It is rather useful sometimes, so don't forget about the named tuple! You might need it sooner or later.

Thursday, 27 September 2012

jQuery.showWhen

I've created a small jQuery plugin to allow for more responsive forms. Sometimes you only want to show parts of a form when other parts are complete. This helps you simplify forms and only go into detail when the user has already filled in some field. Here is an example, and an example with a checkbox instead
Think about a survey:
  1. Do you smoke?
    1. Yes
    2. No (skip to 4.)
  2. How often do you smoke?
    1. Every hour
    2. Every two hours
  3. Do you realize ...
    1. Not really
  4. Is question four a question?
    1. Yes
    2. No
In this survey, we could have tried to follow the standard of interactive and intuitive forms to hide questions number 3. and 4.
This could be done in a non-obstrusive way: If the "(skip to 4.)" text was inside its own span with its own CSS class, it would be trivial to add data-skip-questions to that span, and have jQuery look for span[data-skip-questions], and use String.split with jQuery.add to register with this plugin.
html code:
<ol class="questions">
    <li>Do you smoke?
        <ol>
            <li><input type="radio" name="q1" value="y" />Yes</li>
            <li><input type="radio" name="q1" value="n" />No <span data-skip-questions="2 3">(skip to 4.)</span></li>
        </ol>
    </li>
    <li>How often do you smoke?
        <ol>
            <li><input type="radio" name="q2" value="1" /> Every hour</li>
            <li><input type="radio" name="q2" value="2" /> Every two hours</li>
        </ol>
    </li>
    <li>Do you realize ...
        <ol>
            <li><input type="radio" name="q3" value="n" /> Not really...</li>
        </ol>
    </li>
    <li>Is question four a question?
        <ol>
            <li><input type="radio" name="q4" value="y" /> Yes</li>
            <li><input type="radio" name="q4" value="n" /> No</li>
        </ol>
    </li>
</ol>
javascript code:
$('span[data-skip-questions]').each(function() {
    var questionsToSkip = $(this).data('skip-questions').split(' '),
        q = $(null),
        watchedInput = $(this).parents('li:first').find('input[type="radio"]');

    $.each(questionsToSkip, function(i, val) {
        q = q.add($('ol.questions > li')
              .eq(val - 1));
    });

    $(q).hide().showWhen(watchedInput, true);

})
// Hide the span, since the user doesn't have to skip the questions snymore.
.hide();
Here's a fiddle for the survey example.

Edit:
The plugin is now on github. It was released under the WTFPL. Feel free to fork and use!