Skip to main content

Posts

Showing posts from 2011

Dio, Iun Novan Bonvolu Doni al Mi!

Tradukita de Please God, Give Me Something New! . Koran dankon al Jon Z kaj 黄鸡蛋/Ĉitano pro ilia kontrolado. “Jen... rigardu ĉi tiun <ligilon>. Tamen, vi devas uzi la plej freŝan version de Chrome.” Aĉ! Ĉu ni ne jam spertis tion? 15 jaroj pasis, kaj nun ni reiras rekte al la sama loko, kie ni ekiris… “Plej bone aspekta pere de .” Estas vera domaĝo. Ne miskomprenu min. Jaroj da laboro por normigi HTML, JavaScript, la DOM, CSS, ktp klarigis multajn malklaraĵojn, kaj tio ja estis necesa. Sed striktaj reguloj ankaŭ sufokas kreadon. Ĉar HTML5 kaj ĝiaj amikoj forigis kelkajn el la limigoj, la pendolo svingiĝi antaŭen. Homoj ekkreas denove. Sed, nun kontraŭas Firefox kaj Chrome anstataŭ Internet Explorer kaj Netscape. Tamen, estas sistema problemo preter la “foliumiloj militoj.” Ĉu vi memoras AOL? Facebook nun klopodas esti “La Interreto.” Ĉu vi memoras komputilegojn kaj verd-ekrajnojn? Ni puŝis ĉion al la komputila labortablo, kaj nun puŝas ĉion reen “al La Nubo.” Ĉiuj el la kvara k...

Please God, Give Me Something New!

"Here... check out this (link). But you have to use the most recent version of Chrome." Sigh. Haven't we been through this already? 15 years have passed and we're headed right back to the same place we started... "Best viewed in <someone's favorite browser>." It's sad, really. Don't get me wrong. Years of standardization work on HTML, JavaScript, the DOM, CSS, etc. cleaned up a lot of messy lose ends and yes it was indeed necessary, but stringent standardization also stifles creativity. And now that HTML5 and friends have loosened some of the restrictions the pendulum has started to swing back in the opposite direction. People have started to innovate again. This time around it's Firefox vs Chrome instead of Internet Explorer vs Netscape. There's a systemic problem that goes beyond browser wars, however. Remember AOL? This time it's Facebook trying to be “The Internet.” Remember mainframes and terminals? After pushing everyt...

Top-10 PHP String Functions

By day I work as a programmer at ShoreGroup, Inc . By night I'm a freelance developer and now the managing editor for SitePoint 's latest site, PHPMaster.com . Helping out with the site has been pretty fun so far; my Australian counterparts are all pretty cool, and I've met some really great new authors too. If you haven't visited yet, take a moment and check out PHPMaster.com (there's still some wrinkles to iron out on the site, but we're working to identify and fix them all as soon as we can). Part of my duties as a managing editor include working with authors to make sure the site's content is well balanced. PHPMaster.com is targeting PHP programmers of all skill levels, so there should be a good mix of basic, beginner, intermediate, and advanced content. Planning for a beginner article that demonstrates basic string handling functions, I wondered which function to highlight. I wanted to show ones that would be most relevant, not necessarily ones that we...

Avoid Fetch-Object Abuse

Lately I'm finding a lot of instances of the mysql_fetch_object() function being used in a particular codebase I help maintain. Unfortunately, I've yet to see it used correctly. It always seems to be used to retrieve a stdClass object from a query result where mysql_fetch_array() or mysql_fetch_assoc() would be the more appropriate choice. $row = mysql_fetch_object($result); $kitten = new Kitten(); $kitten->setName($row->name); $kitten->setColor($row->color); ... Put aside the argument that the code should be using PDO or the MySQLi extension instead of the legacy MySQL extension. mysqli_result::fetch_object() and PDOStatement::fetchObject() have the same potential for abuse. The above code is wrong because the returned result is an object but treated like it's an array. The mysql_fetch_array() and mysql_fetch_assoc() functions are used to retrieve a row from the query's result set. I prefer to use mysql_fetch_assoc() so I can access the values...

Smalltalk Challenge: Post 10 - Conclusions

So here I am, more than 20 hours with Smalltalk and 10 blog posts about my experiences as required by the terms of my challenge . Josh said he chose Smalltalk for me because of the language's history of helping giving rise to object-oriented programming, which he thinks I hate. (For the record I don't hate OO; I hate the awkwardness and complexity its over-zealous application inflicts.) But I think secretly he was hoping it would endear me to Java in the same way as I was hoping OCaml would help him see past Java. Smalltalk gave me a newfound respect, not for OO, but for the language's innovations and lasting influence. If anything in relation to current-day OO practices, my experience confirmed how botched OO adoption has been given what it was intended to be. Regardless, while I don't think I'll be using Smalltalk in the foreseeable future, it was definitely fun to explore and gave me a lot of things to think about. Smalltalk isn't a popular "mainstream...

Smalltalk Challenge: Post 9 - Koans

Besides tinkering with turtles and hashes in Squeak, I secretly went back to GNU Smalltalk and went through some of the Smalltalk Koans . Sssh... don't tell Josh! Programming koans are a series of failing unit tests that a student reads through and corrects. Each test demonstrates a particular concept in the language. They can be a fun way to review one's understanding of a language, and occasionally learn something new. Here's an of a koan: testSingleCharacterFromString [ | string | string := 'Smalltalk'. self expect: (self fillMeIn) toEqual: (string at: 1). self expect: (self fillMeIn) toEqual: (string at: 6). ] When the test suite is run, it displays: Do not lose hope. Expected value should equal actual value. Expected : FILL ME IN Actual : $S (an instance of Character) TestString#testSingleCharacterFromString has damaged your karma (in src/koans/TestString.st) The name of the method indicates it is possible access the characters that ...

Smalltalk Challenge: Post 8 - Virtual Images

Virtualization is in vogue right now as companies use such technology to run multiple systems on consolidated hardware. Remember, Smalltalk was designed as a language and an environment. No one is about to replace Windows (or Ubuntu, though I'm tempted) with Smalltalk as their operating system, so it makes sense for it to be implemented as a virtual machine. Similar to products like VMWare Workstation or VirtualBox, most Smalltalk implementations consist of a Virtual machine (VM) application and an image file. The image file contains the definition and state of the Smalltalk environment which is realized by the VM. It may be helpful to think about the image file as a program saved somewhere on your computer's hard drive, and the VM is your computer's processor that executes the code to do something useful. A Squeak installation consists of four files: a VM executable and three files that make up the image. The VM is the interpretor that "runs" a Smalltalk im...

Smalltalk Challenge: Post 7 - Turtles Ahoy!

I can remember going down to the computer lab while in grade school and using Logo on the then state-of-the-art Apple IIe computers. Supposedly Logo allowed students to explore mathematics in a tangible way, but I don't remember doing much more than drawing shapes by moving the little "turtle" around on the green screen and I still don't have much confidence in my math skills 20 years later. I don't think Logo helped kindle my interest in computers, either; games like The Oregon Trail and Where in the World is Carmen Sandiego and the Commodore 64 computer were far more influential to me. But drawing little green triangles and squares was fun. And while Logo may not have been as influential in my education as Papert would have hoped, it was extremely influential to Smalltalk. In fact, the graphics Pen object is actually very similar to Logo's turtle. The Pen class is used for drawing. It inherits from BitBlt which allows it to perform raster drawing on a...

Smalltalk Challenge: Post 6 - Morphic

As the Dynabook/Smalltalk environment was the first to introduce the windowed user interface, it's no surprise that the Model View Controller (MVC) pattern also made its first appearance in Smalltalk. In Smalltalk, the term "MVC" refers to both the architecture pattern that separates code responsibilities into model, view, and controller objects, and the user interface framework used to develop visual and interactive elements. The MVC framework manages objects in the environment using the MVC pattern. Model objects are responsible for maintaining the behavior and state of the element. View objects are responsible for the representation or appearance of the element within the world. Controller objects are responsible for accepting user input and passing messages to the model and view objects. But because of the complexity and limitations of the MVC architecture, Squeak has replaced the MVC framework with Morphic, a direct-manipulation user interface toolkit. Unlike MVC...

Smalltalk Challenge: Post 5 - Talking to Objects

Everything I've read about Smalltalk makes an effort to stress objects are capable of doing three things: maintaining state, receiving messages, and sending messages. The understanding that an object can maintains its own state is common across many languages, but message passing may be unfamiliar to programmers working with other languages (though message passing does play an important role in Objective-C). Alan Kay has said that message passing is the most important concept to understand in Smalltalk, and that objects have been over-emphasized. Smalltalk's object model follows the classical (class-based) style; the programmer writes a class which is then used by the runtime as a blueprint for instantiating an object. But unlike C++ or Java, the programmer never works with objects by invoking their methods directly in Smalltalk. Instead, messages are sent to the object which receives a message, looks up the appropriate method to perform, and then executes the method. This i...

Smalltalk Challenge: Post 4 - Porting the Kember Identity

There are a few things I find myself tripping up over even after spending some time writing "meaningful" Smalltalk code, like using single quotes to delimit strings (double quotes are used for comments) and remembering the order in which different messages are sent, but the more code I write the easier it is to remember such things. After only a few hours, Smalltalk is still something new and unfamiliar. The first programs I wrote when looking into Go were solutions to the first two Project Euler problems and a port of the Kember Identity search program. I decided to skip the Euler problems this time and go straight to the Kember Identity port. The Kember program ultimately boils down to generating and checking MD5 hashes. I didn't find any helpful cryptography related objects or methods in the default image, so I searched Google and eventually found Ron Teitelbaum's Cryptography/Team package . Squeak uses a package management system called Monticello to load ...

Smalltalk Challenge: Post 3 - Awkward

After spending a short time in the Smalltalk (Squeak) environment, it's easy to understand how other existing languages at the time were not suited for realizing the full potential of the Dynabook. Working in a visual environment is a far-cry from working at a mainframe terminal. It's ironic though that some of the same issues that plague OO now are the same that held Smalltalk back in the 80's... it consumed a substantial amount of memory and the performance was not always optimal . For me, one of the issues is the awkwardness of Smalltalk's "everything is an object" philosophy. I believe the "everything is a ___" mindset causes problems, regardless of what fills in the blank. In TCL, everything is a string. In LISP, everything is a list. In Smalltalk, everything is an object. The fact of the matter is not everything in the world is homogeneous. Some things are objects, others are numbers, and yet others are actions. Forcing everything into the sa...

Smalltalk Challenge: Post 2 - Switching to Squeak

A quick survey of Smalltalk's keywords, constructs, and syntax isn't enough to understand how the language approaches programming. There is only a handful of keywords, no control structures, and the syntax is quirky in spots but is hardly exotic. To really get an appreciation, it's helpful to place the language in its historical context. Smalltalk wasn't intended to be a general purpose systems programming language like C, rather it was designed to allow ordinary people to take full advantage of their computers and to be easy enough for children to learn. The intended environment was immersive, interactive, and most-importantly visual. Smalltalk was more than a programming language, it was an entire operating environment. Xerox was working on the Dynabook at its Palo Alto Research Center in the early 1970's. The Dynabook was to have many features we now see in personal laptops and tablet devices (such as touch screens, mice, windowed display managers, etc.). Alan ...

Smalltalk Challenge: Post 1 - Installing GNU Smalltalk

That's right... I'm the one who challenged my coworker Josh to open his mind beyond Java by spending time with a new language and blogging about it. l At first I challenged him to learn Oz , a language that combines the imperative, object-oriented, functional, logic, constraint, distributed, and concurrent programming paradigms (whew!). Unfortunately, apparently the 64-bit version of Mozart on Gentoo is broken at the moment and he didn't want to, as he put it, "build random shit on his box." So I proposed OCaml as an alternative. While it may not combine seven programming paradigms, I'm positive functional programming will be enough to show him there's more to life than what Java offers. In return, for him to accept my challenge I had to agree to spend some time learning a language of his choosing too, and he set the number of required blog posts to 10. That's not too bad in my opinion since I enjoy looking at different programming languages anyway...

Reading Unicode (UTF-8) in C

In working on scanner code for Kiwi I did a bit of reading up on Unicode . It's not really as difficult as one might think parsing UTF-8 character by character in C. In the end I opted to use ICU so I could take advantage of its character class functions instead of rolling my own, but the by-hand method I thought was still worth sharing. Functions like getc() read in a byte from an input stream. ASCII was the predominant encoding scheme and encoded characters in 7-8 bits, so reading a byte was effectively the same as reading a character. But you can only represent 255 characters using 8 bits, far too little to represent all the characters of the world's languages. The most common Unicode scheme is UTF-8 , is a multi-byte encoding scheme capable of representing over 2 million characters using 4 bytes or less. The 128 characters of 7-bit ASCII encoding scheme are encoded the same, the most-significant bit is always 0. Other characters can be encoded as multiple bytes but th...

Lazy Fibonacci Array

What’s the 1,337th number in the Fibonacci sequence? It’s 1.1667830241021E+279, of course! Here’s an cool snippet of PHP code I wrote several months ago which implements not only PHP’s Iterator interface to provide an lazily-iterable list of Fibonacci numbers, but also the ArrayAccess interface and some fancy math to provide indexed access, too. Lazy evaluation is pretty cool because it saves memory. In this case, in effect you have an array of 1,478 of elements (bound only by the capacity of float values) while only using 984 bytes of memory for the object: <?php class Fibonacci implements Iterator, ArrayAccess { const PHI = 1.618033989; private $a; private $b; private $i; public function __construct() { } public function rewind() { $this->a = 1; $this->b = 0; $this->i = 0; } public function current() { return $this->b; } public function key() { return $this->i; } pu...

OO in Language Design

If you were to create a new programming language, and you wanted to support object oriented programming with it, what would it look like? An object is a set of instance data and various functions that work with it. In Java, they're specified by first grouping the variables and functions together in a class, and then creating an instance from the class definition. In JavaScript, functions are dynamically attached to the instance data (or it's prototype). This is an intentional over-simplification but does highlight the fact that different programming languages approach working with objects differently. I've been thinking about objects and working with structured code in relation to Kiwi and it depresses me how much the object oriented school of thought that started with C++ and came to fruition in Java has influenced our industry. Of course there are the so-called five concepts of object oriented design , which says a design that meets the following criteria is considere...

Spaghetti Code Considered Harmful

To chefs and epicureans, spaghetti is a good thing-- it's inexpensive, easy to make, and very versatile. But spaghetti isn't so appetizing to a programmer. The phrase "spaghetti code" is an all-too-common pejorative we programmers use to describe horrible code, whether it's difficult to understand, poorly organized, or just plain long-winded. And there-in lays the problem. What really constitutes spaghetti code is subjective; I've yet to hear a concrete definition or standard metric that measures it. I've seen PHP code that amounts to nothing more than a giant switch construct... a hundred lines here to handle this condition over here, another hundred or so lines in the branch for that condition over there, maybe a dozen conditions... you get the idea. But such code isn't necessarily spaghetti. What's wrong with it is not that it's unreadable, I would argue, but rather there is a lack of encapsulation. There's a greater chance of inadver...

Resuming scp

I was transferring a file from one system to another at work with scp when the connection dropped. It was a substantially sized file and I didn't want to start the transfer over again, but unfortunately scp doesn't support resume. That's when I remembered rsync. With rsync I was able to continue the transfer where it left off, and afterward I had the idea to set the following alias in my .bashrc file. alias scp='rsync -vPe ssh' Now when I transfer files with scp, I'm really using rsync and I don't have to worry about flaky network drops.

Creepy JavaScript Tracking

I recently began allergy shots so my new Monday morning routine includes me sitting in a doctor's office for 30 minutes (I must wait after receiving the shots and be checked by a nurse to make sure there was no reaction). With nothing else better to do while I waited last week, I started playing around with some JavaScript. This is what I came up with: <html> <head> <title>Test</title> <script type="text/javascript"> window.onload = function () { var mX = 0,  mY = 0, sX = 0,  sY = 0, queue = [], interval = 200, recIntv = null, playIntv = null, b = document.body, de = document.documentElement, cursor = document.getElementById("cursor"), record = document.getElementById("record"), play = document.getElementById("play"); window.onmousemove = function (e) { e = e || window.event; if (e.pageX || e.pageY) { ...

Geolocation Search

Services that allow users to identify nearby points of interest continue to grow in popularity. I'm sure we're all familiar with social websites that let you search for the profiles of people near a postal code, or mobile applications that use geolocation to identify Thai restaurants within walking distance. It's surprisingly simple to implement such functionality, and in this post I will discuss how to do so. The first step is to obtain the latitude and longitude coordinates of any locations you want to make searchable. In the restaurant scenario, you'd want the latitude and longitude of each eatery. In the social website scenario, you'd want to obtain a list of postal codes with their centroid latitude and longitude. In general, postal code-based geolocation is a bad idea; their boundaries rarely form simple polygons, the area they cover vary in size, and are subject to change based on the whims of the postal service. But many times we find ourselves stuck on ...