Code


20
May 09

How To: Get anti-aliased fonts in the Arduino and Processing IDE’s

Problem:

Arduino and Processing IDE’s both are java applications and don’t use anti-aliasing when displaying fonts on OS X.

Solution:

Add the Java Swing options to enable anti aliasing to the Info.plist file that OS X uses to launch the IDE’s.

Steps:
Right click the Arduino.app in the Finder and select ‘Show Package Contents’, double click the Contents directory and there you will find the Info.plist file. Open it in a text editor of your choice.
Add the following two lines under the Java option. See the screenshot for the exact location.

<key>VMOptions</key>
<string>-Dswing.aatext=true
</string>

UpdatePlistScreenShot

Now your code editor goes from looking like this crapness:

noaliasing

To this hotness:

withantialiasing

And even better you can use great looking fonts like Inconsolata and get an editor that looks this good:
inconsolasarduino


22
Feb 09

Quick look support for .mxml and .as files

I’ve recently re-installed OSX and lost my quicklook support for .mxml and .as files. Since I couldn’t find whatever packages I had installed that allowed that quicklook support, I’ve modified QLColorCode to add support for previewing both .as files and .mxml files.

It works on my computer and I hope that it’ll work on yours too.

Please feel free to download my version, qlcolorcodeqlgenerator unzip and install, let me know if it doesn’t work.

Installation instructions for quicklook plugins can be found here.

-josh


24
Jan 09

Networked Sound Board

Hi Everybody,

I’ve created a network sound board that you can use to have endless fun with co-workers.

In my office quad we have one OSX machine that is used to play music for everyone, it’s usually running last.fm, pandora or someones iTunes library as background music for everyone. Occasionally it gets cranked up when it’s time to get the led out. I was thinking that it’d be fun to be able to trigger sound effects on that machine from my machine, kind of like what happens on radio shows, expect that my co-workers wouldn’t really be able to change the channel.

So the itch was scratched and I’m proud to present the network sound board. It should run out of the box on any OSX machine with a recent installation of Python. If you’re on Windows or Linux it’ll work if you can find a command line audio player.  Anybody on the same network as the music machine will be able to trigger the sound effects from the comfort of their browsers. After you install there is a soundEffects folder that you can place sound files (.wav/mp3) into and they are instantly available, check the documentation for more info.

You can git the source from github at http://github.com/code128/networkedsoundboard/tree/master

It looks like this.

networked_soundboard

If you’re looking to extend it, adding the ability to upload new sounds from the flex interface would be sweet. If you do let me know.

Have fun.

P.S. If you can get samples of your co-workers saying things and add them to the server that would just be the icing on the comedy cake.


22
Dec 08

Just sitting here watching the logs go by.

Some times while working on remote servers I need to watch various log files. Typically for something like this I’ll create an extremely simple script that watches all the logs at once, since the next time I’m on that machine I’ll probably have forgotten the paths in question.

Something like this:

tail -f /var/www/apache/access.log /var/www/apache/error.log

The problem with that approach is really long lines wrap and I usually just care about the far left of the file, so I’ve been looking for a way to turn off wrapping in tail. Unfortunately that seems to be impossible. I tried messing with my shell to kill the extra characters with this:

echo -e "\e[?7l\c"

But that was messing up other things. The best solution I’ve found so far is to use less with these options

less +F -S /var/log/apache/access.log

+F puts it in a tail like mode and -S chops the line to the screen width, the only drawback is that it doesn’t intersperse the 2 files like tail does. I was hoping to pipe tails input into less in the this fashion but that didn’t seem to work right either.


22
Oct 08

Iterating over a custom object in python

A coworker recently needed to iterate over a custom object in python. It’s pretty easy to do, you just need to implement the __iter__ method on your object.

Here’s some example code that shows you how to extend your object, returning everything in your objects local dictionary:

class IterableObject(object):
    def __iter__(self):
        for item in self.__dict__:
            yield self.__dict__[item]

Now for sample usage:

myObj = IterableObject()
myObj.name = "Johnny Hammersticks"
myObj.otherProperty = "Something Else"
myObj.testList = [1,2,3,4]
myObj.testDict = {1:'one', 2:'two'}
# Serialize the IterableObject into json
for x in myObj:
     print x, type(x)

which returns:

Something Else <type 'str'>
{1: 'one', 2: 'two'} <type 'dict'>
[1, 2, 3, 4] <type 'list'>
Johnny Hammersticks <type 'str'>

Oh and another handy feature of this dictionary style approach, you can do easy string formatting/printing of the object properties in this style.

print "Hi %(name)s, your list %(testList)s" % myObj.__dict__

Which prints:

Hi Johnny Hammersticks, your list: [1, 2, 3, 4]

20
Oct 08

FlixBot

I’ve built a proof of concept in some hacked together python code to automatically add movies to my netflix queue when I send twitter messages to @flixbot.

For example this tweet:

Gets Blade into my queue. Awesome.

I started building this out into a full fledged service so other people can use it as well. Of course I’m going to need a hosted site somewhere for people to sign up. I figured it might be a good time to play with my app engine account.

I got part of the way of there with app engine serving up pages, but then ran into problems with xml libraries I was using in my POC not existing in the AppEngine sandbox. :(

Also I’m starting to run out of enthusiasm.

So that’s where I’m at. Goodnight.


7
May 08

_why the lucky stiff is awesome.

Yet more proof of his awesomeness.

http://hackety.org/2008/05/05/sneakingRubyThroughGoogleAppEngine.html

Basically he’s shown a proof of converting Ruby bytecode into Python bytecode, enabling ruby to run in python only places, like Google app-engine. Quite cool.

Additionally he’s been creating hackety-hack which is an environment for anyone (children) to learn programming. _why’s built it out of ruby and gecko and his own shoes framework, it looks great so far.

Check out the first bylaw of hackety-hack:

Beginners should be greeted to Hackety Hack by a cartoon character. (For the sake of argument, let’s call this character: Hacky Mouse.)

Check it out:

hackety-hack


10
Apr 08

Using Flexbuilder to edit and debug Flash Applications

The goal here is to use the excellent code editing and application debugging/profiling available in Flexbuilder and still have the rapid prototyping and layout ability that the Flash IDE gives to you.

To get started create a new “Actionscript Project” in Flexbuilder.

Now we will add some code to testDebug.as that traces out when the application is run:

package {
import flash.display.Sprite;
public class testDebug extends Sprite
{
public function testDebug()
{
trace("I am created")
}
}
}

With that code saved we will Debug this actionscript project and if everything is working correctly you should see something like this in your console window:

So far everything is working correctly in Flexbuilder, now lets get Flash into the action.

Open up flash and create a new Flash file, lets call it TestFlexBuilderIntegration.fla. Add some timeline animation or something so you know it’s coming from the Flash IDE, save this file into the root directory of your new Flex project.

Now set the document class of your Flash file to ‘testDebug.’ The AS class that we wrote in flexbuilder will now be the document class for your flash file as well.

Here come the tricks, under Publish Settings enable “Permit debugging”

Next in the Formats tab of Publish Settings change the .swf file to be published to the flexbuilder bin-debug folder.

The path will be something like

"/Users/YourName/Workspace/testDebug/bin-debug"

Now if you test the movie in Flash you should see your animation as well as the trace “I am created” in the flash IDE.

For the final steps we go back to Flexbuilder and under the html-template folder open index.template.html in a text editor. This is a template file that generates the index.html that is used to launch your app. We are going to update it so it points to the .swf generated by Flash IDE instead of Flexbuilder.

Replace all occurrences of ${swf} with the name of your Flash IDE generated swf file. In this case it would be TestFlexBuilderIntegration.

The moment of truth! In Flexbuilder Debug your project, it should launch the .swf in a browser for you and the animation you created should be playing, additionally the trace(”I am created”) line should show up in your console.

If Flexbuilder has trouble connecting to the debugger, right click in the swf in the browser and change the debugger connection to 127.0.0.1 and that should solve that issue.

Now you have the full power of Flexbuilder to code and debug and you still have the Flash IDE to layout movieclips and rapidly prototype things. Sweet.

Notes:

As you make changes to the code in Flexbuilder, you’ll need to go back to Flash and republish.

Profiling should probably work as well though I haven’t played with it yet.

You can set breakpoints in Flexbuilder without needing to republish.


21
Jan 08

Duplicate music file finder code.

I’ve been consolidating my music collection and found that there were lots of duplicate files.

Most of the dupes were named something like “Happy Birthday 1.mp3″ and “Happy Birthday.mp3″ would exist in the same directory. I’m not sure which program added these dupes, but removing 2500 or so of em by hand would not be fun.

Without further ado, here’s some python code that takes care of that problem for you. It only examines the filename, not the date or the bitrate or the actual file contents, etc. But you could of course extend it to do all those things.

Enjoy.

#-------------------------------------------------------------------------------
# Name:        cleanDuplicateMusicFiles.py
# Purpose:     Loops over a directory structure looking for 'duplicate' music files
#				and moving them to a safe directory for deletion.
#
# Author:      Joshua Bloom
#
# Created:     01/18/2008
#-------------------------------------------------------------------------------
#!/usr/bin/env python
 
import os
import sys
 
dupList = []
rootDirectory = "/Users/joshbloom/Music/iTunes/iTunes Music"
sequesteredFilesDirectory = "/Users/joshbloom"
 
def main():
    print "Starting search ..."
    checkDir(rootDirectory)
    print "Found %s dupes" % len(dupList)
 
def checkDir(path):
    print "Checking path '%s' for duplicates" % os.path.basename(path)
    for item in [ os.path.join(path, x) for x in os.listdir(path) ]:
        if os.path.isdir(item):
            checkDir(item)
        else:
            checkForDupe(item)
 
def checkForDupe(fName):
	'''Example: if we find 'Happy Birthday 1.mp3' and 'Happy Birthday.mp3' exists in the
	same directory we consider this a duplicate and send it for re-education. '''
    fileName = os.path.basename(fName)
    folderList = os.listdir(os.path.dirname(fName))
    if fileName.endswith("1.mp3"):
        for otherName in folderList:
            if otherName != fileName: #Make sure we aren't comparing with the current file
                if os.path.basename (otherName).startswith(fileName[:-6]):
                    #This is a duplicate
                    dupList.append(fName)
                    sequesterDup(fName)
 
def sequesterDup(fName):
    ''' Move em to a new folder, if you were confident you could change
 		this function to delete the file. '''
    try:
        print "Moving file: %s" % fName
        os.rename(fName, os.path.join(sequesteredFilesDirectory, os.path.basename(fName)) )
    except Exception, E:
        print E
 
if __name__ == '__main__':
    main()

30
Oct 07

XRay Logging with AS3

Using Xray you can utilize logging in your AS3 development in a nice clean manner. One of the great benefits here is that your logging/debugging process can be the same when developing locally and when you are running on your development and production servers.

To get started download the latest xray code from their SVN repository.
http://code.google.com/p/osflash-xray/source

Then create a new AS3 flash document using the code below as the document class:
Make sure that you add the ‘trunk’ directory that you downloaded to your class path (so flash can find the xray files)

Once you are compiling correctly, launch the xray viewer in a browser from http://www.rockonflash.com/xray/flex/Xray.html. You will get a notification about not finding a SWF to connect with, ignore this for now (full xray support is not yet therefor AS3 projects). Make sure that the Show Output checkbox along the bottom is checked.

Now if you click the red square in your swf player, you should see the following show up in the XRay viewer windows.

Congratulations you are now logging. Big thanks to John Grden and everyone else contributing to Flash development methodologies.

picture-4.png

package {
	import com.blitzagency.xray.logger.XrayLog;
 
	import flash.display.*;
	import flash.events.*;
 
	public class testLoggingAS extends MovieClip {
 
		private var log:XrayLog = new XrayLog();
		private var mc:MovieClip
 
		public function testLoggingAS() {
			log.debug("Application starting up");
			createClickableMovieClip()
			log.debug("Application has completed startup");
		}
 
		private function showTheClick(e:Event):void {
			log.debug("Square was clicked. Tracing out the Event", [e]);
		}
 
		private function createClickableMovieClip():void {
			mc = new MovieClip();
			mc.name = "ClickableMovieClip"
			mc.graphics.beginFill(0xFF0000);
			mc.graphics.drawRect(0, 0, 100, 80);
			mc.graphics.endFill();
			mc.x = 80;
			mc.y = 60;
			addChild(mc);
			mc.addEventListener(MouseEvent.CLICK, showTheClick)
		}
 
	}
}