Wednesday, 28 November 2012

Common Regex

I have been busy lately, hacking up stuff with socket.io

I've created a table for regular expressions to do common validations or searches.

Anyway, here is the link, I hope you enjoy it! If you think that an important regex is missing, drop me a line.

Tuesday, 13 November 2012

Dividing by zero for fun and profit

It's monday, and I'm back from vacation, feeling like I'm wasting my time and inevitably falling victim to the great cycle of life, money and everything. while (42) { }. Fortunately, I have sweet, sweet sarcasm on my side.

Anyway, this post is supposed to be about dividing by zero.

In python, it's a great way to find if a certain code path deep inside your call stack is really getting called, and when. You get to write one line which results in a noisy exeption, so your pain and confusion is properly turned into a Traceback.

    class ReturnStatement(Statement):
        def __init__(self, returnee):
            1/0
            super(ReturnStatement, self).__init__(returnee, '<return>')

"Oh. This time the exception never fired. I was sure this was supposed to be executed."

That's the kind of thought you are supposed to get, or something among the lines of:

"There, the exception.. Then why is this @!$# method not working if it's being called?"

Anyway, you get a good troubleshooting test just for typing three characters and a new line. Good bargain!

Of course, in JavaScript it's useless.

Yields Infinity. That's a discussion for another point in time. Maybe. I may never be inclined again to speak of that matter. Hours and hours of agony because of a number having a completely unpredictable number. Ugh.

In compiled languages, it's mostly useless, too.

Mondays.

Wednesday, 7 November 2012

Valilang

I have started a new project. Its name is valilang.

Create validation rules in a single format, meant to be used in both client and server sides.

Although I have given up my first plan of making valilang a minimal imperative programming language, the name still has the suffix "lang". I have opted to base the language syntax upon JSON, so it will be easier to learn and use.

The format is very easy to write. There are :

  • fields, which correspond to form fields, and
  • rules, which are (mostly premade) short functions taking a value argument and doing an assertion upon that value.

A valilang file will have an object with these keys:

  • fields, a list of fields.
  • fieldValidation, an object mapping field names to a list of rules applied sequentially to these fields.

Here is an example valilang file, for a form with a single field:

    {
        "fields": ["name"],
        "fieldValidation": {
            "name": [
                "required",
                "min-10",
                "max-50"
            ]
        }
    }

In the above object, we can see we have a single field name which has the following rules:

  • It's a required field
  • It takes at least ten characters (min-10)
  • and at most 50 characters (max-50).

These rules (which are actually functions) are executed sequentially, until any function returns null, in which case the validation fails.

Notice how arguments are handled. They are extracted from after the dash in each of the rule strings, provided these strings have a dash.

On the client side, you just have to include a valilang file and valilang.js.

    <script type="text/x-valilang">
        {
            "fields": ["name"],
            "fieldValidation": {
                "name": [
                    "required",
                    "min-10",
                    "max-50"
                ]
            }
        }
    </script>
    <script type="text/javascript" src="valilang.js"></script>

On the server side, you will load the valilang library for your framework or language, and ask it to validate your fields.

Of course this is all when both the client side and the server side are implemented. Remote loading of scripts is not yet supported. The server side hasn't been prepared for any language except for javascript (by requireing valilang.js in node and using its API), and there are too few validators (validation functions). Also unit testing is not done for the client or the server.

However, valilang.js is definitely compact, under 5 kb minified, and it is in a nearly usable state. Care to try it out and maybe contribute to its development? Report bugs and fork the github repository.

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.