Tuesday, December 28, 2010

Check 21 Java app - 1 of 2

Extracting data and images from Image Cash Letter files

Background

There are many terms relating to Image Cash Letter files: Check 21, DSTU X9.37, X9.100-187, and check truncation, to name a few.

"Check 21" refers to an act passed in 2003. From Wikipedia's "Check 21 Act" article:

Thursday, December 16, 2010

Java greyscale conversion

Using Java, how do you convert a color image to greyscale? The most straightforward answer I've found was on Code Beach, and is as follows:

Saturday, November 20, 2010

Roman numerals redux

A simple JavaScript function to validate Roman numerals, convert them to Arabic numbers, and back again.

I checked Google Analytics this morning and noticed I've been getting a lot of hits on my October 9 entry on JavaScript Roman numeral conversion. In brief, I wrote a simple function to take a number and build its Roman numeral equivalent. While I was mulling it over this morning, I spontaneously thought of a method to validate and parse a Roman numeral and turn it back into Arabic numbers using regular expressions.

Monday, November 15, 2010

The crazy geometry of basketball courts

I saw an interesting question on dy/dan today about posing basketball-related math questions to students. One of the reader suggestions was to talk open-endedly about the geometry of the court itself, to which Dan suggested writing a program that would draw a court given two mouse clicks to denote the baseline. That sounded right up my alley, so I wrote one.

Before starting to code, I had to learn about the measurements of a basketball court, and I was a little surprised by what I found. First and foremost, every league has its own sizes for every piece of the court, most differing by a foot or less. The biggest discrepancy is with the length of the court, which is 10 feet less for high school than for NCAA and above, or about 2 running steps. Naturally the FIBA league had measurements rounded to meters where all the US leagues are rounded to feet.

Thursday, November 11, 2010

Jury Duty

On Wednesday, when I was up walking around to limber up after reading in a chair for a few hours, I came across the bulletin board in the jury pool waiting room. The board had several local newspaper op-ed pieces on jury service that may as well have been written by a chatbot, randomly generating from a dictionary of truisms and catch-phrases. "Ten Reasons I'm Glad I Served. 1: To see the inner-workings of the law. 2: To meet new friends..." Hence this post, a gritty look at my experience being on jury duty. The management summary: my experience was interesting, but the process is flawed. Like Randy Pees used to say, "Our legal system is terrible. The only one worse than ours is everyone else's."

About two weeks prior to my reading of the platitude-laden corkboard, I received a summons in the mail to report for jury duty. I tried to get out of it by replying with a letter claiming a child-care burden, as I pick up Scout from school on Tuesdays and Thursdays so that Liberty can attend later classes on those days. I got a phone call the next day telling me basically to suck it up and make other arrangements. Conveniently, this did not prove to be an actual problem: On Tuesday we were released before 5pm, and the courthouse was closed today for Veteran's Day.

Sunday, October 24, 2010

Awesome Ted talks

(plus some David Byrne worship, because he rocks)
(and Seth Godin at GEL, who also rocks)

Saturday, October 23, 2010

Fun music videos, mostly 80s

Some videos that are cool. No reason.

Saturday, October 09, 2010

JavaScript Roman numeral calculator

Yesterday I saw a homework question on a coding forum I frequent regarding turning Arabic numbers into Roman numerals. Homework questions are a strange breed. Most of the time the posters are blatantly cheating, some times they are up front that the question is for an assignment and they just want a push in the right direction. Responses range from helpful, following the Wikipedia "assume good faith" mantra, to cynical, to pretty damned rude. Forum admins enjoy flexing their dictatorial muscles in these cases, posting warnings, flames, and deleting posts.

My mantra in these cases is simple: If the question is interesting, I try to answer it. If the poster isn't cut out for a programming career, getting my answer isn't going to change that. If he is, he's going to be asking his peers a lot of questions over his career, as no one is born with an innate gift at coding; it's a learned skill like anything else. The young "super hacker" is generally the geek equivalent of a bully - not as skilled/tough as he pretends.

Thursday, October 07, 2010

Korn shell hack of the day

or, "Scope creep and you, a typical example of the modern IT project"

Sometimes I find myself knee deep in a complicated shell script that probably would have been better off written in perl or Java. Today was one of those days. What started as a simple script I wrote for managing sftp traffic to a couple vendors has been transmogrified to handle calling Glub to do an ftps transfer (the "other" secure FTP) from a vendor, then delivering the files to an internal Windows share drive. So far so good, but feature bloat ended up straining my creativity to tackle each new problem, and ultimately saddled me with a workable solution that, while interesting, is sort of a stinker.

The connection to the Windows share was supposed to be via a mounted drive. I would copy the files to a Unix directory, and Unix would manage the SMB transfer transparently. This turned out to be unsupported by our data services group unless the Windows server in question was virtual. It was not. So suddenly I'm on the hook for adding SMB support to the process.

Sunday, October 03, 2010

Picnic with the missus

Liberty got this cool wicker picnic basket on eBay a while ago, and we decided to take it out for a spin yesterday. One of the better side effects of "bill week" (when your bills all come due at once, and your budget spreadsheet looks a little scary) is that you can find fun money savers that double as relationship builders.

Instead of spending $20 on a movie and snacks just to sit in the dark and be quiet, let's go out for a walk in the sunshine and talk to each other... for free. Instead of stopping for greasy fast food somewhere, or spending more at a better restaurant, let's cook up some food for lunch, and take it with us somewhere. In this case, "some food" was steak cut into strips and fried up with pepper, sweet Italian mini bread, cheddar cheese cut into slices, some green onion, and a refreshing carbonated beverage (the basket has a cool separate area for bottles), and "somewhere" was Highbanks park.

When we got there, we found a long trail that didn't seem to have a lot of people on it, and proceeded to hike around looking for unofficial exit points: Good places to hang out that are accessible, hidden from the trail, but without signs saying not to go there. What we found was here:

Thursday, September 30, 2010

Bezier Curves as Ellipses

A couple weeks ago, I was exploring the source code for the Java runtime classes, trying to figure out exactly how Java draws a circle, and was surprised at what I found. A circle can be defined as an instance of the java.awt.geom.Ellipse2D class with equal width and height. Graphics2D attempts to draw the Ellipse2D shape by calling for its PathIterator. A PathIterator returns segments of the shape in the form of SEG_MOVETO, SEG_LINETO, SEG_QUADTO (quadratic Bezier curve), SEG_CUBICTO (cubic Bezier curve), or SEG_CLOSE. An Ellipse2D contains an initial MOVETO, four CUBICTO segments, and a final CLOSE.

I eventually got my head around what that meant and its implication: The standard 2D graphics library doesn't concern itself with center points and radii, or foci, or pi. In fact, it doesn't even render a real circle, but a very close approximation. It renders four cubic Bezier curves representing 90 degree arcs of the circle. I found this discovery strange at the time, but on reflection it made sense.

Tuesday, September 28, 2010

Form validation using custom attributes

Background

A couple months ago, a friend's daughter came to me for help with a website she was writing for a diabetes seminar registration page. The input form needed to ask the user if they had diabetes, and if so, whether it was type 1 or type 2. She was using Dreamweaver, and was having difficulty getting the form to behave correctly with Spry Widgets form validation.

I wasn't familiar with Spry Widgets (or Dreamweaver, for that matter), so I asked her to show me the source code. We hacked out a semi-functional solution in a few minutes, but I wasn't very happy with it. Spry had input validation that intercepted form submit events. You defined some JavaScript objects declaring what input elements were required, and what format they had to be in (e.g., the input must look like a phone number, or it must look like an email address). When you submitted the form, anything that was wrong gets highlighted red, and you have to go back and correct it.

The definition syntax for a single field looked like this:

Monday, September 27, 2010

Building a Java Applet Sudoku Bot

(Warning: huge and crazy, with no practical target audience that I can imagine.)

Background

I've been interested in the game of Sudoku since it became popular a few years ago, and have often daydreamed about what approach one could take to programmatically solve a puzzle. Although I'm not an expert player, when I play I find that I see complex hints about what numbers *must* go here, or *can not* go there. Explaining to another person the logic of each choice would be fairly simple, but coding a straightforward approach for a computer to do the same thing had, until recently, eluded me. I have now successfully licked that problem, and have written a moderately functional solver applet in Java.

This entry takes you through the start-to-finish process of the applet's creation. I decided from the outset not to make this a Swing applet, and to manage event handling and painting directly.

Sunday, September 26, 2010

Java Swing applet to calculate Fibonacci numbers

I understand this is a common skill builder in Java courses. To write this from scratch, you need to understand Swing input fields, layout management, action listeners, error trapping, and a little math. It also helps if you already think the Fibonacci sequence is cool.

So to help you seekers of assignment solutions, here you go. Study it, though, rather than just copying it wholesale. Maybe I'm not making this as streamlined as I should, or maybe the xor business is too much trouble for the modest speed and memory boost.

First, the working applet:

Saturday, September 25, 2010

Concise Perl

One of my favorite tech blogs is the relatively new Ksplice Software Blog, recently made popular with its unique solution to the recent Linux kernel exploit. In late May they posted an entry called The top 10 tricks of Perl one-liners, which brought back a slew of memories from several years ago when I was doing lots of system admin work from a Unix shell prompt, and also taught me a regular expression switch I had never come across before: \K. Commandline junkies being who they are, there was also ample discussion in the comments on everyone's favorite trick or idiom.

A few days after reading the article, I brought my eldest daughter, then 13, to work with me. She recently started high school, and was hanging out with me in the office completing a summer book summary assignment for an honors class due the first day of school. "Dad, what does 'concise' mean?" she asked me, while looking at the instructions. I replied something to the effect that it meant expressing a lot of detail in as few words as possible. The exchange reminded me of the above blog article, and also of some perl mojo I whipped up a couple weeks earlier at work.

Background

Monday, September 20, 2010

Detecting when a mouse cursor is near a line

Warning, this post contains math!

First, I'm abandoning all of my "recreational" coding projects save one: a java applet for my wife to design clothes. Building a CAD system from the ground up is painful and slow, and I can't tinker any further with other fun things without sapping creative energy I need for my day job.

In the current early stages of this project, I've been thinking a lot about design, and what I do and don't like about similar programs. One of the things I don't like about simple CAD-like tools is their approach to manipulating existing lines. The line's endpoints are draggable, and so is a single point in the middle, but the line itself is not. Take this screenshot of Visio, for example:

Thursday, September 16, 2010

Quick experiment with Java 2D, JComponents, and MouseListeners

Here's something I've been toying around with for a couple days as, of all things, a relaxation experiment. Basically when a shape is hollow, you can drag it to change its size. When a shape is solid, dragging positions it. Clicking on a shape without dragging flips it from hollow to solid, and sets its z-order to the top.

Enjoy!

Thursday, September 09, 2010

Labor Day adventure weekend, and the death of a friend

My wife is a saint. If you have any sort of relationship with Liberty, that may not be the first descriptor that jumps to mind, but I assure you it's true. In fact, there was a time when I believed her assertion that she has no empathy, but now I know that for what it really is: a complete ruse. It's her version of my blank expression that I meet most people with, the thing that's a little off-putting and helps me extricate myself from conversations, the thing that lets me keep my distance instead of getting too involved, and has nothing to do with what's actually going on upstairs.

Thursday, August 26, 2010

Fantasy RPG applet in Java, the early stages

For the past week I've been dabbling at home with building an old school Fantasy RPG, and I've been enjoying the hell out of it. It isn't playable yet by a longshot, as so far I've only got a combat framework and map scroller functional. For what the first real build of this will look like, think Bard's Tale 2. Think Ultima 4. At least, that's what I'm thinking now, as turning this into Diablo or World of Warcraft is still a long way off.

I got the itch to design a game after toying around with Google's App Engine framework. I wrote a slideshow unwrapper for my wife to use when browsing on Ebay or Etsy, which lets you paste in several URLs with slideshows in them, and builds a single page containing all the images. App Engine's "fetch url" function and the ability to execute arbitrary Java code made that a snap. While learning the App Engine ropes, I found that it can serve an applet, and receive an arbitrary serialized object and store it in Google's "data store".

In other words, you can play a game in an applet, and save the game state to the data store.

Wednesday, August 18, 2010

A lightweight Java solution to searching image archives

About a month ago, my wife found a collection of dress images, one of her favorite things to search for online, as she is fond of analyzing how clothes are put together and then making her own. The collection was in the form of a Shockwave file, in a neat little scroller app that lets you scan through dresses seen from different angles, find what you like, and go buy it. My wife was unable to save image files from the app, so she elicited my help in the matter.

Sunday, August 08, 2010

Solving the Facebook “Gattaca” puzzle

If you're coming here looking for an algorithm or complete code to solve Facebook's Gattaca puzzle, then first, you're a damned cheater and nobody likes you. Second, they'll never hire you anyway once they realize you couldn't do it on your own. Third, you've come to the right place!

Google assures me that there are publicly available solutions for this puzzle already, and this particular puzzle has been posted in the Facebook careers section for a while now, so I'm going to break with their recommendation to not distribute complete solutions.

Monday, June 28, 2010

My Strange and Awesome Karate Kid Dream

I recently saw the remake of The Karate Kid with Jackie Chan, and enjoyed it quite a bit. In case you haven't seen the movie, I won't say anything about the movie other than what's in the trailer. One of the winking nods to the original was Mr. Han (Chan's recasting of Mr. Miyagi) not catching a fly with chopsticks, but rather killing one with a flyswatter, then using chopsticks to pull it off of the wall and throw it away... a main plot point in the dream I had last night.

My dream was fairly brief, and a bit of backstory was implied, but not shown in the dream itself: Mr. Han now runs a martial arts school. One of his students is a teenaged girl from a culture not very... how shall we say... "women's studies friendly". (It was unclear where specifically she was from - maybe Iran, maybe an African village. My dreams are ambiguous like that). She had an overbearing father who was waivering between supporting his daughter at the school, and pulling her out to have her veiled, executed for being alone with a male non-relative, circumcised, what have you. Mr. Han, sensitive to her plight, does what he can to keep her healthy and free.

Thursday, May 20, 2010

JavaScript phone number reformatting, programmatically setting onblur

There are two problems I solved in a hurry last night that are apparently talked about a lot in JavaScript forums:
- Detecting something in a text input field that looks like a phone number. and remformatting it to the standard (xxx) xxx-xxxx layout
- Programmatically setting the onblur of a text input field

Thursday, May 13, 2010

Some feedback, s'il vous plaît

I've been keeping an online journal for about 10 years now, in one form or another. I kept the site auterytech.com as my domain running on a headless, older Debian box running in a closet until about 5 years ago, when I converted to Blogger. I signed up a gmail account shortly before losing the awesome "curtis@auterytech.com" email address when I let my domain expire, and opted to combat spam by not listing my email address on the new blog. (The old domain was quickly snatched up by a squatter, and he is happily spending his $10 per year, or whatever domains cost these days, on static lists of search keywords for some nefarious purpose or other.)

Before the conversion, I would occasionally get emails from people I knew but lost contact with, who would tell me they stumbled on the page, liked my writing, and wished me well. Other than that, I had no contact with the site's readers.

I've been on Facebook for a couple years now, which has taught me that a lack of response to a thing does not imply a lack of an audience. When FBers threw events that I would attend, occasionally someone would mention something to me about something I'd posted but no one commented on. "Oh, " I would say, "I had no idea anyone even saw that."



Sunday, May 09, 2010

Creating an Archimedean Spiral generator in Java using the NetBeans IDE

[The images below can be enlarged by clicking on them]

My wife, Liberty, is an amalgam of seamstress, hippy, punk, old-school goth (real goth, not depressed teen sparkly lip gloss emo nonsense), WWII and vintage clothing buff, musical and action movie lover. I am a computer programmer, recovering video game and comic book geek, soccer and puzzle buff, ex helicopter parent. Other than a love of things not mainstream, we sometimes struggle to find areas where our interests overlap.

A few months ago, Liberty thought of something I could do with one of my specialties to assist her with one of her hobbies: write a program to design her next tattoo. Specifically, I would write a program to create interlaced spirals. I told her it would be tough, as most of my coding over the years hasn't included graphics. I experimented with a Java painting applet close to 10 years ago, and, although fearing what I used back then would have been deprecated from the language, or that I would be too far behind the curve with modern IDEs, I set out to give it the old college try. You see, I love my wife, and I'm usually up for a new challenge or puzzle to solve.

I tinkered away in the evenings and early mornings, learning how to use NetBeans, relearning how to create image and graphics objects in Java, how to correctly override the paint() method, and the math of spirals.

I decided to use the Archimedean Spiral, sometimes called the Hypnosis Spiral, whose spines are always equidistant from each other. Wikipedia has an article on that here, which I'll summarize briefly: r = aθ, meaning the radius is some constant times the angle.

Monday, May 03, 2010

40 creeps one year closer

Six years and nine months ago, I was hired at AEP, on the recommendation of a man I worked with at Sterling Commerce. Jerod has since gone on to bigger and better things (I believe he is currently the head of IT Security at Abercrombie & Fitch), and I have remained here, notable only because I have never stayed at a job this long before. My usual itch to flee and seek my fortune elsewhere comes and goes, as always, but I am comfortable enough where I'm at to not act on it. At least, to not act on it for a few more years.

Recently AEP gave me a permanent parking spot in the main building's garage. The spots are doled out as people retire and your place in the queue is determined by your hire date. The spot saves me about 10 minutes daily of searching for a spot in the "unassigned" garage across the street from the main building, and walking down a few flights of stairs where business-casual cubicle dwellers (like myself) crowd me in a panic, and storm past me in a huff for being slowed down on the way to their morning coffee, meetings, and arbitrary clerical deadline of being inside the building. Unlike myself. I'm a stroller in the morning, a meanderer still recovering from my commute-induced daydreams. My coworkers are nothing of the sort, and for 6 years I've been watching them scurry about hurriedly first thing in the morning, which I thought was nothing more than a minor annoyance, until I stopped seeing it every day. Suddenly my commute is peaceful from start to finish, and I reach my desk calm and content.

The seemingly small change of removing that daily stress has had a remarkable effect on my mood and my work, and has sparked in me a reflection on my path through life to get where I'm at. Where am I? 39 years old today, comfortable in a job where I get to be creative intermittently, watching my little girl grow up and get the social successes my bumbling always kept her from in the past, struggling to keep a happy wife and stepdaughter, and a roof over all our heads. I'm hoping to find through my reflection where my ambition went, why my eventual death is suddenly more real to me, and a clue as to where I'll be in another decade. Still at the same job? Still married? Will I be in the same house?

Wednesday, April 28, 2010

How to invoke a Java method from JavaScript

It's surprisingly easy. Basically the applet you declare in the <applet> tag sets up the Java class as an object that can be referenced with standard DOM calls.

For the purpose of this example, I'm not displaying anything with the sample applet, only returning values from method calls, so the code doesn't import awt or Swing, only java.applet.Applet.

Here is a sample java class that exposes two methods, add and subtract:
package cea.demos;

import java.applet.Applet;
public class Arithmetic extends Applet {

  public int add(int x, int y) {
    return x + y;
  }

  public int subtract(int x, int y) {
    return x - y;
  }
}

Tuesday, April 27, 2010

Using File-AID Batch to update multiple PDS members

Today at work I found I had multiple members of a partitioned data set that I wanted to update from a batch job. I had previously written an RPF to do this, but post-Sarbanes/Oxley fallout has caused us to change our dataset permissions and procedures somewhat, so I needed to update with JCL this time.

I was trying to fool around with using TSO edit commands to update the files using IKJEFT01 to invoke a TSO shell, and my boss saw what I was doing and suggested File-AID instead. File-AID is very flexible and fast, but the documentation is a little daunting, and I've never taken a class on it or found any tutorials that I could tolerate. However, with some trial and error I was able to get it to update my dataset members without any problems, and my final JCL read pretty well, unlike some of the more unintelligible arcana I've submitted to the mainframe in the past.

Sunday, April 25, 2010

DHTML events - blast from the past

Back in 2003, I was working on JavaScript code that would function as a text editor/web page authoring tool. It worked within a browser without textarea or other input fields (text you typed appeared in the main body of the page). It was semi-functional, including pop-up right-click menus that let you paste in a few HTML tags, a Java applet to read and write files to disk, and instructions for the user to allow the applet disk access. The whole thing was pointless, as even back then there were better rich text/WYSIWYG web page editors out there, but it was a fun programming exercise. The original source for it is available here if you want to download it and toy with it. It works with IE8, but I think there was a new problem introduced with modern Firefox versions that I never got around to fixing. I also just tried it in Chrome and it just silently fails. Bummin'.

Here are a few screenshots of it in action, showing how to start with blank page, open the right-click menu to add some stuff, and testing the results:

Monday, April 19, 2010

Tax-time blues ain't so bad

I've been away from the blog for a while, due mainly to not having anything I wanted to share, and also being low on creative energy. My work has been draining my batteries for a change, which is good. This week should afford me renewed blogging time and energy, as I'm in a training class that gives frequent breaks, and has frequent problems sharing desktops and application servers with remote students.

So Liberty got laid off, which has so far not had a dramatic impact on us. She gets to spend more time with Scout and her mom, and has been pretty relaxed at home. I no longer get my two nights per week alone with Scout, which I have mixed feelings about. Liberty is also stumbling through the beauracracy of Job & Family Services again to attempt to get unemployment benefits. They seem to be using the fact that she is in school to avoid paying benefits, so she's in the process of job hunting.

My work may also be going into the laying off business pretty soon. (news article) That would put us in an interesting position after a few months, namely being hobos. Or selling off all our garage and basement crap on ebay while scrambling for new jobs.

Tax season was pretty bad, but not life-altering. I owed more money than I got in my annual bonus, and had been unable to save up for the IRS because of the extra financial burdens I've talked about in previous posts. So I made a deal to pay what I could up front, and pay up in full (plus a modest penalty) within 120 days. So no playing for a while, but no debtor's prison either. So it goes.

Tuesday, March 09, 2010

An Open Letter to the Disney Corporation

Dear Disney,

Thank you for the 57 mailings we received yesterday advertising your $500 per night resort rooms. Unfortunately, the various names on the mailings, presumably made up by one of my daughter's school friends as a prank (as they share a lot of their last names), do not live here. Additionally, we live in a single family home which could not comfortably support 57 people as a main residence.

I can only assume that you have a computer database with which you extract the addresses from. If it is a modern relational database that supports the SQL language, you may be able to leverage such functionality as the "group by" and "having" clauses to prevent obviously fraudulent database items, perhaps substituting a single "Seymour Butts or Current Resident" mailing.

Here is an example SQL statement to illustrate my point. My main assumption here is that it is unlikely for a single address to have more than 4 families living in it that are likely to vacation at Disney resorts, therefore you can safely cull out addresses that occur 5 or more times in the database with a statement such as:

select address,count(*) from address_tbl group by address having count(*) < 5

Please run that by your DBAs and get their take on it, and, more importantly, stop enabling mail fraud. It's a felony, after all.

Tuesday, March 02, 2010

Three table inner join vs. the staging table

or as we perl users say, "There's more than one way to do it."

I was faced with an odd situation at work a few days ago, and it led me to do a lot more raw SQL tinkering than I typically do. The situation takes a little setup. (I'll say up front that if you don't fancy yourself a geek, don't torture yourself with the rest of this post, but tune in next week for tales of back-to-back concerts at the Newport!)

My team performs application integration, and our preferred method of doing so is with web services that are modeled. "Modeled" in our parlance refers to being managed by a piece of software called webMethods Modeler. It provides pretty pictures of running services, complete with checkmarks as steps get completed, or big red Xs if they fail.

The services we provide mainly move documents around, doing any needed transformation on them. We take all the possible fields that a business process could want, and create a master document definition called a "canonical", whose definition resembles, but is not congruent with, the normal lay usage. We take inbound documents and map them to the canonical format, and subscribers to the documents get the canonical mapped to their preferred format. Because of this, a complete process definition has two models: one for the publisher, one for each subscriber.

Saturday, February 27, 2010

Where the hell did my alternative music go?

"Let's go and throw
All the songs we know
Into the sea" - Robert Smith

So today I'm driving the wife to work, and we're listening to CD101 -- you know, Columbus' alternative station -- and the DJ says the following:

"Your 9am lounge tip is 'island'. That's 'island', I-S-L-A-N-D."

"Wow," says I to Liberty "so their target audience now can't spell." After dropping her off, I kept listening, and a "Tegan and Sara" song came on that contained the following lyrics:

"I just want back in your head
I'm not unfaithful but I'll stray
When I get a little scared"

I usually tend to avoid blaspheming, but... weeping Jesus on the cross, when the hell did alternative turn into mainstream pop for idiots and emo posers? CD101, in the 90s, had a reputation for playing unusual tunes that would never get air play anywhere else, and their target audience was me and my fresh-out-of-school snobby intellectual posse, who would jam to it and revel in our rejection of all things mainstream. We had the lovely Siouxsie Sioux, treating us to interesting gems such as:

Saturday, January 23, 2010

Closures and Objects in JavaScript


"If you want to make an apple pie from scratch, you must first create the universe." - Carl Sagan

I've always hated the word "JavaScript". What's up with that capital S? However I've always loved the language. I learned the basics of it when Netscape 3 came out in 1996, and was immediately hooked. Your web browser became a scripting language interpreter, how cool! Before then most web pages were static, and business websites, if they existed at all, were mainly shells listing contact information and displaying the company logo.

Some pages I stumbled on back then used CGI scripts to take user input and do something with it - private content that required a login, rudimentary chat, surveys like the ever-popular "purity test", Pi calculators (show me __ digits of Pi [Submit]), things like that. The scripts were all server-side, though. The code was being executed from private space in the web server's cgi-bin directory. For people relatively new to the web like myself, doing something like this was an impossibility. We hadn't found Linux or Apache yet, hadn't learned perl or shell scripting, and our web hosts were angelfire, geocities, tripod, and CompuServe and AOL's user page areas. We could do chili recipes, pictures of our cats, and link to other people's recipes and cat pictures, but not write anything interactive.

From the professional programmers of 1996, Javascript was immediately scorned as a toy for little kids playing progammer. For those of us with a little insight who didn't have cgi-bin access on the web host we were using, Javascript was nothing less than a godsend. We struggled to do client-side what could previously only be done by a script on the webserver. We begged for more features from Netscape. Microsoft struggled to copy the functionality with JScript. Standards bodies struggled to make a standard language definition out of it. Good times.

Monday, January 18, 2010

Good recursion, bad recursion

"Go to the store, buy some more, 99 bottles of beer on the wall!" - 99 Bottles of Beer

Factorials are a common math problem used in computer programming tutorials. For those who don't remember them from 5th grade math class, factorials are integers followed by an exclamation mark. You multiply the number by all the numbers that come before it, down to 1. They go thusly:

1! = 1
2! = 2 * 1 = 2
3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24
...etc

Another way of expressing this same idea is with recursion. Recursion is basically self-reference in an expression. Let's use the euphemism "Same shit, different day" to illustrate:

shit(day) = shit(day - 1)

Thursday, January 14, 2010

Gaming and Coding

So I've been killing lots of time lately playing Flash video games on the kongregate.com games portal. The one I'm currently whittling my way through is called "Cargo Bridge", where you have to build wood or steel bridges across gaps, and then laborers test the bridge by transporting boxes of unknown contents across it, as well as the occasional elephant.

The game that got me hooked on Flash games is called "Use Boxmen". I discovered that a couple months ago, and after beating the game I quickly sought out others. Naturally I've played puzzle games on the web before, but Boxmen was the one that really piqued my interest in the genre. I found it on Kongregate, but it is hosted also at the author's homepage.

The game is very cartoonized with stick figure avatars, and reminds me vaguely of "Simon in the Land of Chalk Drawings". I found it when looking for the "Quake Done Quick" walkthroughs on youtube, and then just browsed around looking at walkthroughs of other games. I found the boxmen one here:

Wednesday, January 06, 2010

Google Analytics, and sometimes I can't do math

First, my apologies to rich people: You're getting at most a $65 tax break over last year, not the 5% I promised you. I didn't account for the extra tax brackets that came with the new withholding tables. There are nine tax brackets now rather than seven, and things line up less disturbingly than I thought. Still, poor people have a higher tax obligation than last year, rich people a smaller one. The amounts are now insignificant, but the symbolism is still bad.

Here are the corrected charts, first, how much normal people will be paying extra, then how much less rich people will be paying. I'm including the new amounts for people filing as married, as well.





Monday, January 04, 2010

Oh, it really is the rich getting richer, after all

(Update, Jan 6, 2010 - Bad math corrected.)

I've heard the phrase "it's the rich gettin' richer and the poor gettin' poorer" often throughout my life, usually by old-timers discussing politics, social mobility, the decline of the middle class, things like that. Like most things people say when they're complaining about the government or "rich people", I didn't put much stock in it.

Each year since 2006 I have created a spreadsheet at work to calculate what my paycheck should be. You fill in how much you pay for insurance, whether you're filing as single or married, how many exemptions you're claiming, and your salary, and it outputs what your paycheck should be - give or take a couple pennies. To make it work correctly, I stumbled through figuring out how gross, taxable, and net income are calculated, what federal, state, and local withholdings should be, how exemptions work, how 401k and company paid benefits are calculated, what marital status really changes. Here are a couple examples to show how nuts payroll math can be:
  • 401k isn't tax-free. Medicare, Social Security, and the city of Columbus all tax your 401k contributions.
  • Saying you're married on your W-4 decreases federal withholding only, and only if you make more than $15,000. The state of Ohio doesn't care if you're married or not.
  • Employee-paid benefits (life insurance, for example) aren't really free. They count as a raise in taxable income that is deducted back off after withholding is calculated.
So today I started on this year's spreadsheet using the withholding tables listed on 2010's Publication 15 on irs.gov. The tables looked odd, making me suspicious, so I investigated and got all mathy. Usually as your pay rate goes up, your tax rate goes up. In 2009, for example, single people making over $10,400 annually were taxed at 15%. Those making over $36,200 were taxed at 25%. $66,530 = 28%, $173,600 = 33%, and $375,000 = 35%. This year was similar, unless you make between $84,450 and $87,700. In that range, your tax rate jumps up from 27% to 30%. After $87,700, the rate drops back down to 28%. Confused, I decided to run the 2009 tables and 2010 tables through for different pay rates to see what the real tax amount would be for each income level. As you can predict, that produced a pile of meaningless numbers, and my eyes quickly crossed. "OK, then," I said to myself "let's just subtract the 2010 tax from the 2009 tax for different income levels and see what happens". It took a few seconds of glancing at the results for me to loudly declare that yes, indeed, the rich are getting richer, and the poor are getting poorer. Not by much, but by enough to notice. If you make $10,000, this year you'll pay $113 more in federal deductions than you did in 2009. If you make $200,000 annually, this year you'll pay $1,000 $25.85 LESS in federal withholdings than you did last year. Here's a chart showing some sample incomes and change in withholdings, including the sweet-spot of $76,865 where the withholding is the same both years: