A Foolish Manifesto

fREWdiculous!

Archive for the ‘Uncategorized’ Category

Vim Feature of the Day

A coworker called me and asked me what it meant that when vim opened a file there were a bunch of ^@‘s in it. I didn’t know off hand, but I did know that vim had some feature to print out the ascii value of the character that the cursor is over. So without further ado:
:as or ga

Enjoy!

  • 0 Comments
  • Filed under: Uncategorized
  • OLOTD

    1
    noglob zmv -W **/^*.flac **/*.flac

    I just ripped a bunch of music into flac and I forgot to add .flac to the end of the files until I was mostly done. If you are using zsh (and you load the zmv module) the above line will rename all files that do not end in .flac to whatever they used to be, but with .flac at the end.

    excellent.

  • 0 Comments
  • Filed under: Uncategorized
  • Javascript scope

    One of my least favorite things about javascript is scope management. In most languages scope is quite clear; if you defined a variable previously and “higher up” in some kind of scope stack, you can access it. And furthermore, this always refers to the current object. That’s not quite true for javascript, because javascript is different than (almost) any other programming language you have ever used.
    You don’t like monkeypatching? Bummer. That’s how objects are created in javascript…more or less. But more on that later. Right now: scope.

    Here is a base form that I wrote for work. We use ExtJS for all of our UI, which lets us do cool things like this. Feel free to read it like a story; I just want to point out lines 18-37. Take a look at those and then read on.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    Ext.ns('ACDRI.ui');

    ACDRI.ui.BaseForm = Ext.extend(Ext.FormPanel, {
        generateUrl: function() {
              return '/devcgi/init.plx/controller_' +
                this.controller + '/' + this.action;
        },
        validateRole: function(form, action) {
           console.error(action);
        },
        initComponent: function() {
           var config = {
              bodyStyle:'padding:5px 5px 0',
              width: 350,
              defaults: {width: 230},
              buttons: [{
                 text: 'Save',
                 handler: function() {
                    this.getForm().submit({
                      url: this.url,
                      baseParams: this.baseParams,
                      waitMsg:'Saving...',
                      success:function(form, action){
                         this.closeFunction();
                         console.log(this);
                         if (this.successFunction) {
                            this.successFunction();
                         }
                      },
                      failure:function(form, action){
                         this.validateRole(form,
                             action);
                      },
                      scope: this
                    });
                 },
                 scope: this
              },{
                 scope: this,
                 text: 'Cancel',
                 handler: function() {
                    this.closeFunction();
                 }
              }]
           };
           Ext.apply(this, config);
           ACDRI.ui.BaseForm.superclass.
             initComponent.apply(this, arguments);
        }
     });

    Note the “scope: this” directives sprinkled throughout the code. The reason for the usage of the directives is that we have some functions (success, etc) that have the keyword this in them. By default this is supposed to refer to the object from which the method is called (the invocant), but with a language like javascript where you can add methods and variables to objects (kinda like monkeypatching, but only for instances of objects) on the fly, you start to realize that sometimes you don’t want this to be the invocant, but something else. You probably want this to be the object that adds the method to the other object. Well, in ExtJS the scope config option allows you to set the invocant.

    In the above example we have to set the invocant because otherwise the validateRole method will be called from the button, and not the form. The same follows for the this.getForm() etc.

    That’s pretty common in Ext. People run into this kind of thing all the time because they assume that what they are configuring is the current object but it usually isn’t.

    But that’s chump change to what I had to do below. Read (17-19):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    Ext.ns('ACDRI.ui');

    ACDRI.ui.CustomerContacts = Ext.extend(
      ACDRI.ui.Grid, {
        addFunction: function() {
           var win;
           win = new ACDRI.ui.FormWindow({
               title: 'Create New ' + this.itemName,
               height: 250,
               items: [{
                  url: this.generateCreationUrl(),
                  baseParams: {
                     customer_id: this.customer_id
                  },
                  xtype: 'customer_contact_form',
                  //  \/  Look here  \/
                  successFunction: function() {
                     this.getStore().load();
                  }.createDelegate(this),
                  closeFunction: function() {
                     win.close();
                  }
               }]
              });
           win.show();
        },
        initComponent: function() {
           this.record = Ext.data.Record.create([
              {name: 'id', type: 'string'},
              {name: 'first_name', type: 'string'},
              {name: 'last_name', type: 'string'},
              {name: 'phone', type: 'string'},
              {name: 'fax', type: 'string'},
              {name: 'email', type: 'string'}
              ]);
           var config = {
              controller: 'WorkOrderEntry',
              action: 'customer_contacts',
              title: 'Contacts',
              itemName: 'Contact',
              baseParams: {
                customer_id: this.customer_id
              },
              columns: [{
                 header: 'Name',
                 renderer: function(value, metadata,
                   record) {
                    var t = new Ext.XTemplate([
                      '<tpl if="email">',
                       '<a href="mailto:{email}">',
                       '{first_name} {last_name}</a>',
                      '</tpl>',
                      '<tpl if="!email">',
                       '{first_name} {last_name}',
                      '</tpl>'
                    ]);
                    return t.applyTemplate({
                      email: record.get('email'),
                      first_name:
                       record.get('first_name'),
                      last_name:
                       record.get('last_name')
                    });
                 },
                 sortable: true,
                 width: 110
              },{
                 header: 'Phone',
                 dataIndex: 'phone',
                 sortable: true,
                 width: 110
              },{
                 header: 'Fax',
                 dataIndex: 'fax',
                 sortable: true,
                 width: 110
              }]
           };
          Ext.apply(this, config);
          ACDRI.ui.CustomerContacts.superclass.
            initComponent.apply(this, arguments);
        }
     });

    Ext.reg('customer_contacts',
        ACDRI.ui.CustomerContacts);

    See, the scope option is Ext specific. When you start doing your own stuff (like I am) you have to deal with scope yourself. createDelegate (bind in Prototype) helps us set the scope in a function. It gives us a new anonymous function with the scope set to whatever we passed it.

    The issue above is that we want the window to reload the grid after a successful save. The window doesn’t know anything about the grid, so we have to explicitly tell it that the this is the grid. That’s what createDelegate does.

    Crazy huh?

  • 0 Comments
  • Filed under: Uncategorized
  • Album of the Week: To Watch the Storms

    This week’s AOTW is To Watch the Storms by Steve Hackett. I first heard of Steve Hackett (and also this album) in a sampler from InsideOut. I remember listening to the sampler and being blown away by both the Hackett song and the Flower Kings song. I later ordered this album and have consistently been impressed by the quality of the album.

    But quality is not all that it takes to make a great album. This album has an amazing variety of music. For example, The Devil is an Englishman is an unusual techno-rock song, Frozen Statues is an extremely sparse song (I count 2 instruments,) and The Silk Road is a powerful, almost acoustic drum based song. I consider this album prog in the purest sense in that it does very unusual things with music and pulls them off quite nicely.

    I would say the best listening conditions for this album are when you are on a dark beach with a storm coming in so the wind is blowing gently. It may sound like the album name is the reason, but imagine listening to it in those conditions and I think you will see what I mean.

    This is another one of those albums that is hard to pick songs for, but I can try: Brand New, Rebecca, The Silk Road, and Serpentine Song.

    Colors: Blue, White, and Brown.

  • 0 Comments
  • Filed under: Uncategorized
  • Higher-Order Perl

    One thing that I love about reading good programming books (maybe even good Perl programming books) is the humor instilled in them. Tonight I decided to start reading Higher Order Perl (which you can get free here!) Here is a selection from the frontispiece:

    … Hardly anyone wants to listen to Lisp programmers. Perl folks have a deep suspicion of Lisp, as demonstrated by Larry Wall’s famous remark that Lisp has all the visual appeal of oatmeal with fingernail clippings mixed in. Lisp programmers go around making funny noises like ‘cons’ and ‘cooder,’ and they talk about things like the PC loser-ing problem, whatever that is. They believe that Lisp is better than other programming languages, and they say so, which is irritating. But now it is all okay, because now you do not have to listen to the Lisp folks. You can listen to me instead. I will make soothing noises about hashes and stashes and globs, and talk about the familiar and comforting soft reference and variable suicide problems. Instead of telling you how wonderful Lisp is, I will tell you how wonderful Perl is, and at the end you will not have to know any Lisp…

    I am looking forward to reading this one :-)

  • 1 Comment
  • Filed under: Uncategorized
  • Least Favorite Features

    brian d foy (author of numerous perl books) asked this question on Stack Overflow: “What are five things you hate about your favorite language?”

    I figured that since I am trying to bring perl 6 to fruition (note: I’ve only written tests, so I am not very good at helping so far) I would pick perl 6 as my favorite programming language. Here was my answer:

    I’m going out on a limb since I can’t really use it full time, but I’ll try anyway!

    Perl 6

    1. func(“frew”) != func (“frew”)
      • It annoys me, but there is good reason for it. In perl 5 print (5 + 6) * 10 still gets me every now and then)
    2. It may be easier to parse than perl 5 in a lot of places, but it still kills my editor sometimes
    3. It still has a lot of the line noise perl 5 which scares a lot of people. That means it’s harder to get them excited etc.
    4. There are no libraries yet.
      • This will be a non issue if perl 6 does indeed end up supporting perl 5, but that may be a burden not worth bearing.
    5. There’s no REPL, or what rubyists would call irb.
      • A solid interactive perl 6 with tab completion, color coding, etc, would make using and learning it so much nicer.
    6. Currently the documentation is basically the English spec. Not exactly an easy read.
    7. I know it’s a stupid cliche, but it’s not out yet!
      • I am allowed to complain because I am helping :-P

    The first three are the language; the rest aren’t really the language itself but the fact that it’s not out yet.

  • 0 Comments
  • Filed under: Uncategorized
  • Paranoid Deletion in DBIx::Class

    In the most well designed databases that I’ve used we never really deleted anything from the database. We would just mark a field as deleted and then just make sure to filter out the deleted data when we searched and it was all groovy. You could easily readd the item and you never truly lost much data.

    Well, now that I am using an ORM I’d like a similar feature in my current database and I’d like it to be as automatic as possible. The first thing I did was, in the Model class, override the delete method. Easy peasy:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    package ACD::Model::CustomerBillingAddress;
    use base DBIx::Class;

    __PACKAGE__->load_components(qw/PK::Auto Core
       InflateColumn::DateTime/);

    __PACKAGE__->table('CustomerBillingAddresses');

    __PACKAGE__->add_columns(qw/
        customer_id
        id
        # ...
        creation_date
        deletion_date
        phone
        fax
        email
        /);

    __PACKAGE__->set_primary_key(qw/customer_id id/);

    __PACKAGE__->belongs_to('customer' =>
      'ACD::Model::Customer', 'customer_id');

    sub delete {
       my $self = shift;
       $self->update({
          deletion_date => \"GETDATE()"
       });
    }

    1;

    And then to filter out the deleted rows I just did this in my Contoller’s search function:

    1
    $search->{deletion_date} = \"IS NULL";

    (I have a Controller based function because it also turns all the data into json, paginates it, etc.)

    But setting that in every single model class is Bad Design. What if I decided to switch to a boolean instead of a date? So I did some research and found out that with Components I could change the delete method. So here is a component that does what I want:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    package ACD::ParanoidDeletion;
    use base qw(DBIx::Class);
    use strict;
    use warnings;
    use feature ':5.10';

    sub delete {
        my $self = shift;
        $self->update({
            deletion_date => \"GETDATE()"
        });
    }

    1;

    That’s pretty cool! And then to use it I just add this line to my model classes:

    1
    2
    3
    4
    __PACKAGE__->load_components(qw/
       +ACD::ParanoidDeletion
       PK::Auto Core InflateColumn::DateTime/
    );

    Now there is really only one thing left that bugs me about this current interface. When searching I have to remember to filter out the deleted items. Again: bad design! So after more research and help from people in #dbix-class I came up with this solution. First we make a new ResultSet class:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package ACD::ParanoidResultSet;
    use strict;
    use warnings;
    use base 'DBIx::Class::ResultSet';

    sub search {
        my $self = shift;
        $_[0]->{deletion_date} = \"IS NULL";
        return $self->next::method( @_ );
    }


    1;

    That override’s the search method and add’s deletion_date IS NULL to the sql query. The next::method call is what would be super in java, except not quite the same because it allows for multiple inheritance.

    And then, this is the best part, to have the models automatically use this resultset we add the following method to our ParanoidDeletion Component:

    1
    2
    3
    4
    5
    sub table {
        my $class = shift;
        $class->next::method( @_ );
        $class->resultset_class('ACD::ParanoidResultSet');
    }

    and that’s basically it! The only real thing left to do is allow the user of the class to specify which column will be set on deletion and then package it up and send it to CPAN!

    Enjoy!

  • 4 Comments
  • Filed under: Uncategorized
  • Rakudo Autobuilder

    First off, if you did not already know, rakudo is the first implementation of perl6. There is no plan for an official Perl 6 implementation, so we have to give this implementation a name other than perl6.

    Anyway, I know that you are all working diligently on perl6 like I am, so I know that you are having trouble because you have to rebuild parrot and rakudo which is kindav a hassle. Let’s remedy that now! (Much of this information was taken from this post by Moritz.)

    First you’ll want to get your initial checkouts. I’ll presume that you have git, subversion, and everything else required to build rakudo already installed on your unix based computer :-) Also, I will assume you check them out into ~/dev. I actually have a ~/personal and a ~/scripts that I check this stuff out into for my laptop and desktop respectively, but the point is, they both get checked out to the same directory.

    So to checkout both you’ll do this:

    1
    2
    3
    cd ~/dev
    git clone git://github.com/rakudo/rakudo.git
    svn co https://svn.parrot.org/parrot/trunk parrot

    So now you should have a ~/dev/rakudo and a ~/dev/parrot. Now make a script called build_rakudo.sh inside of ~/dev and fill it with these lovingly crafted characters:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    #!/bin/bash

    cd ~/dev/parrot

    # clear out any old cruft that used to be there.
    # this isn't always necessary, but sometimes it
    #  is and we want this to be entirely automated
    make realclean

    # updated the source
    svn up

    # configure it for your local system
    perl Configure.pl

    # and build it!
    make

    cd ~/dev/rakudo

    # remove the old symlink so make realclean
    # doesn't delete our checkout/build
    rm parrot

    # see above
    make realclean
    git pull

    # make a symlink of the above parrot
    # directory in the rakudo sourcetree
    ln -s ../parrot parrot

    # see above
    perl Configure.pl
    make

    # I just do this so that I can run perl6
    # and have an "interactive" perl6 it isn't
    # really interactive, but it's better than
    # write, execute loops
    make perl6

    And then I’d recommend doing a crontab -e and adding

    1
    0 17  *   *   *     sh /home/foo/dev/build_rakudo.sh

    so that it gets built every day, starting at 5 pm, so it’s ripe for work when you get home :-)

    And one last thing: working on perl6 locally can be kindav a drag because it doesn’t tell you the result of all of your lines when you are using the fake-o interactive mode. A nice thing to do is this:

    1
    sub p($anything) { $anything.perl.say }

    That way if you give it an array, it will print out the array as an array instead of some weird tab delimited stringification or whatever.

    Happy hacking!

  • 0 Comments
  • Filed under: Uncategorized
  • Today I was talking with a friend about the stuff we are doing at work and I mentioned to him how I was planning on doing the authorization. Since I had only thought about it at that point I didn’t even know if my idea was valid Perl syntax, let alone a feasible idea. But enough with the backstory, how about some real information.

    Let’s assume that we have a webpage that lets you read user data and write user data. Theoretically we have already logged the user in, so we know who they are talking to, and we have a simple database model of the roles the user is authorized for. That’s no fun but it’s pretty easy. Three tables: one for the user, one join table from user to roles, and one that lists roles. So if we wanted to limit a sub to a user with role ‘read_user’ and ‘write_user’ we could do this:

    1
    2
    3
    4
    5
    6
    7
    8
    sub read_user {
      my $self = shift;
      if ($self->user->has_role('read_user') and $self->user->has_role('read_user')) {
        # display user data somehow
      } else {
        # display some form of error
      }
    }

    That’s really a fine way to do it. It works. It’s how most things work. But it would be no fun to have to write that for essentially every page on a site. That’s a drag!

    Perl has this thing call attributes; which is basically a way to tag functions. At first I thought, “Hey, we’ll just tag a function with it’s roles and have validation work based on that. So our previous thing would look like this:

    1
    2
    3
    4
    sub read_user : role_read_user role_write_user {
      my $self = shift;
      # display user data somehow
    }

    That would be great! But how on earth would you do something like that? I started off looking at the source to AutoRunmode which basically gave me this idea in the first place. There is some very deep magic in there, so I decided to keep looking. The source to AutoRunmode references Attribute::Handlers, originally by Damian Conway (author of numerous Perl books) which allows me to at least do something when someone includes a handler. That’s a start. So I looked at how to use Attribute::Handlers and after seeing what was possible I decided it would be easier and more clear to change my goal to this:

    1
    2
    3
    4
    sub read_user : Authorize(qw/role_read_user role_write_user/) {
      my $self = shift;
      # display user data somehow
    }

    That way if I use the Attribute::Handlers system I write a single function that gets a list of roles (amongst other things.) Then came the hard part. How can you change a function in Perl? Well, it turns out that changing a method is Kinda Hard, but Dave Rolsky Stevan Little made Moose, which makes it totally easy!

    So this is the final mockup of how I plan on doing it:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
        package MyClass;
        use feature ':5.10';
        use Attribute::Handlers;
        use Moose;

        sub Authorize : ATTR(CODE) {
           my ($class, $globref, $referent, $attr, $data, $phase, $filename, $linenum) = @_;

           # deep magic that gets the name of the function
           my ($function) = ${$globref} =~ /::([^:]+)$/;

           $class->meta->add_before_method_modifier ($function => sub {
                 foreach (@{$data}) {
                    $class->validate($_);
                 }
              });

           return;

        }

        sub read_user : Authorize(qw/user_read user_write/) {
           my $self = shift;
           say "reading personal files!";
        }

        sub validate {
           my $self = shift;
           my $role = shift;
           say "validating $role for ".$self->user;
        }

        sub user {
           my $self = shift;
           return 'frew';
        }

    Debolaz from #perl helped out a lot with this one. The only major thing left is some way to check all functions with the attribute ‘Runmode’ and ensure that they also have the Authorize attribute with at least one thing in there. That way we can’t accidentally forget to authorize people. I don’t think that will be very hard, but even if we can’t do it, this is still great.

    The only thing I am worried about is whether I can use Moose in a CGI::App class. Probably, but we’ll see.

    Hurray for Perl!

  • 3 Comments
  • Filed under: Uncategorized
  • Album of the Week: Metropolis Pt. 2

    Metropolis Part 2, by Dream Theater, is this weeks AOTW. This is one of those rare albums that must be listened to entirely, in order, and gaplessly. I am sure lots of you music people do this anyway. I know that I do for sure. But the thing is that these songs mostly have seamless transitions along with an important, plotish order.

    Metropolis Part 2 is a concept album. It is Prog Rock as it’s by Dream Theater. The concept has something to do with murder and reincarnation; at least that is what I have gathered after listening to it numerous times. It is one of the few albums, in my opinion, that pulls off sound effects well. Lots of songs use sound effects as part of the song. How many do you know that use sound effects as sound effects and still sound good and actually have something to do with the song?

    I think this is a great album to sit down and just listen to as opposed to listening to at work. I also listen to it at work and while I drive etc. But the lyrics and the music itself are worth paying attention to.

    I like every single song on the album, which I think is unusual, but I will still note my favorites.

    My favorite tracks of the album: Finally Free, Fatal Tragedy, Beyond This Life, The Dance Of Eternity.

    Colors: Red, Black, Blue.

  • 2 Comments
  • Filed under: Uncategorized