Skip to main content

Posts

Showing posts from 2010

Ubuntu Packages Please Get Your Act Together

I didn't intend to write another blog entry so close to the conclusion of my Week with Go series, but my experiences earlier today definitely warranted a rant. Installing the SpiderMonkey JavaScript engine for use as a stand-alone interpreter on Ubuntu 10.04 LTS doesn't sound like outlandish goal. After all, CouchDB ships by default as of 9.10 and it requires a JavaScript run-time. Technologies like node.js and v8 are pretty hot right now so there might even be a few alternatives to choose from, right? WRONG!
sudo apt-get install spidermonkey-bin E: Couldn't find package spidermonkey-binThere used to be such a package but apparently SpiderMonkey is "unsupported" now and was removed from the Universe repository.

Sorry Ubuntu. I'm not feeling the love for Rhino. It doesn't do JIT and runs slower than a one-legged sloth. Besides, I don't feel like installing ca-certificates-java, default-jre-headless, icedtea-6-jre-cacao, java-common, libavahi-client3, li…

A Week with Go, Day 5

Concurrent programming in Go makes use of coroutines, which are quaintly called "goroutines", and channels. Coroutines are functions executed asynchronously from the rest of your program, and channels are synchronous pipes through which the routines communicate. I had written a multi-threaded Kember Identity program in C a while back, and decided to rewrite it in Go to gain some exposure working with these features.

The Effective Go primer gives a hint of what goes on under the hood with coroutines in Go.
A goroutine has a simple model: it is a function executing in parallel with other goroutines in the same address space. It is lightweight, costing little more than the allocation of stack space. And the stacks start small, so they are cheap, and grow by allocating (and freeing) heap storage as required.

Goroutines are multiplexed onto multiple OS threads so if one should block, such as while waiting for I/O, others continue to run. Their design hides many of the complexities…

A Week with Go, Day 4

Day 4 was spent learning about Go's take on object oriented programming, which I found to be a refreshing change from the likes of Java and C#. It's not type-focused; instead of relying on an object's type to know whether or not it offer certain functionality, the object will generally implement an interface. This mindset is not dissimilar to good JavaScript programming where feature detection is preferred over browser sniffing. The code doesn't care what something is (browser/object), just what it can do (functionality/interface).

The word "object" is probably a bit misleading since Go doesn't really have them in the traditional sense. There's no need to write a class definition as in Java, nor to instantiate an object literal like JavaScript. The programmer specifies a set of functions and Go's compiler deduces the relationships.
type Rectangle struct { width float height float } func (r *Rectangle) Area() float { return r.width * r…

A Week with Go, Day 3

The first two days of tinkering and scouring helped me form an opinion of Go based on its syntax. To form a more-informed opinion I would have to write some more code and see how much resistance I experienced along the way. What features were missing? How was typing applied? I wrote a rudimentary version of Deal or No Deal, and slowly some of those meaningless sections in the language spec started taking on more meaning.

I decided to store the case amounts as an integer array (nobody likes the 0.01 anyway!) and came across my first bit of frustration and misunderstanding when it came time to shuffle the amounts.
cases = []int{100, 200, 300, 400, 500, 750, 1000, 5000, 10000, 50000} shuffle(cases) func shuffle(arr []int) { rand.Seed(time.Nanoseconds()) for i := len(arr) - 1; i > 0; i-- { j := rand.Intn(i) arr[i], arr[j] = arr[j], arr[i] } }The language spec says arrays are value types and slices are reference types. shuffle …

A Week with Go, Day 2

After dabbling a little bit on day 1, I dedicated some time on day 2 to skim through Go's language spec and standard libraries. A lot of it didn't have much relevance to me yet because I hadn't begun to play with those parts of the language. What caught my eye though was that Go supports the \v escape (obviously no one at Google has read Stop the Vertical Tab Madness). Welcome to 1963, folks.

In addition to tweaking how loops are written, Go has augmented the traditional syntax of if and switch statements too. I don't see the enhancement providing as much benefit as I do with for. It's almost as if someone decided to let people move the placement of if up a statement earlier just to be different, and it certainly doesn't read well.
x := recover() if x != nil { ... }vs
if x := recover(); x != nil { ... }
The list of available packages is rather impressive considering Go has been available for a year. Some packages are pretty standard, like math and cmath, while so…

A Week with Go, Day 1

Go is a general purpose systems programming language developed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Go has been on my radar since it became publicly available a year ago as an open source project, and since then its documentation has been improving and a small community of users has been forming around the language. Last week I had some time off from work that coincided nicely with the Thanksgiving holiday and I thought it'd be fun to spend some of it looking at Go. Here's the first in a series of five posts that share my thoughts and experiences of spending a week with Go.

My first Go programs were solutions to a couple Project Euler solutions. This was just to get a basic feel for its syntax.

Problem 1
package main import fmt "fmt" func main() { sum := 0 for i := 0; i < 1000; i++ { if i%3 == 0 || i%5 == 0 { sum += i } } fmt.Printf("%d\n", sum) }
There are a few oddities, but overall ther…

On Gartner's 2011 Top Technologies

A coworker stumbled across Gartner's top 10 technologies for 2011 and decided to share it with everyone in the office via email. Overlooking the need for a cluebat, and resisting the urge to similarly spam everyone with The Oatmeal's take on email etiquette, I think Gartner missed the mark on some things.

Let's be honest for a moment. Cloud computing has been hyped since '08 when Eucalyptus and Amazon's EC2 Services came out. Social media has been on the radar since since blogs became popular (though admittedly Twitter and Facebook upped the ante). Mobile computing has been slowly making inroads but I think it's still too soon to claim "The PC era is over." All the technologies have been around for years in one form or another; they just happen to be "hot" right now... and by the time someone starts touting them they've probably peaked.

In the next 12 months I predict there'll be a lot of potential for things like IPv4/6 networking, …

"Inchworm on a Stick" in PHP

~- is known as the inchworm on a stick operator in Perl obfuscation circles. It isn't really an operator; it's a term coined to describe negating a value and then taking its compliment, the apparent effect of which is to decrement the value. (To understand why, you need to understand how negative numbers are represented in binary.)

In Perl, ~- works for positive values:

for ($i = 3; $i > -3; $i--) { print ~-$i . "\n"; } $ perl test.pl 2 1 0 4294967295 4294967294 4294967293
Interestingly enough, when the same is tried in PHP the results are slightly different...

2 1 0 -1 -2 -3
PHP treats the value as a signed integer where Perl treats it as an unsigned integer. I don't know which way is "better" or which is "more correct," but it is something I found interesting and I thought would be worth sharing.

8 Tips to Improve Your Golf Game

I wasted more time golfing this week than I should have. No, not real golf... code golf. Trying to write small programs in the least number of keystrokes can be fun, challenging, and sometimes even addicting. It's not about writing pretty code or code that's easily-understandable. It's all about cramming as much code as you can into the least number of characters. While some languages golf better than others, you can still write impressively small code in your language of choice if you're familiar enough with the intricacies of its behavior. Here are 8 tips to improve your golf score when golfing with PHP:

Use short tags.
Using <? instead of <?php and using <?= instead of <?echo will both save you 3 characters.

Avoid initializing variables if possible.
Uninitialized variables assume the value 0, "", or false depending on the context in which they're referenced. $x=0; is 5 characters too much!

Know your function aliases.
A few functions in PHP are…

I Remember...

I remember when Java first came out surfing the Internet on my 28k dial-up connection and hitting a page with a Java applet; either Netscape would come crashing down or my computer would lock up...

I remember schoolmates telling me Java was "the future" because it ran on a virtual machine which meant it was cross platform, and then being ostracized by them when I pointed out that QBasic would be considered cross platform, too...

I remember reading Java programming books before I understood OOP and wondering why I had to write a hundred lines of code just to output "Hello World"...

I remember reading Java programming books after I understood OOP and still wondering why I had to write a hundred lines of code just to output "Hello World"...

I remember trying to convince myself every time I started Eclipse and watched my P4 run slower than a 486 that I just hadn't given Java a fair shake and I needed to embrace it with an open heart and mind...

I remembe…

End of Support isn't the End of the World

The PHP development team released PHP 5.2.14 last week and with it comes the end of active support for the 5.2 branch. A bit of dissent rippled throughout the community... but is it really a big deal? Contrary to popular belief, downloads from php.net don't come with an expiration date.

There is a lot of legacy code running mission-critical applications. These apps work and are stable so the time, effort, and expense required to upgrade them put doing so very low on a companies' priority lists. A few years ago I worked as a System Administrator for a credit union turned bank; the core processing system was written in PL/I and the ATM switching system was written in COBOL. There are probably more applications written in non-OOP PHP 3 code with register globals running atop a Linux 2.4 kernel than any of us want to acknowledge.

But version numbers are just mile-markers that reference a snapshot of the project at a given time. The development team is continually improving PHP so t…

Learning Prolog

I'm not quite sure exactly I was searching for, but somehow I serendipitously stumbled upon the site learnprolognow.org a few months ago. It's the home for an introductory Prolog programming course. Logic programming offers an interesting way to think about your problems; I've been doing so much procedural and object-oriented programming in the past decade that it really took effort to think at a higher level!

I found the most interesting features to be definite clause grammars (DCG), and unification. Difference lists are very powerful and Prolog's DCG syntax makes it easy to work with them. Specifying a grammar such as:
s(s(NP,VP)) --> np(NP,X,Y,subject), vp(VP,X,Y).

np(np(DET,NBAR,PP),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y),
pp(PP).
np(np(DET,NBAR),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y).
np(np(PRO),X,Y,Z) --> pro(PRO,X,Y,Z).

vp(vp(V),X,Y) --> v(V,X,Y).
vp(vp(V,NP),X,Y) --> v(V,X,Y), np(NP,_,_,object).

nbar(nbar(JP),X,3) --> jp(JP,X).

pp(pp(PREP,NP)) --> …

On Unobtrusive JavaScript

Traditionally, unobtrusive JavaScript means the code is kept separate from the page's markup. This separation makes it easier to maintain and reuse the code. However, I view unobtrusive code as more than simple separation. True unobtrusiveness means your JavaScript code will function alongside other code that may be loaded by the browser, and the other code will function alongside yours. Don't pollute the global scope in the execution environment; don't clobber global objects, their properties, or prototypes with your own; and be able to work alongside various frameworks.

Use Discretion when Reviewing Code Metrics

Code metrics are interesting creatures. Some are just raw numbers, such as depth of inheritance or lines of code, while others are a bit more subjective, like a maintainability index. But ultimately they are all meaningless without broader context and an understanding of the code.

As a brief example, consider the following C# function which accepts a string and returns the 40-character hexadecimal representation of the string's SHA1 hash.

public static String Sha1(String text)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
Byte[] textBytes = Encoding.Unicode.GetBytes(text);
Byte[] hashBytes = sha1.ComputeHash(textBytes);
return Convert.ToBase64String(hashBytes);
}
}The function accomplishes one task. Variables are defined closest to their usage. Function calls are clear and do not nest other function calls. Even using ( ) is used so the run-time can automatically dispose of the SHA1Managed resource. Yet a scan using Visual Studio 2010's Code Me…

Signing Assemblies with a Strong Name

Code Analysis/FXCop warned me that my credit card application was not signed with a Strong Name, which would make it more difficult to determine if the assemblies had been tampered with. For more information on Strong Names and why they're a good thing, see this Tech Republic article.

you first need a cryptographic key before you can sign an assembly. The key is created using the sn.exe tool provided by the Windows SDK.
sn.exe -k sgKey.snk
I added my sgKey.snk file to my project in Visual Studio, and then in the Application's properties I went to the Signing tab, checked the "Sign the assembly" box, and specified my key file.

I had forgotten that I used a 3rd party library to manage logging the user out after a configurable period of inactivity and their assembly was not signed. You can't sign an assembly unless all of its dependencies are signed as well, which makes sense. You need to replace the unsigned assemblies with signed ones first.
If you can compile the 3rd …

Code Analysis in Visual Studio

Continuing to play around with Visual Studio 2010 Ultimate, I ran the Code Analysis tool on some code I had written for a customer-- a desktop-based application which securely stores credit card information using hardware identifiers as portions of the encryption key. I started with over 300 warnings and have now worked them down to around 120 warnings or so. Those that remain are Globalization related, which I'm not concerned about since it was a one-off project that is unlikely to be internationalized. FxCop, the utility which Code Analysis is based on, is freely available online.

Visual Studio 2010 Released

If you haven't heard the news already (which I hadn't because I typically don't keep up with such things), Visual Studio 2010 came out earlier this month. I've been playing around with Visual Studio 2010 Ultimate (a 90-day trial version is available) and I must say I'm impressed. Microsoft has finally added common features like block editing and text-zoom, an Extension Manager to extend the IDE à la Eclipse, and support for jQuery. If I were a Fortune 500 company hacking out Windows code all day I could justify a couple of licenses if it really helped my developers efficiently produce a more secure and stable application, but the price tag puts it far out of reach for my needs. I'll stick with either VS2005 or C# Express 2010.

I'll probably post a few follow-up entries as I explore more throughout the next 90 days, so be sure to keep an eye out!

Null Pointer Exception

This is why I don't program in Java:
import java.util.ArrayList;

class Program
{
class Person
{
public Person partner;
}

class Prostitute extends Person { }
class Eunuch extends Person { }

private Prostitute prostitute;
private Eunuch eunuch;

public static void main(String[] args) {
Program p = new Program();
p.run();
}

public void run() {
eunuch.partner = prostitute;
}
}

> Exception in thread "main" java.lang.NullPointerException
But if you do, you should check out the nifty online JXXX Compiler Service.

When Will We Ever Use This?

My sister's boyfriend showed me a nifty chart which presents the size of by distance from a television before your eyes begin to notice the difference of 1080p resolution. Just out of curiosity, we measured the length of my living room and looked at the chart to see how large of a television I would need. The distance between my couch and television is a bit shy of 20ft... off the chart!

The chart goes up to 130 inches, or approximately 11 feet. But an 11 ft diagonal measurement doesn't really mean anything to me other than "big ass TV"*, so I decided to dig out my high school math skills to help me put it into perspective. Assuming a standard 16:9 wide screen display and some liberal number rounding:I would need a television that's almost 6 ft tall, and 10 ft wide if I wanted to see Jay Leno's crow's-feet in high definition!

I only have 8 ft ceilings so that gives 2 ft of clearance above it, and the room is 16 ft wide so I'd have 3 ft of clearance on …

Writing a URI Regular Expression

A friend of mine was tasked with writing a regular expression that could recognize a Uniform Resource Identifier (URI) and break apart its primary components. Not a terribly difficult task since there are a lot of sample regexs one can just pluck from the Internet. But he asked my opinion and I deferred to RFC 3986 which outlines the generic syntax for URIs.

The RFC provides this example expression:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?Personally though I think that's rather sloppy. Were I to write the expression from scratch myself then I'd probably be more verbose and restrictive; I'd expressly match patterns specified in the RFC's ABNF. For example, the RFC defines the scheme portion of a URI as:
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )The portion ^([^:/?#]+): will match characters that are not lexically permitted, such as an underscore or percent-sign. Assuming the i (case-insensitive matching) modifier is u…

PHP and SQLite2 on CentOS

I'm changing shared hosting providers for my websites and the sites I manage for clients as Salt City Tech. Most of the sites are basic websites powered by PHP, share a common code base, and store data in MySQL databases. But I've also been taking advantage of the situation to transition the sites from MySQL to SQLite. There are a lot of things that annoy me about SQLite (such as allowing NULLs in primary-key columns, ignoring foreign key constrains, and incomplete ALTER TABLE support) and a few things that I think are pretty awesome (such as user-defined functions in PHP). Pragmatically speaking, SQLite will be more convenient for deployment to and backup from the shared hosting environment and the sites' simple storage requirements fall exactly in SQLite's sweet-spot.

The transition hasn't been terribly difficult... the biggest obstacle has been configuring a development environment that adequately mirrored the shared hosting deployment environment. I happened to …

Happy 2010!

Happy New Year! I hope everyone has had a rewarding holiday and will have a prosperous new year! Last year I tentatively designated 2009 as my "Year of Balance." I wanted to make a concerted effort to focus more on what's really important in life. With a busy full-time job, a death in the family, juggling several side-projects, and buying a house this year (2009 was probably my "Year of Expense" in retrospect with the new house and all the joys that come with home ownership)... my head would probably have exploded had I not been making that effort. I'm not sure what my theme for 2010 will be, but I'll still be doing my best live, laugh, and love as much as I can and I hope you will be to!