June 2, 2008

Chipotle...

It's pronounced chee-poht-lay.

September 10, 2007

Morris Puzzle Progression Done With Perl

A while back my boss asked us to complete the Morris puzzle for fun. What's the Morris puzzle you ask?

What's the next sequence in this set?

1
11
21
1211
111221

After figuring it out, I couldn't help but want to write a solution in perl. Below is a Perl script that will carry out the progression to 16 lines. Note, this was written to be terse, not readable.

$s = '1';

BLOCK: {
     print "$s\n";

     exit() if ( length( $s ) > 100 );
     
     @nums = split( //, $s );
     @uniq = ();
     $tmp = ();
     
     foreach my $num ( @nums ){
          push( @uniq, $num ) if ( $num != $uniq[-1] );
     }
     
     foreach my $num ( @uniq ) {
          $s =~ s/^($num+)//;
          $tmp .= ( length( $1 ) . $num );
     }
     
     $s = $tmp;
     goto BLOCK;
}
If you'd like, you can get more lines by adjusting the line that begins with 'exit()'.

September 6, 2007

Headphone Amps. Audio Hardware You Didn't Know You Needed

I am somewhat of a wanna-be audiophile, and a few months back I decided it was time to invest in a fairly nice set of a headphones. I settled on the Sennheiser HD-595s which have received great reviews and are at a relatively low price point compared to a really high end set of headphones.

Upon getting them I immediately plugged them into my iPod for a test drive. Oh no! The highs and mids sounded extremely clear, however the lows were nonexistent compared to my Sennheiser earbuds which sound wonderful for the price, with nice highs and mids, along with rich, full bass. It's amazing what kind of sound can be pushed through speakers so tiny!

I knew this couldn't be right so I did some research and I came across some articles that talked about using "headphone amps". I'd never heard of these, and frankly, using an amp with a pair of headphones sounded absurd. I continued reading about them and found that you can build you own if you're into that kind of thing, which I am, but I'm more into instant gratification at this point.

Eventually I ran across some affordable headphone amps from Headroom that got great reviews. Getting over my angst about buying something as absurd sounding as a "headphone amp", I thought I'd give a Total AirHead amp a try. I chose this one because it can be connected to an external power adapter so it doesn't have to rely on it's batteries or a USB connection as the Total BitHead does for power.

WOW! What a difference this little amp made! The low frequencies that were missing before were there in full force now, and everything sounded great across the spectrum. This bit of hardware really makes these headphones shine. I totally recommend checking out these amps if you've got a nice set of headphones, it'll be worth it.

An added benefit that I discovered about this amp is that it has two audio output jacks. So if you'd like to, you can connect two sets of headphones at the same time, however this isn't how I use it. Late last year I moved away from my desktop Linux machine and bought a MacBook Pro to use as my main computer (Love it!). The issue is that my Klipsch ProMedia set of speakers have two mini-jack connectors that plugged into my sound card. One for the front speakers, and one for the rear speakers. The MacBook Pro only has one audio output, so I could only plug in my front speakers, rendering my rear speakers useless.

Total AirHead amp to the rescue! With it's two audio outputs, I can connect the audio out from my MacBook Pro to the Audio in of the amp, and then connect the two jacks from my speakers to the audio outs of the amp! Voila! All four speakers work, albeit not in surround mode. I believe I'll be buying a second amp to leave permanently connected to my speakers. W00t!

The moral of this story is that if you've got nice headphones and love great audio, or need to connect speakers with two mini-jacks to a source with only one output, you need one of these amps....or perhaps two.

January 16, 2007

What the Haskell!?

I know I said my next directory recurser would be in Ruby, but Haskell has drawn my attention in a big way. Here's what I came up with...

module Main     where

import IO
import System
import Directory

main = do
  [recDir] <- getArgs
  printDirectory recDir

printDirectory path = do
  putStrLn path
  contents <- getDirectoryContents path
  mapM_ (\f -> do
      let newPath = (path ++ "/" ++ f)
      isaDir <- doesDirectoryExist newPath
      if isaDir
           then printDirectory newPath
           else putStrLn newPath
      ) (drop 2 contents)

Haskell seems like a pretty sweet language that I can learn a lot from. The pattern matching is very sweet and I'm looking forward to having a good understanding of Monads.

September 26, 2006

Giving XMMS the "what for" with Perl (AKA, C developers, append to enums, don't insert)

I've always wanted a way to be able to remotely control my MP3 player that runs on my linux box, through some sort of web interface or something. So I took some time off recently and thought it'd be fun to hack something together to let me do this. So the first thing I do is search the CPAN for any modules that let me control XMMS from Perl. What I found was the Xmms::Remote set of modules which just tied itself with a little XS code to a C library that is meant for sending commands to XMMS.

To make a long story short, this didn't work for me because when I used this module from my CGI script running through apache on my linux box, it was looking for the apache users instance of XMMS, not MY instance of XMMS. Ugh! So I wondered how this library was communicating with XMMS and guessed correctly that there was a Unix domain socket open. A little "netstat -a" action revealed my socket endpoint at /tmp/xmms_myusername.0. So what the library does is find your username and builds this path when it tries to connect to the socket in order to send XMMS a command. So, my CGI script, behind the scenes, was actually trying to connect to /tmp/xmms_apache.0, which of course, didn't exist.

This lead to the realization that I could use this socket to send my own command to XMMS! Sweeeeeeeeet! So I cracked open the XMMS source code and found its mechanisms for accepting commands on this socket and implemented my code for sending them to it. In this source code, I found an enumeration that went a bit like this...

enum
{
     CMD_GET_VERSION, CMD_PLAYLIST_ADD, CMD_PLAY, CMD_PAUSE, CMD_STOP,
}

What this does is maps numbers starting at 0 to each of the names in the enum. So CMD_GET_VERSION is 0, CMD_PLAYLIST_ADD is 1 and so on. So this enum maps out the commands that can be sent to the socket.

Next I needed to figured out the protocol that is used to send commands and receive data back from XMMS. This was easily found with a little more digging. There are two C structs defined for sending and receiving....

typedef struct
{
     guint16 version;
     guint16 command;
     guint32 data_length;
} ClientPktHeader;

and

typedef struct
{
     guint16 version;
     guint32 data_length;
} ServerPktHeader;

So if you want to send a command to XMMS, you just need to create a ClientPktHeader, enter the values and send it to the socket and XMMS will see it and execute the command. In order to do things like this in Perl, you need to get cozy with the pack() and unpack() functions. With pack() you can pack values into memory, or in other words, create a C struct. In order to make a ClientPktHeader I just needed to do this...


my $data = pack( 'SSI', $xmms_protocol_version, $command, $data_length );

What this does is packs a C short (16 bits) or "S", followed by another one, followed by a C int (32 bits), for a total of 8 bytes, into memory. Once this is done, you can feed pack()s output to Perls send() function to send this data to the socket. Wonderful! Connecting to the socket is straightforward if you've done any socket work. The key is that it's a Unix domain socket, not a TCP socket.

Everything worked great, and quite honestly, I couldn't believe it did. However as I went on to implement functions to send XMMS commands, I noticed that some of them seemed to work and some didn't. One even crashed XMMS! I spent hours looking at my code and I was doing everything correctly. My solution? Watch TV for a couple days and forget about it. A few days later though, I came back to it and after a few hours realized that the enum that mapped out all of the XMMS commands must have been out of sync with what XMMS was actually expecting! Ugh! So when I was trying to call CMD_GET_VOLUME, it was actually calling CMD_SET_VOLUME and was crashing because it was expecting me to send it 8 bytes of data representing the new volume of the 2 stereo channels and didn't get it. The result? Segmentation Fault!

What had happened was that when my linux distro (Gentoo) built and installed XMMS it also applied patches to the source tree and made changes to that enum. So what read

enum
{
     CMD_GET_VERSION, CMD_PLAYLIST_ADD, CMD_PLAY, CMD_PAUSE, CMD_STOP
}

was actually now

enum
{
     CMD_GET_VERSION, CMD_PLAYLIST_ADD, CMD_SOMETHING_ELSE, CMD_DIFFERENT_CMD, CMD_PLAY, CMD_PAUSE, CMD_STOP
}

The result of this is that I was sending incorrect commands to XMMS without knowing it. I finally got the correct enum out of the patched XMMS tree and everything now works great.

The moral of this story? When you're writing enums that someone could possibly get their grubby hands on and start using, please, please, please append any changes to the end of the enum instead of inserting items in the middle of it! Of course you'd probably say, "Well, you shouldn't go and do stuff like you did, it's your own fault. You should know better than to use someone elses code that could easily change!" And you'd be right I suppose, but I don't care.

At the very least, even if this project is doomed to failure by unpredictable XMMS enums, it was still a fantastic learning experience and a lot of fun to boot.

P.S. I know I could have just used C or C++ and used the XMMS library that is meant for this sort of thing, but I really wanted to implement a pure Perl solution instead of something that needed a binary to work.

P.P.S. I also know that there is a xmms-shell program that lets you control XMMS from a command line, so I can SSH into my box and control it remotely that way. This works great and I highly recommend it.

September 20, 2006

A filesystem recurser in Python too

So I'm learning Python here and there and thought I'd reimplement my directory recurser with it. Again, I'm only learning, so there may be a better way to do this in Python. Of course I could use os.walk(), but that would defeat the purpose of creating my own recurser. Why am I doing this simple task? Just cuz. :)

#!/usr/bin/env python

import os, sys

def printDir( path ):
     "Print a directory and it's files recursively"
     
     print 'Directory: ' + path
     
     for item in os.listdir( path ):
          newPath = path + '/' + item
          if os.path.isdir( newPath ):
               printDir( newPath )
          elif os.path.isfile( newPath ):
               print item
          
if len(sys.argv) > 1:
     printDir( sys.argv[1] )
else:
     printDir( '.' )

Next up...Ruby...

September 5, 2006

A shorter filesystem recurser in Perl

Shortened it up a bit...

#!/usr/bin/perl use strict; use warnings;

printdir( $ARGV[0] );

sub printdir
{
     my $dir          = $_[0] ? $_[0] : '.';
     my $handle      = ();
     
     print "Directory: $dir\n";
     
     opendir( $handle, $dir );
     my @items = sort( readdir( $handle ) );
     closedir( $handle );
     
     map
     {
          -d "$dir/$_"
          ? printdir( "$dir/$_" )
          : print "$dir/$_\n"
     } @items[2 .. $#items];
}

And people call Perl just a bunch of line noise?! Bah, sissies! :-P

August 26, 2006

Recursivly print directories in Perl...with no modules

Just for fun I came up with some Perl to recursively print out a directories files and child directories. Why am I posting it? It's not that it's all that difficult or obscure, I just feel like it, and when I did a web search for code on this that doesn't use the File::Find Perl module, I was surprised as to how few results there were. So in the interest of reinventing the wheel a bit, here's what I came up with.

#!/usr/bin/perl use strict; use warnings;

printdir( $ARGV[0] );

sub printdir
{
     my $dir          = $_[0] ? $_[0] : '.';
     my $handle      = ();
     my @dirs      = ();
     my $i           = ();
     
     print "Directory: $dir\n";
     
     opendir( $handle, $dir );
     my @items = readdir( $handle );
     closedir( $handle );
     
     shift @items; #Get rid of .
     shift @items; #Get rid of ..
     
     @items = sort( @items );
     
     while ( $i = shift( @items ) )
     {
          if ( -d "$dir/$i" )
          {
               push( @dirs, $i );
               next;
          }
          print "$dir/$i\n";
     }
     printdir( "$dir/$i" ) while ( $i = shift( @dirs ) );
}

February 5, 2006

Timing Is Everything

It certainly has been a while since the last update, and to be honest, I can't remember all the stuff I've worked on since. :) I do know that I've played with probe timing a bit and added max/min timeout settings to the scan engine. I've also added some parallelism features to the engine so more than one probe gets sent at one time.

I'm facing a couple issues right now that I've been avoiding. One of which I've figured out and have test code working for. This is the ability to find the proper network interface to send probe packets from on machines with more than one. I just need to get off my butt and write the code in a way that's more formal than my test code. :)

The second issue seems to be a large one. The problem is that when sending probe packets really fast, I've noticed that I don't always get replies. However, if I wait a millisecond between sending each probe, I'll reliably get the replies, but this adds up when you scan many hosts along with many ports. So I need to build in much more sophisticated timing code, along with the ability to send retries for hosts we think we should be getting responses from. These kinds of hosts would be ones for which we have no state information on. If we can determine the host is definitely up, we know we should get a RST back. If we don't, it could be filtering those probes, so we'd need to send a few retries to determine this. It seems pretty complex, so I've been doing a lot of thinking about the problem, and little coding about it. But that'll change soon enough. :)

On another note, in the past few weeks I've started learning Lisp and Python. I'm learning Lisp mainly to get a new perspective on the code world and to find out what all the fuss is about that I keep hearing out of Paul Graham and other Lisp hackers. As far as Python, there's been a lot of fuss about it out of pretty much everybody lately, so I wanna see if it'll knock Perl out of first place as my favorite dynamic programming language. From what I can tell so far, Perl is quite secure in this position. :)

Speaking of Perl; having used it for a while now and being pretty proficient in it, it makes it tough to learn other languages because when I try to use the new language I inevitably get a case of, "Why am I doing this? I could do this SO easily in Perl.". Perl just makes everything so easy, IMHO of course. Hopefully I can successfully fend this attitude off until I get a good grasp of both Python and Lisp.

December 15, 2005

Multi-port support

I've recently written a std::string tokenizer, (which was really fun), and extended it to be able to tokenize port lists that looks like these...

21-80

21,23,80

or even...

21-80,5900,5800

So now Yavar can scan as many ports and as many kinds of combinations as you might want. I don't know if I want to give Yavar the ability to take this kind of port argument since it seems kinda malicious, however I think it's good to have the ability to do it within the scanning engine, so whether or not this sticks around will remain to be seen.