diff --git a/Makefile b/Makefile index 05bbcb9..4770350 100644 --- a/Makefile +++ b/Makefile @@ -1,56 +1,21 @@ -JAVASCRIPTS=$(shell echo assets/js/*.js) -STYLESHEETS=$(shell echo assets/css/*.css) -POSTS=$(shell echo _blog/published/*.html) $(shell echo _blog/published/*.md) +JSON=harp.json $(shell echo public/*.json) $(shell echo public/*/*.json) +EJS=$(shell echo public/*.ejs) $(shell echo public/*/*.ejs) +JAVASCRIPTS=$(shell echo public/js/*.js) +STYLESHEETS=$(shell echo public/css/*.css) +POSTS=$(shell echo public/posts/*.html) $(shell echo public/posts/*.md) -all: proj blog combine +all: compile -proj: projects.json templates/proj/index.html templates/proj/project.html +compile: posts @echo - ./bin/projects.js projects.json public/proj + ./bin/compile.sh -blog: _blog/blog.json templates/blog/index.html templates/blog/post.html $(POSTS) +posts: $(POSTS) @echo - cd _blog && git pull - ./bin/blog.rb _blog public + ./bin/posts.rb public public -minify: $(JAVASCRIPTS) $(STYLESHEETS) +publish: compile @echo - ./bin/minify.sh + ./bin/publish.sh --delete public/ -combine: minify $(JAVASCRIPTS) $(STYLESHEETS) - @echo - ./bin/combine.sh - -publish_assets: combine - @echo - ./bin/publish.sh --delete public/css public/images public/js - ./bin/publish.sh public/f - -publish_blog: blog publish_assets - @echo - ./bin/publish.sh --delete public/blog - scp public/blog/posts.json bohodev.net:discussd/posts.json - scp discussd/discussd.js bohodev.net:discussd/discussd.js - scp public/s42/.htaccess samhuri.net:s42.ca/.htaccess - ssh bohodev.net bin/restart-discussd.sh - -publish_proj: proj publish_assets - @echo - ./bin/publish.sh --delete public/proj - -publish_index: public/index.html - @echo - ./bin/publish.sh public/index.html - -publish: publish_index publish_blog publish_proj - @echo - ./bin/publish.sh public/.htaccess - ./bin/publish.sh public/favicon.ico - -clean: - rm -rf public/proj/* - rm -rf public/blog/* - rm public/css/*.css - rm public/js/*.js - -.PHONY: proj blog +.PHONY: publish diff --git a/TODO b/TODO deleted file mode 100644 index 4b7bc1e..0000000 --- a/TODO +++ /dev/null @@ -1,6 +0,0 @@ -TODO -==== - - * remove comments - - * use harp diff --git a/assets/css/blog.css b/assets/css/blog.css deleted file mode 100644 index a8fa07c..0000000 --- a/assets/css/blog.css +++ /dev/null @@ -1,179 +0,0 @@ -body { margin: 0 - ; padding: 0 - } - -h1 { margin: 0 - ; padding: 0.2em - ; color: #9ab - } - -.center { text-align: center - ; font-size: 1.2em - } - -.hidden { display: none } - -#index { width: 80% - ; min-width: 300px - ; max-width: 800px - ; border: solid 1px #999 - ; -moz-border-radius: 10px - ; -webkit-border-radius: 10px - ; border-radius: 10px - ; background-color: #eee - ; margin: 1em auto - ; padding: 1em - ; font-size: 1.2em - ; line-height: 1.5em - ; list-style-type: none - } - -.date { float: right } - -#article, -article { width: 80% - ; min-width: 400px - ; max-width: 800px - ; margin: 0.6em auto - ; font-size: 1.2em - ; line-height: 1.4em - ; color: #222 - } - -#article h1, -article h1 { text-align: left - ; font-size: 2em - ; line-height: 1.2em - ; font-weight: normal - ; color: #222 - ; margin: 0 - ; padding-left: 0 - } - -#article h1 a, -article h1 a { color: #222 - ; text-decoration: underline - ; border-bottom: none - ; text-shadow: #ccc 1px 1px 5px - ; -webkit-transition: text-shadow 0.4s ease-in - } - -#article h1 a:hover, -article h1 a:hover { text-shadow: 1px 1px 6px #ffc - ; color: #000 - } - -#article h2, -article h2 { font-size: 1.8em - ; font-weight: normal - ; text-align: left - ; margin: 1em 0 - ; padding: 0 - ; color: #222 - } - -#article h3, -article h3 { font-size: 1.6em - ; font-weight: normal - } - -.time, -time { color: #444 - ; font-size: 1.2em - } - -.permalink { font-size: 1em } - -.gist { font-size: 0.8em } - -/* show discussion */ -#sd-container { margin: 3em 0 } - -input[type=submit], -#sd { border: solid 1px #999 - ; border-right-color: #333 - ; border-bottom-color: #333 - ; padding: 0.4em 1em - ; color: #444 - ; background-color: #ececec - ; -moz-border-radius: 5px - ; -webkit-border-radius: 5px - ; border-radius: 5px - ; text-decoration: none - ; margin: 0 2px 2px 0 - } - -input[type=submit]:active, -#sd:active { margin: 2px 0 0 2px - ; color: #000 - ; background-color: #ffc - } - -#comment-stuff { display: none - ; color: #efefef - ; margin: 0 - ; padding: 2em 0 - } - -#comments-spinner { text-align: center } - -#comments { width: 70% - ; max-width: 600px - ; margin: 0 auto - } - -.comment { color: #555 - ; border-top: solid 2px #ccc - ; padding-bottom: 2em - ; margin-bottom: 2em - } - -.comment big { font-size: 2em - ; font-family: Verdana, sans-serif - } - -#comment-form { width: 400px - ; margin: 2em auto 0 - } - -input[type=text], -textarea { font-size: 1.4em - ; color: #333 - ; width: 100% - ; padding: 0.2em - ; border: solid 1px #999 - ; -moz-border-radius: 5px - ; -webkit-border-radius: 5px - ; border-radius: 5px - ; font-family: verdana, sans-serif - } - -input:focus[type=text], -textarea:focus { border: solid 1px #333 } - -textarea { height: 100px } - -input[type=submit] { font-size: 1.1em - ; cursor: pointer - } - -pre { background-color: #eeeef3 - ; margin: 0.5em 1em 1em - ; padding: 0.5em - ; border: dashed 1px #ccc - } - -footer { margin: 0 auto - ; padding: 0.2em 0 - ; border-top: solid 1px #ddd - ; clear: both - ; width: 80% - } - -footer p { margin: 0.5em } - -footer a { border-bottom: none - ; color: #25c - ; font-size: 1.2em - ; text-decoration: none - } diff --git a/assets/css/ie6.css b/assets/css/ie6.css deleted file mode 100644 index dc74a5d..0000000 --- a/assets/css/ie6.css +++ /dev/null @@ -1,7 +0,0 @@ -ul { behavior: none - ; padding-bottom: 25px - } - -img { behavior: url(../js/iepngfix.htc) - ; behavior: url(../../js/iepngfix.htc) - } diff --git a/assets/css/ie7.css b/assets/css/ie7.css deleted file mode 100644 index c2a3ff0..0000000 --- a/assets/css/ie7.css +++ /dev/null @@ -1 +0,0 @@ -ul#projects li { list-style-type: none } diff --git a/assets/css/mobile.css b/assets/css/mobile.css deleted file mode 100644 index 15e7b92..0000000 --- a/assets/css/mobile.css +++ /dev/null @@ -1,140 +0,0 @@ -/* phones and iPad */ - -@media only screen and (orientation: portrait) and (min-device-width: 768px) and (max-device-width: 1024px), - only screen and (min-device-width: 320px) and (max-device-width: 480px), - only screen and (max-device-width: 800px) -{ - ul.nav { padding: 0.5em - ; width: 60% - ; max-width: 600px - } - - ul.nav li { display: block - ; font-size: 1.5em - ; line-height: 1.8em - } - - ul.nav li:after { content: '' } -} - -/* phones */ -@media only screen and (min-device-width: 320px) and (max-device-width: 480px), - handheld and (max-device-width: 800px) -{ - /* common */ - - h1 { font-size: 2em - ; margin-top: 0.5em - } - h2 { font-size: 1.3em; line-height: 1.2em } - - .navbar { font-size: 0.9em } - .navbar { width: 32% } - #breadcrumbs { margin-left: 5px } - - #show-posts { margin-top: 1em - ; font-size: 0.8em - } - - #forkme { display: none } - - ul.nav { width: 80% } - - ul.nav li { font-size: 1.4em - ; line-height: 1.6em - } - - td { font-size: 1em - ; line-height: 1.1em - } - - #blog img { max-width: 100% } - - #index { width: 90% - ; min-width: 200px - ; margin: 0.3em auto 1em - ; padding: 0.5em - ; font-size: 1em - } - - #index li > span.date { display: block - ; float: none - ; color: #666 - ; font-size: 0.8em - } - - #blog #article h1, - #blog article h1 { font-size: 1.6em - ; line-height: 1.2em - ; margin-top: 0 - } - - #blog article h2 { font-size: 1.4em } - - #article, - article { min-width: 310px - ; margin: 0 - ; padding: 0.6em 0.4em - ; font-size: 0.8em - } - - .time, - time { font-size: 1.0em } - - pre, .gist { font-size: 0.8em } - - #comment-stuff { padding: 0 - ; margin-top: 2em - } - - #comments { width: 100% } - - #comment-form { width: 90% - ; margin: 0 auto - } - - input[type=text], - textarea { font-size: 1.2em - ; width: 95% - } - - input[type=submit] { font-size: 1em } - - /* proj */ - #info { width: 70% - ; padding: 0 1em - } - - #info > div { clear: left - ; width: 100% - ; max-width: 100% - ; padding: 0.5em 0.2em 1em - ; border-left: none - ; font-size: 1em - } - - #stats { font-size: 1em; margin-bottom: 0.5em } - - footer { margin: 0 - ; padding: 0.5em 0 - ; font-size: 1em - ; width: 100% - } - -} - -/* landscape */ - -@media only screen and (orientation: landscape) and (min-device-width: 768px) and (max-device-width: 1024px), - only screen and (orientation: landscape) and (min-device-width: 320px) and (max-device-width: 480px), - handheld and (orientation: landscape) and (max-device-width: 800px) -{ - body { font-size: 0.8em } -} - - -/* iPad portrait */ -@media only screen and (orientation: portrait) and (min-device-width: 768px) and (max-device-width: 1024px) -{ - article > header > h1 { font-size: 1.8em } -} diff --git a/assets/css/proj-common.css b/assets/css/proj-common.css deleted file mode 100644 index 912f347..0000000 --- a/assets/css/proj-common.css +++ /dev/null @@ -1,7 +0,0 @@ -td { font-size: 1.5em - ; line-height: 1.6em - } - -td:nth-child(2) { padding: 0 10px } - -.highlight { font-size: 1.2em } diff --git a/assets/css/proj.css b/assets/css/proj.css deleted file mode 100644 index ce0fd0f..0000000 --- a/assets/css/proj.css +++ /dev/null @@ -1,43 +0,0 @@ -#stats a { text-decoration: none } - -#info { text-align: center - ; margin: 1em auto - ; padding: 1em - ; border: solid 1px #ccc - ; width: 90% - ; max-width: 950px - ; background-color: #fff - ; -moz-border-radius: 20px - ; -webkit-border-radius: 20px - ; border-radius: 20px - ; behavior: url(../js/border-radius.htc) - ; behavior: url(../../js/border-radius.htc) - } - -h4 { margin: 0.5em 0 0.7em } - -#info > div { text-align: center - ; font-size: 1.3em - ; width: 31% - ; max-width: 400px - ; float: left - ; display: inline - ; padding: 0.5em 0.2em - ; border-left: dashed 1px #aaa - } - -#info > div:first-child { border-left: none } - -#info ul { list-style-type: none - ; text-align: center - ; padding: 0 - ; margin: 0 - } - -#info li { padding: 0.2em 0 - ; margin: 0 - } - -#info > br.clear { clear: both } - -#contributors-box a { line-height: 1.8em } diff --git a/assets/css/style.css b/assets/css/style.css deleted file mode 100644 index 3ee955a..0000000 --- a/assets/css/style.css +++ /dev/null @@ -1,90 +0,0 @@ -body { background-color: #f7f7f7 - ; color: #222 - ; font-family: 'Helvetica Neue', Verdana, sans-serif - } - -h1 { text-align: center - ; font-size: 2em - ; font-weight: normal - ; margin: 0.8em 0 0.4em - ; padding: 0 - } - -h2 { text-align: center - ; font-size: 1.7em - ; line-height: 1.1em - ; font-weight: normal - ; margin: 0.2em 0 1em - ; padding: 0 - } - -a { color: #0E539C } - -a.img { border: none } - -.navbar { display: inline-block - ; width: 33% - ; font-size: 1.5em - ; line-height: 1.8em - ; margin: 0 - ; padding: 0 - } - -.navbar a { text-shadow: none } - -#breadcrumbs a { color: #222 } -#title { text-align: center } -#archive { text-align: right } - -#forkme { position: absolute - ; top: 0 - ; right: 0 - ; border: none - } - -ul.nav { text-align: center - ; max-width: 400px - ; margin: 0 auto - ; padding: 1em - ; border: solid 1px #ccc - ; background-color: #fff - ; -moz-border-radius: 20px - ; -webkit-border-radius: 20px - ; border-radius: 20px - ; behavior: url(js/border-radius.htc) - ; behavior: url(../js/border-radius.htc) - } - -ul.nav li { display: block - ; font-size: 1.6em - ; line-height: 1.8em - ; margin: 0 - ; padding: 0 - } - -ul.nav li a { padding: 5px - ; text-decoration: none - ; border-bottom: solid 1px #fff - ; text-shadow: #ccc 2px 2px 3px - } -ul.nav li a:visited { color: #227 } - -ul.nav li a:hover, -ul.nav li a:active { text-shadow: #cca 2px 2px 3px - ; border-bottom: solid 1px #aaa - } - -ul.nav li a:active { text-shadow: none } - -footer { text-align: center - ; font-size: 1.2em - ; margin: 1em - } - -footer a { border-bottom: none } - -#promote-js { margin-top: 3em - ; text-align: center - } - -#promote-js img { border: none } diff --git a/assets/js/blog.js b/assets/js/blog.js deleted file mode 100644 index 6dca9a8..0000000 --- a/assets/js/blog.js +++ /dev/null @@ -1,133 +0,0 @@ -;(function() { - if (typeof console === 'undefined') - window.console = {} - if (typeof console.log !== 'function') - window.console.log = function(){} - if (typeof console.dir !== 'function') - window.console.dir = function(){} - - var server = 'http://bohodev.net:8000/' - , getCommentsURL = function(post) { return server + 'comments/' + post } - , postCommentURL = function() { return server + 'comment' } - , countCommentsURL = function(post) { return server + 'count/' + post } - - function getComments(cb) { - SJS.request({uri: getCommentsURL(SJS.filename)}, function(err, request, body) { - if (err) { - if (typeof cb === 'function') cb(err) - return - } - var data - , comments - , h = '' - try { - data = JSON.parse(body) - } - catch (e) { - console.log('not json -> ' + body) - return - } - comments = data.comments - if (comments && comments.length) { - h = data.comments.map(function(c) { - return tmpl('comment_tmpl', c) - }).join('') - $('#comments').html(h) - } - if (typeof cb === 'function') cb() - }) - } - - function showComments(cb) { - $('#sd-container').remove() - getComments(function(err) { - $('#comments-spinner').hide() - if (err) { - $('#comments').text('derp') - if (typeof cb === 'function') cb(err) - } - else { - $('#comment-stuff').slideDown(1.5, function() { - if (typeof cb === 'function') cb() - else this.scrollIntoView(true) - }) - } - }) - } - - jQuery(function($) { - - $('#need-js').remove() - - SJS.request({uri: countCommentsURL(SJS.filename)}, function(err, request, body) { - if (err) return - var data - , n - try { - data = JSON.parse(body) - } - catch (e) { - console.log('not json -> ' + body) - return - } - n = data.count - $('#sd').text(n > 0 ? 'show the discussion (' + n + ')' : 'start the discussion') - }) - - // jump to comment if linked directly - var hash = window.location.hash || '' - if (/^#comment-\d+/.test(hash)) { - showComments(function (err) { - if (!err) { - window.location.hash = '' - window.location.hash = hash - } - }) - } - - $('#sd').click(showComments) - - var showdown = new Showdown.converter() - , tzOffset = -new Date().getTimezoneOffset() * 60 * 1000 - - $('#comment-form').submit(function() { - var comment = $(this).serializeObject() - comment.name = (comment.name || '').trim() || 'anonymous' - comment.url = (comment.url || '').trim() - if (comment.url && !comment.url.match(/^https?:\/\//)) { - comment.url = 'http://' + comment.url - } - comment.body = comment.body || '' - if (!comment.body) { - alert("is that all you have to say?") - document.getElementById('thoughts').focus() - return false - } - comment.timestamp = +new Date() + tzOffset - - var options = { method: 'POST' - , uri: postCommentURL() - , body: JSON.stringify(comment) - } - SJS.request(options, function(err, request, body) { - if (err) { - console.dir(err) - alert('derp') - return false - } - - $('#comment-form').get(0).reset() - - comment.timestamp = +new Date() - comment.html = showdown.makeHtml(comment.body) - comment.name = (comment.name || '').trim() || 'anonymous' - comment.url = (comment.url || '').trim() - if (comment.url && !comment.url.match(/^https?:\/\//)) { - comment.url = 'http://' + comment.url - } - $('#comments').append(tmpl('comment_tmpl', comment)) - }) - return false - }) - }) -}()); diff --git a/assets/js/gitter.js b/assets/js/gitter.js deleted file mode 100644 index 5bd2e95..0000000 --- a/assets/js/gitter.js +++ /dev/null @@ -1,766 +0,0 @@ -/// gitter -/// http://github.com/samsonjs/gitter -/// @_sjs -/// -/// Copyright 2010 - 2012 Sami Samhuri -/// MIT License - -(function() { - "use strict" - - var global = (function() { return this || (1, eval)('this') }()) - , isBrowser = 'document' in global - , ie - - if (isBrowser) { - ie = (function() { - var undef - , v = 3 - , div = document.createElement('div') - , all = div.getElementsByTagName('i') - - while ( - div.innerHTML = '', - all[0] - ); - - return v > 4 ? v : undef - }()) - } - - var inherits - if ('create' in Object) { - // util.inherits from node - inherits = function(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false - } - }) - } - } - else if ([].__proto__) { - inherits = function(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype.__proto__ = superCtor.prototype - ctor.prototype.constructor = ctor - } - } - else { // ie8 - var __hasProp = Object.prototype.hasOwnProperty - inherits = function(child, parent) { - for (var key in parent) { - if (__hasProp.call(parent, key)) child[key] = parent[key] - } - function ctor() { this.constructor = child } - ctor.prototype = parent.prototype - child.prototype = new ctor - child.__super__ = parent.prototype - return child - } - } - - var api = { - // Blob - blob: function(user, repo, sha, cb) { - return new Blob(user, repo, sha, cb) - } - - // Branch - , branch: function(user, repo, name, cb) { - return new Branch(user, repo, name, cb) - } - - // Commit - , commit: function(user, repo, sha, cb) { - return new Commit(user, repo, sha, cb) - } - - // Download - , download: function(user, repo, id, cb) { - return new Download(user, repo, id, cb) - } - - // Issue - , issue: function(user, repo, id, cb) { - return new Issue(user, repo, id, cb) - } - - // Organization - , org: function(name, cb) { - return new Org(name, cb) - } - , members: function(name, cb) { - return new Org(name).fetchMembers(cb) - } - - // Repo - , repo: function(user, repo, cb) { - return new Repo(user, repo, cb) - } - , branches: function(user, repo, cb) { - return new Repo(user, repo).fetchBranches(cb) - } - , collaborators: function(user, repo, cb) { - return new Repo(user, repo).fetchCollaborators(cb) - } - , contributors: function(user, repo, cb) { - return new Repo(user, repo).fetchContributors(cb) - } - , downloads: function(user, repo, cb) { - return new Repo(user, repo).fetchDownloads(cb) - } - , forks: function(user, repo, cb) { - return new Repo(user, repo).fetchForks(cb) - } - , issues: function(user, repo, cb) { - return new Repo(user, repo).fetchIssues(cb) - } - , languages: function(user, repo, cb) { - return new Repo(user, repo).fetchLanguages(cb) - } - , tags: function(user, repo, cb) { - return new Repo(user, repo).fetchTags(cb) - } - , watchers: function(user, repo, cb) { - return new Repo(user, repo).fetchWatchers(cb) - } - - , ref: function(user, repo, name, cb) { - return new Ref(user, repo, name, cb) - } - - // Tag - , tag: function(user, repo, name, cb) { - return new Tag(user, repo, name, cb) - } - - // Tree - , tree: function(user, repo, sha, cb) { - return new Tree(user, repo, sha, cb) - } - - // User - , user: function(login, cb) { - return new User(login, cb) - } - , followers: function(login, cb) { - return new User(login).fetchFollowers(cb) - } - , following: function(login, cb) { - return new User(login).fetchFollowing(cb) - } - , repos: function(login, cb) { - return new User(login).fetchRepos(cb) - } - , watched: function(login, cb) { - return new User(login).fetchWatched(cb) - } - - // Why not, expose the resources directly as well. - , Blob: Blob - , Branch: Branch - , Commit: Commit - , Download: Download - , Issue: Issue - , Org: Org - , Ref: Ref - , Repo: Repo - , Tree: Tree - , User: User - } - - // when running in the browser request is set later, in shim() - var request - - if (isBrowser) { - shim() - global.GITR = api - } - else { - var https = require('https') - request = function(options, cb) { - var req = https.request(options, function(response) { - var bodyParts = [] - response.on('data', function(b) { bodyParts.push(b) }) - response.on('end', function() { - var body = bodyParts.join('') - if (response.statusCode === 200) { - cb(null, body, response) - } - else { - console.dir(options, response, body) - var err = new Error('http error') - err.statusCode = response.statusCode - err.body = body - cb(err) - } - }) - }) - req.end() - req.on('error', function(err) { cb(err) }) - } - module.exports = api - } - - - // Generic Resource // - // - // Used as the prototype by createResource. Provides - // methods for fetching the resource and related - // sub-resources. - function Resource() {} - - // Fetch data for this resource and pass it to the - // callback after mixing the data into the object. - // Data is also available via the `data` property. - Resource.prototype.fetch = function(cb) { - if (this.data) { - cb(null, this.data) - } - else { - var self = this - fetch(this.path, function(err, data) { - // console.log('FETCH', self.path, err, data) - if (err) { - // console.log(err) - } - else { - self.data = data - mixin(self, data) - } - if (typeof cb === 'function') { - cb.call(self, err, data) - } - }) - } - return this - } - - Resource.prototype.fetchSubResource = function(thing, cb) { - if (this['_' + thing]) { - cb(null, this['_' + thing]) - } - else { - var self = this - fetch(this.path + '/' + thing, function(err, data) { - // console.log('FETCH SUBRESOURCE', self.path, thing, err, data) - if (err) { - // console.log(self.path, err) - } - else { - self['_' + thing] = data - } - if (typeof cb === 'function') { - cb.call(self, err, data) - } - }) - } - return this - } - - var __slice = Array.prototype.slice - - // Create a resource w/ Resource as the prototype. - // - // spec: an object with the following properties: - // - // - constructor: a constructor function - // - has: a list of resources belonging to this resource - // - // Typically the constructor accepts one or more arguments specifying - // the name or pieces of info identifying the specific resource and - // used to build the URL to fetch it. It also accepts an optional - // callback as the last parameter. - // - // The constructor must set the `path` property which is used to - // fetch the resource. - // - // If a callback is provided then the resource is immediately - // fetched and the callback is threaded through to the `fetch` - // method. The callback function has the signature - // `function(err, data)`. - // - // The `has` list specifies sub-resources, e.g. a user has repos, - // followers, etc. An organization has members. - // - // Each related sub-resource gets a method named appropriately, - // e.g. the User resource has followers so User objects have a - // `fetchFollowers` method. - function createResource(spec) { - var subResources = spec.has ? __slice.call(spec.has) : null - , resource = function(/* ..., cb */) { - var args = __slice.call(arguments) - , lastArgIsCallback = typeof args[args.length - 1] === 'function' - , cb = lastArgIsCallback ? args.pop() : null - , result = spec.constructor.apply(this, args) - - if (typeof cb === 'function') { - this.fetch(cb) - } - - return result - } - - inherits(resource, Resource) - - if (subResources) { - subResources.forEach(function(thing) { - var fnName = 'fetch' + toTitleCase(thing) - resource.prototype[fnName] = function(cb) { - return this.fetchSubResource(thing, cb) - } - }) - } - - return resource - } - - - // Define Resources // - - var Blob = createResource({ - constructor: function(user, repo, sha) { - this.user = user - this.repo = repo - this.sha = sha - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') + '/git/blobs/' + sha - } - }) - - var Branch = createResource({ - constructor: function (user, repo, name) { - this.user = user - this.repo = repo - this.name = name - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') + '/git/refs/heads/' + name - } - }) - - var Commit = createResource({ - constructor: function Commit(user, repo, sha) { - this.user = user - this.repo = repo - this.sha = sha - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') + '/git/commits/' + sha - } - }) - - var Download = createResource({ - constructor: function(user, repo, id) { - this.user = user - this.repo = repo - this.id = id - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') + '/downloads/' + id - } - }) - - var Issue = createResource({ - constructor: function(user, repo, id) { - this.user = user - this.repo = repo - this.id = id - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') + '/issues/' + id - } - }) - - var Org = createResource({ - constructor: function(name) { - this.name = name - this.path = '/orgs/' + encodeURIComponent(nam) - } - - , has: 'members repos'.split(' ') - }) - - var Ref = createResource({ - constructor: function (user, repo, name) { - this.user = user - this.repo = repo - this.name = name - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') + '/git/refs/' + name - } - }) - - var Repo = createResource({ - constructor: function(user, repo) { - this.user = user - this.repo = repo - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') - } - - , has: ('branches collaborators contributors downloads' + - ' forks languages tags teams watchers').split(' ') - }) - - var Tag = createResource({ - constructor: function (user, repo, name) { - this.user = user - this.repo = repo - this.name = name - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') + '/git/refs/tags/' + name - } - }) - - var Tree = createResource({ - constructor: function(user, repo, sha) { - this.user = user - this.repo = repo - this.sha = sha - this.path = '/repos/' + [user, repo].map(encodeURIComponent).join('/') + '/git/trees/' + sha - } - }) - - var User = createResource({ - constructor: function(login) { - // Allow creating a user from an object returned by the API - if (login.login) { - login = login.login - } - this.login = login - this.path = '/users/' + encodeURIComponent(login) - } - - , has: 'followers following repos watched'.split(' ') - }) - - - // Fetch data from github. JSON is parsed and keys are camelized. - // - // path: the path to the resource - // cb: callback(err, data) - function fetch(path, cb) { - request({ host: 'api.github.com', path: path }, function(err, body, response) { - // JSONP requests in the browser return the object directly - var data = body - - // Requests in Node return json text, try to parse it - if (response && /json/i.exec(response.headers['content-type'])) { - try { - data = JSON.parse(body) - } - catch (e) { - err = e - data = null - } - } - - cb(err, camelize(data)) - }) - } - - // created_at => createdAt - function camel(s) { - return s.replace(/_(.)/g, function(_, l) { return l.toUpperCase() }) - } - - // camelize all keys of an object, or all objects in an array - function camelize(obj) { - if (!obj || typeof obj === 'string') return obj - if (Array.isArray(obj)) return obj.map(camelize) - if (typeof obj === 'object') { - return Object.keys(obj).reduce(function(camelizedObj, k) { - camelizedObj[camel(k)] = camelize(obj[k]) - return camelizedObj - }, {}) - } - return obj - } - - function toTitleCase(s) { - return s.charAt(0).toUpperCase() + s.slice(1) - } - - function mixin(a, b) { - for (var k in b) { - if (b.hasOwnProperty(k)) a[k] = b[k] - } - } - - - // Browser Utilities // - - function shim() { - shimBind() - shimES5() - shimRequest() - } - - function shimBind() { - // bind from Prototype - if (!Function.prototype.bind) { - (function(){ - function update(array, args) { - var arrayLength = array.length, length = args.length - while (length--) array[arrayLength + length] = args[length] - return array - } - function merge(array, args) { - array = __slice.call(array, 0) - return update(array, args) - } - Function.prototype.bind = function(context) { - if (arguments.length < 2 && typeof arguments[0] === 'undefined') return this - var __method = this, args = __slice.call(arguments, 1) - return function() { - var a = merge(args, arguments) - return __method.apply(context, a) - } - } - }()) - } - } - - // a few functions from Kris Kowal's es5-shim - // https://github.com/kriskowal/es5-shim - function shimES5() { - var has = Object.prototype.hasOwnProperty - - // ES5 15.2.3.6 - if (!Object.defineProperty || ie === 8) { // ie8 - Object.defineProperty = function(object, property, descriptor) { - if (typeof descriptor == "object" && object.__defineGetter__) { - if (has.call(descriptor, "value")) { - if (!object.__lookupGetter__(property) && !object.__lookupSetter__(property)) { - // data property defined and no pre-existing accessors - object[property] = descriptor.value - } - if (has.call(descriptor, "get") || has.call(descriptor, "set")) { - // descriptor has a value property but accessor already exists - throw new TypeError("Object doesn't support this action") - } - } - // fail silently if "writable", "enumerable", or "configurable" - // are requested but not supported - else if (typeof descriptor.get == "function") { - object.__defineGetter__(property, descriptor.get) - } - if (typeof descriptor.set == "function") { - object.__defineSetter__(property, descriptor.set) - } - } - return object - } - } - - // ES5 15.2.3.14 - // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation - if (!Object.keys) { // ie8 - (function() { - var hasDontEnumBug = true, - dontEnums = [ - 'toString', - 'toLocaleString', - 'valueOf', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor' - ], - dontEnumsLength = dontEnums.length - - for (var key in {"toString": null}) { - hasDontEnumBug = false - } - - Object.keys = function (object) { - - if ( - typeof object !== "object" && typeof object !== "function" - || object === null - ) - throw new TypeError("Object.keys called on a non-object") - - var keys = [] - for (var name in object) { - if (has.call(object, name)) { - keys.push(name) - } - } - - if (hasDontEnumBug) { - for (var i = 0, ii = dontEnumsLength; i < ii; i++) { - var dontEnum = dontEnums[i] - if (has.call(object, dontEnum)) { - keys.push(dontEnum) - } - } - } - - return keys - } - }()) - } // Object.keys - - // - // Array - // ===== - // - - // ES5 15.4.3.2 - if (!Array.isArray) { - Array.isArray = function(obj) { - return Object.prototype.toString.call(obj) == "[object Array]" - } - } - - // ES5 15.4.4.18 - if (!Array.prototype.forEach) { // ie8 - Array.prototype.forEach = function(block, thisObject) { - var len = this.length >>> 0 - for (var i = 0; i < len; i++) { - if (i in this) { - block.call(thisObject, this[i], i, this) - } - } - } - } - - // ES5 15.4.4.19 - // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map - if (!Array.prototype.map) { // ie8 - Array.prototype.map = function(fun /*, thisp*/) { - var len = this.length >>> 0 - if (typeof fun != "function") { - throw new TypeError() - } - - var res = new Array(len) - var thisp = arguments[1] - for (var i = 0; i < len; i++) { - if (i in this) { - res[i] = fun.call(thisp, this[i], i, this) - } - } - - return res - } - } - - // ES5 15.4.4.20 - if (!Array.prototype.filter) { // ie8 - Array.prototype.filter = function (block /*, thisp */) { - var values = [] - , thisp = arguments[1] - for (var i = 0; i < this.length; i++) { - if (block.call(thisp, this[i])) { - values.push(this[i]) - } - } - return values - } - } - - // ES5 15.4.4.21 - // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce - if (!Array.prototype.reduce) { // ie8 - Array.prototype.reduce = function(fun /*, initial*/) { - var len = this.length >>> 0 - if (typeof fun != "function") { - throw new TypeError() - } - - // no value to return if no initial value and an empty array - if (len == 0 && arguments.length == 1) { - throw new TypeError() - } - - var i = 0 - if (arguments.length >= 2) { - var rv = arguments[1] - } else { - do { - if (i in this) { - rv = this[i++] - break - } - - // if array contains no values, no initial value to return - if (++i >= len) { - throw new TypeError() - } - } while (true) - } - - for (; i < len; i++) { - if (i in this) { - rv = fun.call(null, rv, this[i], i, this) - } - } - - return rv - } - } // Array.prototype.reduce - } // function shimES5() - - // jsonp request, quacks like node's http.request - function shimRequest() { - var load, _jsonpCounter = 1 - - // request is declared earlier - request = function(options, cb) { - var jsonpCallbackName = '_jsonpCallback' + _jsonpCounter++ - , url = 'https://' + options.host + options.path + '?callback=GITR.' + jsonpCallbackName - GITR[jsonpCallbackName] = function(response) { - if (response.meta.status >= 200 && response.meta.status < 300) { - cb(null, response.data) - } - else { - var err = new Error('http error') - err.statusCode = response.meta.status - err.response = response - cb(err) - } - setTimeout(function() { delete GITR[jsonpCallbackName] }, 0) - } - load(url) - } - - // bootstrap loader from LABjs (load is declared earlier) - load = function(url) { - var oDOC = document - , handler - , head = oDOC.head || oDOC.getElementsByTagName("head") - - // loading code borrowed directly from LABjs itself - // (now removes script elem when done and nullifies its reference --sjs) - setTimeout(function () { - if ("item" in head) { // check if ref is still a live node list - if (!head[0]) { // append_to node not yet ready - setTimeout(arguments.callee, 25) - return - } - head = head[0]; // reassign from live node list ref to pure node ref -- avoids nasty IE bug where changes to DOM invalidate live node lists - } - var scriptElem = oDOC.createElement("script") - , scriptdone = false - - scriptElem.onload = scriptElem.onreadystatechange = function () { - if ((scriptElem.readyState && scriptElem.readyState !== "complete" && scriptElem.readyState !== "loaded") || scriptdone) { - return false - } - scriptElem.onload = scriptElem.onreadystatechange = null - scriptElem.parentNode.removeChild(scriptElem) - scriptElem = null - scriptdone = true - } - scriptElem.src = url - head.insertBefore(scriptElem, head.firstChild) - }, 0) // setTimeout - - // required: shim for FF <= 3.5 not having document.readyState - if (oDOC.readyState == null && oDOC.addEventListener) { - oDOC.readyState = "loading" - oDOC.addEventListener("DOMContentLoaded", function handler() { - oDOC.removeEventListener("DOMContentLoaded", handler, false) - oDOC.readyState = "complete" - }, false) - } - - } // function load(url) - - } // function shimRequest() - -}()) diff --git a/assets/js/jquery-serializeObject.js b/assets/js/jquery-serializeObject.js deleted file mode 100644 index 6956ba4..0000000 --- a/assets/js/jquery-serializeObject.js +++ /dev/null @@ -1,31 +0,0 @@ -/*! - * jQuery serializeObject - v0.2 - 1/20/2010 - * http://benalman.com/projects/jquery-misc-plugins/ - * - * Copyright (c) 2010 "Cowboy" Ben Alman - * Dual licensed under the MIT and GPL licenses. - * http://benalman.com/about/license/ - */ - -// Whereas .serializeArray() serializes a form into an array, .serializeObject() -// serializes a form into an (arguably more useful) object. - -;(function($,undefined){ - '$:nomunge'; // Used by YUI compressor. - - $.fn.serializeObject = function(){ - var obj = {}; - - $.each( this.serializeArray(), function(i,o){ - var n = o.name, - v = o.value; - - obj[n] = obj[n] === undefined ? v - : $.isArray( obj[n] ) ? obj[n].concat( v ) - : [ obj[n], v ]; - }); - - return obj; - }; - -})(jQuery); diff --git a/assets/js/proj.js b/assets/js/proj.js deleted file mode 100644 index 59fab02..0000000 --- a/assets/js/proj.js +++ /dev/null @@ -1,137 +0,0 @@ -;(function() { - if (typeof console === 'undefined') { - console = {log:function(){}} - } - - var global = this - global.SJS = { - proj: function(name) { - SJS.projName = name - var data = createObjectStore(name) - if (document.addEventListener) { - document.addEventListener('DOMContentLoaded', ready, false) - } else if (window.attachEvent) { - window.attachEvent('onload', ready) - } - function ready() { - function addClass(el, name) { - var c = el.className || name - if (!c.match(new RegExp('\b' + name + '\b', 'i'))) c += ' ' + name - } - function html(id, h) { - document.getElementById(id).innerHTML = h - } - - var body = document.getElementsByTagName('body')[0] - , text - if ('innerText' in body) { - text = function(id, text) { - document.getElementById(id).innerText = text - } - } else { - text = function(id, text) { - document.getElementById(id).textContent = text - } - } - - function highlight(id) { - document.getElementById(id).style.className = ' highlight' - } - function textHighlight(id, t) { - text(id, t) - document.getElementById(id).className = ' highlight' - } - function hide(id) { - document.getElementById(id).style.display = 'none' - } - - function langsByUsage(langs) { - return Object.keys(langs).sort(function(a, b) { - return langs[a] < langs[b] ? -1 : 1 - }) - } - - function listify(things) { - return '' - } - - function updateBranches(name, branches) { - function branchLink(b) { - return '' + b.name + '' - } - html('branches', listify(branches.map(branchLink))) - } - - function updateContributors(contributors) { - function userLink(u) { - return '' + (u.name || u.login) + '' - } - html('contributors', listify(contributors.map(userLink))) - } - - function updateLangs(langs) { - html('langs', listify(langsByUsage(langs))) - } - - function updateN(name, things) { - textHighlight('n' + name, things.length) - if (things.length === 1) hide(name.charAt(0) + 'plural') - } - - var t = data.get('t-' + name) - if (!t || +new Date() - t > 3600 * 1000) { - console.log('stale ' + String(t)) - data.set('t-' + name, +new Date()) - GITR.repo('samsonjs', name) - .fetchBranches(function(err, branches) { - if (err) { - text('branches', '(oops)') - } else { - data.set('branches', branches) - updateBranches(name, branches) - } - }) - .fetchLanguages(function(err, langs) { - if (err) { - text('langs', '(oops)') - return - } - data.set('langs', langs) - updateLangs(langs) - }) - .fetchContributors(function(err, users) { - if (err) { - text('contributors', '(oops)') - } else { - data.set('contributors', users) - updateContributors(users) - } - }) - .fetchWatchers(function(err, users) { - if (err) { - text('nwatchers', '?') - } else { - data.set('watchers', users) - updateN('watchers', users) - } - }) - .fetchForks(function(err, repos) { - if (err) { - text('nforks', '?') - } else { - data.set('forks', repos) - updateN('forks', repos) - } - }) - } else { - console.log('hit ' + t + ' (' + (+new Date() - t) + ')') - updateBranches(name, data.get('branches')) - updateLangs(data.get('langs')) - updateContributors(data.get('contributors')) - updateN('watchers', data.get('watchers')) - updateN('forks', data.get('forks')) - } - } - } - } -}()); diff --git a/assets/js/request.js b/assets/js/request.js deleted file mode 100644 index 27c143a..0000000 --- a/assets/js/request.js +++ /dev/null @@ -1,36 +0,0 @@ -;(function() { - if (typeof window.SJS === 'undefined') window.SJS = {} - - // cors xhr request, quacks like mikeal's request module - window.SJS.request = function(options, cb) { - var url = options.uri - , method = options.method || 'GET' - , headers = options.headers || {} - , body = typeof options.body === 'undefined' ? null : String(options.body) - , xhr = new XMLHttpRequest() - - // withCredentials => cors - if ('withCredentials' in xhr) { - xhr.open(method, url, true) - } else if (typeof XDomainRequest === 'function') { - xhr = new XDomainRequest() - xhr.open(method, url) - } else { - cb(new Error('cross domain requests not supported')) - return - } - for (var k in headers) if (headers.hasOwnProperty(k)) { - xhr.setRequestHeader(k, headers[k]) - } - xhr.onload = function() { - if (xhr.status === 200 || xhr.status === 204) { - cb(null, xhr, xhr.responseText) - } - else { - console.log('xhr error ' + xhr.status + ': ' + xhr.responseText) - cb(new Error('error: ' + xhr.status)) - } - } - xhr.send(body) - } -}()); diff --git a/assets/js/showdown.js b/assets/js/showdown.js deleted file mode 100644 index 226ae8b..0000000 --- a/assets/js/showdown.js +++ /dev/null @@ -1,1296 +0,0 @@ -// -// showdown.js -- A javascript port of Markdown. -// -// Copyright (c) 2007 John Fraser. -// -// Original Markdown Copyright (c) 2004-2005 John Gruber -// -// -// Redistributable under a BSD-style open source license. -// See license.txt for more information. -// -// The full source distribution is at: -// -// A A L -// T C A -// T K B -// -// -// - -// -// Wherever possible, Showdown is a straight, line-by-line port -// of the Perl version of Markdown. -// -// This is not a normal parser design; it's basically just a -// series of string substitutions. It's hard to read and -// maintain this way, but keeping Showdown close to the original -// design makes it easier to port new features. -// -// More importantly, Showdown behaves like markdown.pl in most -// edge cases. So web applications can do client-side preview -// in Javascript, and then build identical HTML on the server. -// -// This port needs the new RegExp functionality of ECMA 262, -// 3rd Edition (i.e. Javascript 1.5). Most modern web browsers -// should do fine. Even with the new regular expression features, -// We do a lot of work to emulate Perl's regex functionality. -// The tricky changes in this file mostly have the "attacklab:" -// label. Major or self-explanatory changes don't. -// -// Smart diff tools like Araxis Merge will be able to match up -// this file with markdown.pl in a useful way. A little tweaking -// helps: in a copy of markdown.pl, replace "#" with "//" and -// replace "$text" with "text". Be sure to ignore whitespace -// and line endings. -// - - -// -// Showdown usage: -// -// var text = "Markdown *rocks*."; -// -// var converter = new Showdown.converter(); -// var html = converter.makeHtml(text); -// -// alert(html); -// -// Note: move the sample code to the bottom of this -// file before uncommenting it. -// - - -// -// Showdown namespace -// -var Showdown = {}; - -// -// converter -// -// Wraps all "globals" so that the only thing -// exposed is makeHtml(). -// -Showdown.converter = function() { - -// -// Globals: -// - -// Global hashes, used by various utility routines -var g_urls; -var g_titles; -var g_html_blocks; - -// Used to track when we're inside an ordered or unordered list -// (see _ProcessListItems() for details): -var g_list_level = 0; - - -this.makeHtml = function(text) { -// -// Main function. The order in which other subs are called here is -// essential. Link and image substitutions need to happen before -// _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the -// and tags get encoded. -// - - // Clear the global hashes. If we don't clear these, you get conflicts - // from other articles when generating a page which contains more than - // one article (e.g. an index page that shows the N most recent - // articles): - g_urls = new Array(); - g_titles = new Array(); - g_html_blocks = new Array(); - - // attacklab: Replace ~ with ~T - // This lets us use tilde as an escape char to avoid md5 hashes - // The choice of character is arbitray; anything that isn't - // magic in Markdown will work. - text = text.replace(/~/g,"~T"); - - // attacklab: Replace $ with ~D - // RegExp interprets $ as a special character - // when it's in a replacement string - text = text.replace(/\$/g,"~D"); - - // Standardize line endings - text = text.replace(/\r\n/g,"\n"); // DOS to Unix - text = text.replace(/\r/g,"\n"); // Mac to Unix - - // Make sure text begins and ends with a couple of newlines: - text = "\n\n" + text + "\n\n"; - - // Convert all tabs to spaces. - text = _Detab(text); - - // Strip any lines consisting only of spaces and tabs. - // This makes subsequent regexen easier to write, because we can - // match consecutive blank lines with /\n+/ instead of something - // contorted like /[ \t]*\n+/ . - text = text.replace(/^[ \t]+$/mg,""); - - // Turn block-level HTML blocks into hash entries - text = _HashHTMLBlocks(text); - - // Strip link definitions, store in hashes. - text = _StripLinkDefinitions(text); - - text = _RunBlockGamut(text); - - text = _UnescapeSpecialChars(text); - - // attacklab: Restore dollar signs - text = text.replace(/~D/g,"$$"); - - // attacklab: Restore tildes - text = text.replace(/~T/g,"~"); - - return text; -} - - -var _StripLinkDefinitions = function(text) { -// -// Strips link definitions from text, stores the URLs and titles in -// hash references. -// - - // Link defs are in the form: ^[id]: url "optional title" - - /* - var text = text.replace(/ - ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1 - [ \t]* - \n? // maybe *one* newline - [ \t]* - ? // url = $2 - [ \t]* - \n? // maybe one newline - [ \t]* - (?: - (\n*) // any lines skipped = $3 attacklab: lookbehind removed - ["(] - (.+?) // title = $4 - [")] - [ \t]* - )? // title is optional - (?:\n+|$) - /gm, - function(){...}); - */ - var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm, - function (wholeMatch,m1,m2,m3,m4) { - m1 = m1.toLowerCase(); - g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive - if (m3) { - // Oops, found blank lines, so it's not a title. - // Put back the parenthetical statement we stole. - return m3+m4; - } else if (m4) { - g_titles[m1] = m4.replace(/"/g,"""); - } - - // Completely remove the definition from the text - return ""; - } - ); - - return text; -} - - -var _HashHTMLBlocks = function(text) { - // attacklab: Double up blank lines to reduce lookaround - text = text.replace(/\n/g,"\n\n"); - - // Hashify HTML blocks: - // We only want to do this for block-level HTML tags, such as headers, - // lists, and tables. That's because we still want to wrap

s around - // "paragraphs" that are wrapped in non-block-level tags, such as anchors, - // phrase emphasis, and spans. The list of tags we're looking for is - // hard-coded: - var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del" - var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math" - - // First, look for nested blocks, e.g.: - //

- //
- // tags for inner block must be indented. - //
- //
- // - // The outermost tags must start at the left margin for this to match, and - // the inner nested divs must be indented. - // We need to do this before the next, more liberal match, because the next - // match will start at the first `
` and stop at the first `
`. - - // attacklab: This regex can be expensive when it fails. - /* - var text = text.replace(/ - ( // save in $1 - ^ // start of line (with /m) - <($block_tags_a) // start tag = $2 - \b // word break - // attacklab: hack around khtml/pcre bug... - [^\r]*?\n // any number of lines, minimally matching - // the matching end tag - [ \t]* // trailing spaces/tabs - (?=\n+) // followed by a newline - ) // attacklab: there are sentinel newlines at end of document - /gm,function(){...}}; - */ - text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement); - - // - // Now match more liberally, simply from `\n` to `\n` - // - - /* - var text = text.replace(/ - ( // save in $1 - ^ // start of line (with /m) - <($block_tags_b) // start tag = $2 - \b // word break - // attacklab: hack around khtml/pcre bug... - [^\r]*? // any number of lines, minimally matching - .* // the matching end tag - [ \t]* // trailing spaces/tabs - (?=\n+) // followed by a newline - ) // attacklab: there are sentinel newlines at end of document - /gm,function(){...}}; - */ - text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement); - - // Special case just for
. It was easier to make a special case than - // to make the other regex more complicated. - - /* - text = text.replace(/ - ( // save in $1 - \n\n // Starting after a blank line - [ ]{0,3} - (<(hr) // start tag = $2 - \b // word break - ([^<>])*? // - \/?>) // the matching end tag - [ \t]* - (?=\n{2,}) // followed by a blank line - ) - /g,hashElement); - */ - text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement); - - // Special case for standalone HTML comments: - - /* - text = text.replace(/ - ( // save in $1 - \n\n // Starting after a blank line - [ ]{0,3} // attacklab: g_tab_width - 1 - - [ \t]* - (?=\n{2,}) // followed by a blank line - ) - /g,hashElement); - */ - text = text.replace(/(\n\n[ ]{0,3}[ \t]*(?=\n{2,}))/g,hashElement); - - // PHP and ASP-style processor instructions ( and <%...%>) - - /* - text = text.replace(/ - (?: - \n\n // Starting after a blank line - ) - ( // save in $1 - [ ]{0,3} // attacklab: g_tab_width - 1 - (?: - <([?%]) // $2 - [^\r]*? - \2> - ) - [ \t]* - (?=\n{2,}) // followed by a blank line - ) - /g,hashElement); - */ - text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement); - - // attacklab: Undo double lines (see comment at top of this function) - text = text.replace(/\n\n/g,"\n"); - return text; -} - -var hashElement = function(wholeMatch,m1) { - var blockText = m1; - - // Undo double lines - blockText = blockText.replace(/\n\n/g,"\n"); - blockText = blockText.replace(/^\n/,""); - - // strip trailing blank lines - blockText = blockText.replace(/\n+$/g,""); - - // Replace the element text with a marker ("~KxK" where x is its key) - blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n"; - - return blockText; -}; - -var _RunBlockGamut = function(text) { -// -// These are all the transformations that form block-level -// tags like paragraphs, headers, and list items. -// - text = _DoHeaders(text); - - // Do Horizontal Rules: - var key = hashBlock("
"); - text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key); - text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key); - text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key); - - text = _DoLists(text); - text = _DoCodeBlocks(text); - text = _DoBlockQuotes(text); - - // We already ran _HashHTMLBlocks() before, in Markdown(), but that - // was to escape raw HTML in the original Markdown source. This time, - // we're escaping the markup we've just created, so that we don't wrap - //

tags around block-level tags. - text = _HashHTMLBlocks(text); - text = _FormParagraphs(text); - - return text; -} - - -var _RunSpanGamut = function(text) { -// -// These are all the transformations that occur *within* block-level -// tags like paragraphs, headers, and list items. -// - - text = _DoCodeSpans(text); - text = _EscapeSpecialCharsWithinTagAttributes(text); - text = _EncodeBackslashEscapes(text); - - // Process anchor and image tags. Images must come first, - // because ![foo][f] looks like an anchor. - text = _DoImages(text); - text = _DoAnchors(text); - - // Make links out of things like `` - // Must come after _DoAnchors(), because you can use < and > - // delimiters in inline links like [this](). - text = _DoAutoLinks(text); - text = _EncodeAmpsAndAngles(text); - text = _DoItalicsAndBold(text); - - // Do hard breaks: - text = text.replace(/ +\n/g,"
\n"); - - return text; -} - -var _EscapeSpecialCharsWithinTagAttributes = function(text) { -// -// Within tags -- meaning between < and > -- encode [\ ` * _] so they -// don't conflict with their use in Markdown for code, italics and strong. -// - - // Build a regex to find HTML tags and comments. See Friedl's - // "Mastering Regular Expressions", 2nd Ed., pp. 200-201. - var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|)/gi; - - text = text.replace(regex, function(wholeMatch) { - var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`"); - tag = escapeCharacters(tag,"\\`*_"); - return tag; - }); - - return text; -} - -var _DoAnchors = function(text) { -// -// Turn Markdown link shortcuts into XHTML
tags. -// - // - // First, handle reference-style links: [link text] [id] - // - - /* - text = text.replace(/ - ( // wrap whole match in $1 - \[ - ( - (?: - \[[^\]]*\] // allow brackets nested one level - | - [^\[] // or anything else - )* - ) - \] - - [ ]? // one optional space - (?:\n[ ]*)? // one optional newline followed by spaces - - \[ - (.*?) // id = $3 - \] - )()()()() // pad remaining backreferences - /g,_DoAnchors_callback); - */ - text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag); - - // - // Next, inline-style links: [link text](url "optional title") - // - - /* - text = text.replace(/ - ( // wrap whole match in $1 - \[ - ( - (?: - \[[^\]]*\] // allow brackets nested one level - | - [^\[\]] // or anything else - ) - ) - \] - \( // literal paren - [ \t]* - () // no id, so leave $3 empty - ? // href = $4 - [ \t]* - ( // $5 - (['"]) // quote char = $6 - (.*?) // Title = $7 - \6 // matching quote - [ \t]* // ignore any spaces/tabs between closing quote and ) - )? // title is optional - \) - ) - /g,writeAnchorTag); - */ - text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag); - - // - // Last, handle reference-style shortcuts: [link text] - // These must come last in case you've also got [link test][1] - // or [link test](/foo) - // - - /* - text = text.replace(/ - ( // wrap whole match in $1 - \[ - ([^\[\]]+) // link text = $2; can't contain '[' or ']' - \] - )()()()()() // pad rest of backreferences - /g, writeAnchorTag); - */ - text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag); - - return text; -} - -var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { - if (m7 == undefined) m7 = ""; - var whole_match = m1; - var link_text = m2; - var link_id = m3.toLowerCase(); - var url = m4; - var title = m7; - - if (url == "") { - if (link_id == "") { - // lower-case and turn embedded newlines into spaces - link_id = link_text.toLowerCase().replace(/ ?\n/g," "); - } - url = "#"+link_id; - - if (g_urls[link_id] != undefined) { - url = g_urls[link_id]; - if (g_titles[link_id] != undefined) { - title = g_titles[link_id]; - } - } - else { - if (whole_match.search(/\(\s*\)$/m)>-1) { - // Special case for explicit empty url - url = ""; - } else { - return whole_match; - } - } - } - - url = escapeCharacters(url,"*_"); - var result = ""; - - return result; -} - - -var _DoImages = function(text) { -// -// Turn Markdown image shortcuts into tags. -// - - // - // First, handle reference-style labeled images: ![alt text][id] - // - - /* - text = text.replace(/ - ( // wrap whole match in $1 - !\[ - (.*?) // alt text = $2 - \] - - [ ]? // one optional space - (?:\n[ ]*)? // one optional newline followed by spaces - - \[ - (.*?) // id = $3 - \] - )()()()() // pad rest of backreferences - /g,writeImageTag); - */ - text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag); - - // - // Next, handle inline images: ![alt text](url "optional title") - // Don't forget: encode * and _ - - /* - text = text.replace(/ - ( // wrap whole match in $1 - !\[ - (.*?) // alt text = $2 - \] - \s? // One optional whitespace character - \( // literal paren - [ \t]* - () // no id, so leave $3 empty - ? // src url = $4 - [ \t]* - ( // $5 - (['"]) // quote char = $6 - (.*?) // title = $7 - \6 // matching quote - [ \t]* - )? // title is optional - \) - ) - /g,writeImageTag); - */ - text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag); - - return text; -} - -var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { - var whole_match = m1; - var alt_text = m2; - var link_id = m3.toLowerCase(); - var url = m4; - var title = m7; - - if (!title) title = ""; - - if (url == "") { - if (link_id == "") { - // lower-case and turn embedded newlines into spaces - link_id = alt_text.toLowerCase().replace(/ ?\n/g," "); - } - url = "#"+link_id; - - if (g_urls[link_id] != undefined) { - url = g_urls[link_id]; - if (g_titles[link_id] != undefined) { - title = g_titles[link_id]; - } - } - else { - return whole_match; - } - } - - alt_text = alt_text.replace(/"/g,"""); - url = escapeCharacters(url,"*_"); - var result = "\""" + _RunSpanGamut(m1) + "");}); - - text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, - function(matchFound,m1){return hashBlock("

" + _RunSpanGamut(m1) + "

");}); - - // atx-style headers: - // # Header 1 - // ## Header 2 - // ## Header 2 with closing hashes ## - // ... - // ###### Header 6 - // - - /* - text = text.replace(/ - ^(\#{1,6}) // $1 = string of #'s - [ \t]* - (.+?) // $2 = Header text - [ \t]* - \#* // optional closing #'s (not counted) - \n+ - /gm, function() {...}); - */ - - text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, - function(wholeMatch,m1,m2) { - var h_level = m1.length; - return hashBlock("" + _RunSpanGamut(m2) + ""); - }); - - return text; -} - -// This declaration keeps Dojo compressor from outputting garbage: -var _ProcessListItems; - -var _DoLists = function(text) { -// -// Form HTML ordered (numbered) and unordered (bulleted) lists. -// - - // attacklab: add sentinel to hack around khtml/safari bug: - // http://bugs.webkit.org/show_bug.cgi?id=11231 - text += "~0"; - - // Re-usable pattern to match any entirel ul or ol list: - - /* - var whole_list = / - ( // $1 = whole list - ( // $2 - [ ]{0,3} // attacklab: g_tab_width - 1 - ([*+-]|\d+[.]) // $3 = first list item marker - [ \t]+ - ) - [^\r]+? - ( // $4 - ~0 // sentinel for workaround; should be $ - | - \n{2,} - (?=\S) - (?! // Negative lookahead for another list item marker - [ \t]* - (?:[*+-]|\d+[.])[ \t]+ - ) - ) - )/g - */ - var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm; - - if (g_list_level) { - text = text.replace(whole_list,function(wholeMatch,m1,m2) { - var list = m1; - var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol"; - - // Turn double returns into triple returns, so that we can make a - // paragraph for the last item in a list, if necessary: - list = list.replace(/\n{2,}/g,"\n\n\n");; - var result = _ProcessListItems(list); - - // Trim any trailing whitespace, to put the closing `` - // up on the preceding line, to get it past the current stupid - // HTML block parser. This is a hack to work around the terrible - // hack that is the HTML block parser. - result = result.replace(/\s+$/,""); - result = "<"+list_type+">" + result + "\n"; - return result; - }); - } else { - whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g; - text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) { - var runup = m1; - var list = m2; - - var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol"; - // Turn double returns into triple returns, so that we can make a - // paragraph for the last item in a list, if necessary: - var list = list.replace(/\n{2,}/g,"\n\n\n");; - var result = _ProcessListItems(list); - result = runup + "<"+list_type+">\n" + result + "\n"; - return result; - }); - } - - // attacklab: strip sentinel - text = text.replace(/~0/,""); - - return text; -} - -_ProcessListItems = function(list_str) { -// -// Process the contents of a single ordered or unordered list, splitting it -// into individual list items. -// - // The $g_list_level global keeps track of when we're inside a list. - // Each time we enter a list, we increment it; when we leave a list, - // we decrement. If it's zero, we're not in a list anymore. - // - // We do this because when we're not inside a list, we want to treat - // something like this: - // - // I recommend upgrading to version - // 8. Oops, now this line is treated - // as a sub-list. - // - // As a single paragraph, despite the fact that the second line starts - // with a digit-period-space sequence. - // - // Whereas when we're inside a list (or sub-list), that line will be - // treated as the start of a sub-list. What a kludge, huh? This is - // an aspect of Markdown's syntax that's hard to parse perfectly - // without resorting to mind-reading. Perhaps the solution is to - // change the syntax rules such that sub-lists must start with a - // starting cardinal number; e.g. "1." or "a.". - - g_list_level++; - - // trim trailing blank lines: - list_str = list_str.replace(/\n{2,}$/,"\n"); - - // attacklab: add sentinel to emulate \z - list_str += "~0"; - - /* - list_str = list_str.replace(/ - (\n)? // leading line = $1 - (^[ \t]*) // leading whitespace = $2 - ([*+-]|\d+[.]) [ \t]+ // list marker = $3 - ([^\r]+? // list item text = $4 - (\n{1,2})) - (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+)) - /gm, function(){...}); - */ - list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm, - function(wholeMatch,m1,m2,m3,m4){ - var item = m4; - var leading_line = m1; - var leading_space = m2; - - if (leading_line || (item.search(/\n{2,}/)>-1)) { - item = _RunBlockGamut(_Outdent(item)); - } - else { - // Recursion for sub-lists: - item = _DoLists(_Outdent(item)); - item = item.replace(/\n$/,""); // chomp(item) - item = _RunSpanGamut(item); - } - - return "
  • " + item + "
  • \n"; - } - ); - - // attacklab: strip sentinel - list_str = list_str.replace(/~0/g,""); - - g_list_level--; - return list_str; -} - - -var _DoCodeBlocks = function(text) { -// -// Process Markdown `
    ` blocks.
    -//
    -
    -	/*
    -		text = text.replace(text,
    -			/(?:\n\n|^)
    -			(								// $1 = the code block -- one or more lines, starting with a space/tab
    -				(?:
    -					(?:[ ]{4}|\t)			// Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
    -					.*\n+
    -				)+
    -			)
    -			(\n*[ ]{0,3}[^ \t\n]|(?=~0))	// attacklab: g_tab_width
    -		/g,function(){...});
    -	*/
    -
    -	// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
    -	text += "~0";
    -
    -	text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
    -		function(wholeMatch,m1,m2) {
    -			var codeblock = m1;
    -			var nextChar = m2;
    -
    -			codeblock = _EncodeCode( _Outdent(codeblock));
    -			codeblock = _Detab(codeblock);
    -			codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
    -			codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
    -
    -			codeblock = "
    " + codeblock + "\n
    "; - - return hashBlock(codeblock) + nextChar; - } - ); - - // attacklab: strip sentinel - text = text.replace(/~0/,""); - - return text; -} - -var hashBlock = function(text) { - text = text.replace(/(^\n+|\n+$)/g,""); - return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n"; -} - - -var _DoCodeSpans = function(text) { -// -// * Backtick quotes are used for spans. -// -// * You can use multiple backticks as the delimiters if you want to -// include literal backticks in the code span. So, this input: -// -// Just type ``foo `bar` baz`` at the prompt. -// -// Will translate to: -// -//

    Just type foo `bar` baz at the prompt.

    -// -// There's no arbitrary limit to the number of backticks you -// can use as delimters. If you need three consecutive backticks -// in your code, use four for delimiters, etc. -// -// * You can use spaces to get literal backticks at the edges: -// -// ... type `` `bar` `` ... -// -// Turns to: -// -// ... type `bar` ... -// - - /* - text = text.replace(/ - (^|[^\\]) // Character before opening ` can't be a backslash - (`+) // $2 = Opening run of ` - ( // $3 = The code block - [^\r]*? - [^`] // attacklab: work around lack of lookbehind - ) - \2 // Matching closer - (?!`) - /gm, function(){...}); - */ - - text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm, - function(wholeMatch,m1,m2,m3,m4) { - var c = m3; - c = c.replace(/^([ \t]*)/g,""); // leading whitespace - c = c.replace(/[ \t]*$/g,""); // trailing whitespace - c = _EncodeCode(c); - return m1+""+c+""; - }); - - return text; -} - - -var _EncodeCode = function(text) { -// -// Encode/escape certain characters inside Markdown code runs. -// The point is that in code, these characters are literals, -// and lose their special Markdown meanings. -// - // Encode all ampersands; HTML entities are not - // entities within a Markdown code span. - text = text.replace(/&/g,"&"); - - // Do the angle bracket song and dance: - text = text.replace(//g,">"); - - // Now, escape characters that are magic in Markdown: - text = escapeCharacters(text,"\*_{}[]\\",false); - -// jj the line above breaks this: -//--- - -//* Item - -// 1. Subitem - -// special char: * -//--- - - return text; -} - - -var _DoItalicsAndBold = function(text) { - - // must go first: - text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, - "$2"); - - text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, - "$2"); - - return text; -} - - -var _DoBlockQuotes = function(text) { - - /* - text = text.replace(/ - ( // Wrap whole match in $1 - ( - ^[ \t]*>[ \t]? // '>' at the start of a line - .+\n // rest of the first line - (.+\n)* // subsequent consecutive lines - \n* // blanks - )+ - ) - /gm, function(){...}); - */ - - text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, - function(wholeMatch,m1) { - var bq = m1; - - // attacklab: hack around Konqueror 3.5.4 bug: - // "----------bug".replace(/^-/g,"") == "bug" - - bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting - - // attacklab: clean up hack - bq = bq.replace(/~0/g,""); - - bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines - bq = _RunBlockGamut(bq); // recurse - - bq = bq.replace(/(^|\n)/g,"$1 "); - // These leading spaces screw with
     content, so we need to fix that:
    -			bq = bq.replace(
    -					/(\s*
    [^\r]+?<\/pre>)/gm,
    -				function(wholeMatch,m1) {
    -					var pre = m1;
    -					// attacklab: hack around Konqueror 3.5.4 bug:
    -					pre = pre.replace(/^  /mg,"~0");
    -					pre = pre.replace(/~0/g,"");
    -					return pre;
    -				});
    -
    -			return hashBlock("
    \n" + bq + "\n
    "); - }); - return text; -} - - -var _FormParagraphs = function(text) { -// -// Params: -// $text - string to process with html

    tags -// - - // Strip leading and trailing lines: - text = text.replace(/^\n+/g,""); - text = text.replace(/\n+$/g,""); - - var grafs = text.split(/\n{2,}/g); - var grafsOut = new Array(); - - // - // Wrap

    tags. - // - var end = grafs.length; - for (var i=0; i= 0) { - grafsOut.push(str); - } - else if (str.search(/\S/) >= 0) { - str = _RunSpanGamut(str); - str = str.replace(/^([ \t]*)/g,"

    "); - str += "

    " - grafsOut.push(str); - } - - } - - // - // Unhashify HTML blocks - // - end = grafsOut.length; - for (var i=0; i= 0) { - var blockText = g_html_blocks[RegExp.$1]; - blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs - grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText); - } - } - - return grafsOut.join("\n\n"); -} - - -var _EncodeAmpsAndAngles = function(text) { -// Smart processing for ampersands and angle brackets that need to be encoded. - - // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: - // http://bumppo.net/projects/amputator/ - text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&"); - - // Encode naked <'s - text = text.replace(/<(?![a-z\/?\$!])/gi,"<"); - - return text; -} - - -var _EncodeBackslashEscapes = function(text) { -// -// Parameter: String. -// Returns: The string, with after processing the following backslash -// escape sequences. -// - - // attacklab: The polite way to do this is with the new - // escapeCharacters() function: - // - // text = escapeCharacters(text,"\\",true); - // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true); - // - // ...but we're sidestepping its use of the (slow) RegExp constructor - // as an optimization for Firefox. This function gets called a LOT. - - text = text.replace(/\\(\\)/g,escapeCharacters_callback); - text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback); - return text; -} - - -var _DoAutoLinks = function(text) { - - text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"
    $1"); - - // Email addresses: - - /* - text = text.replace(/ - < - (?:mailto:)? - ( - [-.\w]+ - \@ - [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+ - ) - > - /gi, _DoAutoLinks_callback()); - */ - text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi, - function(wholeMatch,m1) { - return _EncodeEmailAddress( _UnescapeSpecialChars(m1) ); - } - ); - - return text; -} - - -var _EncodeEmailAddress = function(addr) { -// -// Input: an email address, e.g. "foo@example.com" -// -// Output: the email address as a mailto link, with each character -// of the address encoded as either a decimal or hex entity, in -// the hopes of foiling most address harvesting spam bots. E.g.: -// -// foo -// @example.com -// -// Based on a filter by Matthew Wickline, posted to the BBEdit-Talk -// mailing list: -// - - // attacklab: why can't javascript speak hex? - function char2hex(ch) { - var hexDigits = '0123456789ABCDEF'; - var dec = ch.charCodeAt(0); - return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15)); - } - - var encode = [ - function(ch){return "&#"+ch.charCodeAt(0)+";";}, - function(ch){return "&#x"+char2hex(ch)+";";}, - function(ch){return ch;} - ]; - - addr = "mailto:" + addr; - - addr = addr.replace(/./g, function(ch) { - if (ch == "@") { - // this *must* be encoded. I insist. - ch = encode[Math.floor(Math.random()*2)](ch); - } else if (ch !=":") { - // leave ':' alone (to spot mailto: later) - var r = Math.random(); - // roughly 10% raw, 45% hex, 45% dec - ch = ( - r > .9 ? encode[2](ch) : - r > .45 ? encode[1](ch) : - encode[0](ch) - ); - } - return ch; - }); - - addr = "" + addr + ""; - addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part - - return addr; -} - - -var _UnescapeSpecialChars = function(text) { -// -// Swap back in all the special characters we've hidden. -// - text = text.replace(/~E(\d+)E/g, - function(wholeMatch,m1) { - var charCodeToReplace = parseInt(m1); - return String.fromCharCode(charCodeToReplace); - } - ); - return text; -} - - -var _Outdent = function(text) { -// -// Remove one level of line-leading tabs or spaces -// - - // attacklab: hack around Konqueror 3.5.4 bug: - // "----------bug".replace(/^-/g,"") == "bug" - - text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width - - // attacklab: clean up hack - text = text.replace(/~0/g,"") - - return text; -} - -var _Detab = function(text) { -// attacklab: Detab's completely rewritten for speed. -// In perl we could fix it by anchoring the regexp with \G. -// In javascript we're less fortunate. - - // expand first n-1 tabs - text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width - - // replace the nth with two sentinels - text = text.replace(/\t/g,"~A~B"); - - // use the sentinel to anchor our regex so it doesn't explode - text = text.replace(/~B(.+?)~A/g, - function(wholeMatch,m1,m2) { - var leadingText = m1; - var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width - - // there *must* be a better way to do this: - for (var i=0; i)[^\t]*)'/g, "$1\r") - .replace(/\t=(.*?)%>/g, "',$1,'") - .split("\t").join("');") - .split("%>").join("p.push('") - .split("\r").join("\\'") - + "');}return p.join('');"); - - // Provide some basic currying to the user - return data ? fn( data ) : fn; - }; -}()); diff --git a/bin/blog.rb b/bin/blog.rb deleted file mode 100755 index 8e32447..0000000 --- a/bin/blog.rb +++ /dev/null @@ -1,262 +0,0 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require 'time' -require 'rubygems' -require 'bundler/setup' -require 'builder' -require 'json' -require 'mustache' -require 'rdiscount' - -DefaultKeywords = ['sjs', 'sami samhuri', 'sami', 'samhuri', 'samhuri.net', 'blog'] - -ShortURLCodeSet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' -ShortURLBase = ShortURLCodeSet.length.to_f - -def main - srcdir = ARGV.shift.to_s - destdir = ARGV.shift.to_s - Dir.mkdir(destdir) unless File.exists?(destdir) - unless File.directory?(srcdir) - puts 'usage: blog.rb ' - exit 1 - end - b = Blag.new srcdir, destdir - puts 'title: ' + b.title - puts 'subtitle: ' + b.subtitle - puts 'url: ' + b.url - puts "#{b.posts.size} posts" - b.generate! - puts 'done blog' -end - -class Blag - attr_accessor :title, :subtitle, :url - - def self.go! src, dest - self.new(src, dest).generate! - end - - def initialize src, dest - @src = src - @dest = dest - @blog_dest = File.join(dest, 'blog') - @css_dest = File.join(dest, 'css') - read_blog - end - - def generate! - generate_posts - generate_index - generate_rss - generate_posts_json - generate_archive - generate_short_urls - copy_assets - end - - def generate_index - # generate landing page - index_template = File.read(File.join('templates', 'blog', 'index.html')) - post = posts.first - values = { :post => post, - :styles => post[:styles], - :article => html(post), - :previous => posts[1], - :filename => post[:filename], - :url => post[:relative_url], - :comments => post[:comments] - } - index_html = Mustache.render(index_template, values) - File.open(File.join(@blog_dest, 'index.html'), 'w') {|f| f.puts(index_html) } - end - - def generate_posts - page_template = File.read(File.join('templates', 'blog', 'post.html')) - posts.each_with_index do |post, i| - values = { :title => post[:title], - :link => post[:link], - :styles => post[:styles], - :article => html(post), - :previous => i < posts.length - 1 && posts[i + 1], - :next => i > 0 && posts[i - 1], - :filename => post[:filename], - :url => post[:relative_url], - :comments => post[:comments], - :keywords => (DefaultKeywords + post[:tags]).join(',') - } - post[:html] = Mustache.render(page_template, values) - File.open(File.join(@blog_dest, post[:filename]), 'w') {|f| f.puts(post[:html]) } - end - end - - def generate_posts_json - json = JSON.generate({ :published => posts.map {|p| p[:filename]} }) - File.open(File.join(@blog_dest, 'posts.json'), 'w') { |f| f.puts(json) } - end - - def generate_archive - archive_template = File.read(File.join('templates', 'blog', 'archive.html')) - html = Mustache.render(archive_template, :posts => posts) - File.open(File.join(@blog_dest, 'archive'), 'w') { |f| f.puts(html) } - end - - def generate_rss - # posts rss - File.open(rss_file, 'w') { |f| f.puts(rss_for_posts.target!) } - end - - def generate_short_urls - htaccess = ['RewriteEngine on', 'RewriteRule ^$ http://samhuri.net [R=301,L]'] - posts.reverse.each_with_index do |post, i| - code = shorten(i + 1) - htaccess << "RewriteRule ^#{code}$ #{post[:url]} [R=301,L]" - end - File.open(File.join(@dest, 's42', '.htaccess'), 'w') do |f| - f.puts(htaccess) - end - end - - def shorten(n) - short = '' - while n > 0 - short = ShortURLCodeSet[n % ShortURLBase, 1] + short - n = (n / ShortURLBase).floor - end - short - end - - def copy_assets - Dir[File.join(@src, 'css', '*.css')].each do |stylesheet| - minified = File.join(@css_dest, File.basename(stylesheet).sub('.css', '.min.css')) - `yui-compressor #{stylesheet} #{minified}` - end - Dir[File.join(@src, 'files', '*')].each do |file| - FileUtils.copy(file, File.join(@dest, 'f', File.basename(file))) - end - Dir[File.join(@src, 'images', '*')].each do |file| - FileUtils.copy(file, File.join(@dest, 'images', 'blog', File.basename(file))) - end - end - - def posts - prefix = File.join(@src, 'published') + '/' - @posts ||= Dir[File.join(prefix, '*')].sort.reverse.map do |filename| - lines = File.readlines(filename) - post = { :filename => filename.sub(prefix, '').sub(/\.(html|m(ark)?d(own)?)$/i, '') } - loop do - line = lines.shift.strip - m = line.match(/^(\w+):/) - if m && param = m[1].downcase - post[param.to_sym] = line.sub(Regexp.new('^' + param + ':\s*', 'i'), '').strip - elsif line.match(/^----\s*$/) - lines.shift while lines.first.strip.empty? - break - else - puts "ignoring unknown header: #{line}" - end - end - post[:type] = post[:link] ? :link : :post - post[:title] += " →" if post[:type] == :link - post[:styles] = (post[:styles] || '').split(/\s*,\s*/) - post[:tags] = (post[:tags] || '').split(/\s*,\s*/) - post[:relative_url] = post[:filename].sub(/\.html$/, '') - post[:url] = @url + '/' + post[:relative_url] - post[:timestamp] = post[:timestamp].to_i - post[:content] = lines.join - post[:body] = RDiscount.new(post[:content], :smart).to_html - post[:rfc822] = Time.at(post[:timestamp]).rfc822 - # comments on by default - post[:comments] = (post[:comments] == 'on' || post[:comments].nil?) - post - end.sort { |a, b| b[:timestamp] <=> a[:timestamp] } - end - - - private - - def blog_file - File.join(@src, 'blog.json') - end - - def read_blog - blog = JSON.parse(File.read(blog_file)) - @title = blog['title'] - @subtitle = blog['subtitle'] - @url = blog['url'] - end - - def html(post) - Mustache.render(template(post[:type]), post) - end - - def template(type) - if type == :post - @post_template ||= File.read(File.join('templates', 'blog', 'post.mustache')) - elsif type == :link - @link_template ||= File.read(File.join('templates', 'blog', 'link.mustache')) - else - raise 'unknown post type: ' + type - end - end - - def rss_template(type) - if type == :post - @post_rss_template ||= File.read(File.join('templates', 'blog', 'post.rss.html')) - elsif type == :link - @link_rss_template ||= File.read(File.join('templates', 'blog', 'link.rss.html')) - else - raise 'unknown post type: ' + type - end - end - - def rss_file - File.join(@blog_dest, 'sjs.rss') - end - - def rss_html(post) - Mustache.render(rss_template(post[:type]), { :post => post }) - end - - def rss_for_posts(options = {}) - title = options[:title] || @title - subtitle = options[:subtitle] || @subtitle - url = options[:url] || @url - rss_posts ||= options[:posts] || posts[0, 10] - - xml = Builder::XmlMarkup.new - xml.instruct! :xml, :version => '1.0' - xml.instruct! 'xml-stylesheet', :href => 'http://samhuri.net/css/blog-all.min.css', :type => 'text/css' - - rss_posts.each do |post| - post[:styles].each do |style| - xml.instruct! 'xml-stylesheet', :href => "http://samhuri.net/css/#{style}.min.css", :type => 'text/css' - end - end - - xml.rss :version => '2.0' do - xml.channel do - xml.title title - xml.description subtitle - xml.link url - xml.pubDate posts.first[:rfc822] - - rss_posts.each do |post| - xml.item do - xml.title post[:title] - xml.description rss_html(post) - xml.pubDate post[:rfc822] - xml.author post[:author] - xml.link post[:link] || post[:url] - xml.guid post[:url] - end - end - end - end - xml - end - -end - -main if $0 == __FILE__ diff --git a/bin/combine.sh b/bin/combine.sh deleted file mode 100755 index 05fd863..0000000 --- a/bin/combine.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env zsh - -### javascript ### - -# blog -echo "request,showdown,strftime,tmpl,jquery-serializeObject,blog -> blog-all.min.js" -cat public/js/{request,showdown,strftime,tmpl,jquery-serializeObject,blog}.min.js >|public/js/blog-all.min.js - -# project index -echo "gitter,store -> proj-index-all.min.js" -cat public/js/{gitter,store}.min.js >|public/js/proj-index-all.min.js - -# projects -echo "gitter,store,proj -> proj-all.min.js" -cat public/js/{gitter,store,proj}.min.js >|public/js/proj-all.min.js - - -### css ### - -# blog -echo "style,blog -> blog-all.min.css" -cat public/css/{style,blog}.min.css >|public/css/blog-all.min.css - -# project index -echo "style,proj-common -> proj-index-all.min.css" -cat public/css/{style,proj-common}.min.css >|public/css/proj-index-all.min.css - -# projects -echo "style,proj-common,proj -> proj-all.min.css" -cat public/css/{style,proj-common,proj}.min.css >|public/css/proj-all.min.css diff --git a/bin/compile.sh b/bin/compile.sh new file mode 100755 index 0000000..48ad6dc --- /dev/null +++ b/bin/compile.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +harp compile public public + +for FILENAME in public/posts/*.html public/projects/*.html; do + [[ "$FILENAME" = "index.html" ]] && continue + + DIRNAME="${FILENAME%.html}" + mkdir -p "$DIRNAME" + mv "$FILENAME" "$DIRNAME/index.html" +done diff --git a/bin/minify.sh b/bin/minify.sh deleted file mode 100755 index b68826b..0000000 --- a/bin/minify.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env zsh - -setopt extendedglob - -[[ ! -d public/js ]] && mkdir public/js -for js (assets/js/*.js) { - target=public/js/${${js:t}%.js}.min.js - if [ ! -f $target ] || [ $js -nt $target ]; then - echo "$js -> $target" - closure < $js >| $target - fi -} - -[[ ! -d public/css ]] && mkdir public/css -for css (assets/css/*.css) { - target=public/css/${${css:t}%.css}.min.css - if [ ! -f $target ] || [ $css -nt $target ]; then - echo "$css -> $target" - yui-compressor $css $target - fi -} diff --git a/bin/posts.rb b/bin/posts.rb new file mode 100755 index 0000000..a5330e8 --- /dev/null +++ b/bin/posts.rb @@ -0,0 +1,188 @@ +#!/usr/bin/env ruby +# encoding: utf-8 + +require 'time' +require 'rubygems' +require 'bundler/setup' +require 'builder' +require 'json' +require 'rdiscount' +require 'mustache' + +DEFAULT_KEYWORDS = %w[samsonjs sjs sami samhuri sami samhuri samhuri.net] + +def main + srcdir = ARGV.shift.to_s + destdir = ARGV.shift.to_s + Dir.mkdir(destdir) unless File.exists?(destdir) + unless File.directory? srcdir + puts 'usage: blog.rb ' + exit 1 + end + b = Blag.new srcdir, destdir + puts 'title: ' + b.title + puts 'subtitle: ' + b.subtitle + puts 'url: ' + b.url + puts "#{b.posts.size} posts" + b.generate! + puts 'done blog' +end + +class Blag + attr_accessor :title, :subtitle, :url + + def self.go! src, dest + self.new(src, dest).generate! + end + + def initialize src, dest + @src = src + @dest = dest + read_blog + end + + def generate! + generate_posts_json + generate_rss + end + + def generate_posts_json + posts_data = posts.reverse.inject({}) do |all, p| + all[p[:slug]] = { + title: p[:title], + date: p[:date], + timestamp: p[:timestamp], + tags: p[:tags], + author: p[:author], + url: p[:relative_url], + link: p[:link], + styles: p[:styles] + }.delete_if { |k, v| v.nil? } + + all + end + json = JSON.pretty_generate posts_data + filename = File.join @dest, 'posts', '_data.json' + File.open(filename, 'w') { |f| f.puts json } + + filename = File.join @dest, '_data.json' + data = JSON.parse File.read(filename) + post = latest_post + data['latest'] = posts_data[post[:slug]].merge('body' => post[:body]) + json = JSON.pretty_generate data + File.open(filename, 'w') { |f| f.puts json } + end + + def generate_rss + # posts rss + File.open(rss_file, 'w') { |f| f.puts rss_for_posts.target! } + end + + def latest_post + posts.first + end + + def posts + prefix = @src + '/posts/' + @posts ||= Dir[File.join(prefix, '*')].sort.reverse.map do |filename| + next if File.directory?(filename) || filename =~ /_data\.json/ + + lines = File.readlines filename + post = { + slug: filename.sub(prefix, '').sub(/\.(html|md)$/i, '') + } + loop do + line = lines.shift.strip + m = line.match /^(\w+):/ + if m && param = m[1].downcase + post[param.to_sym] = line.sub(Regexp.new('^' + param + ':\s*', 'i'), '').strip + elsif line.match /^----\s*$/ + lines.shift while lines.first.strip.empty? + break + else + puts "ignoring unknown header: #{line}" + end + end + if post[:styles] + post[:styles] = post[:styles].split(/\s*,\s*/) + end + post[:type] = post[:link] ? :link : :post + post[:title] += " →" if post[:type] == :link + post[:tags] = (post[:tags] || '').split(/\s*,\s*/) + post[:relative_url] = '/posts/' + post[:slug] + post[:url] = @url + post[:relative_url] + post[:timestamp] = post[:timestamp].to_i + post[:content] = lines.join + post[:body] = RDiscount.new(post[:content], :smart).to_html + post[:rfc822] = Time.at(post[:timestamp]).rfc822 + post + end.compact.sort { |a, b| b[:timestamp] <=> a[:timestamp] } + end + + + private + + def blog_file + File.join(@src, '_data.json') + end + + def read_blog + blog = JSON.parse(File.read(blog_file)) + @title = blog['title'] + @subtitle = blog['subtitle'] + @url = blog['url'] + end + + def rss_template(type) + if type == :post + @post_rss_template ||= File.read(File.join('templates', 'post.rss.html')) + elsif type == :link + @link_rss_template ||= File.read(File.join('templates', 'link.rss.html')) + else + raise 'unknown post type: ' + type + end + end + + def rss_file + File.join @dest, 'sjs.rss' + end + + def rss_html post + Mustache.render rss_template(post[:type]), post: post + end + + def rss_for_posts options = {} + title = options[:title] || @title + subtitle = options[:subtitle] || @subtitle + url = options[:url] || @url + rss_posts ||= options[:posts] || posts[0, 10] + + xml = Builder::XmlMarkup.new + xml.instruct! :xml, :version => '1.0' + xml.instruct! 'xml-stylesheet', :href => 'http://samhuri.net/css/style.css', :type => 'text/css' + + xml.rss :version => '2.0' do + xml.channel do + xml.title title + xml.description subtitle + xml.link url + xml.pubDate posts.first[:rfc822] + + rss_posts.each do |post| + xml.item do + xml.title post[:title] + xml.description rss_html(post) + xml.pubDate post[:rfc822] + xml.author post[:author] + xml.link post[:link] || post[:url] + xml.guid post[:url] + end + end + end + end + xml + end + +end + +main if $0 == __FILE__ diff --git a/bin/projects.js b/bin/projects.js deleted file mode 100755 index 65f0c31..0000000 --- a/bin/projects.js +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env node - -var fs = require('fs') - , path = require('path') - , mustache = require('mustache') - - , rootDir = path.join(__dirname, '..') - , projectFile = path.join(rootDir, process.argv[2]) - , templateDir = path.join(rootDir, 'templates', 'proj') - , targetDir = path.join(rootDir, process.argv[3]) - -try { - fs.mkdirSync(targetDir, 0775) -} -catch (e) { - if (e.code != 'EEXIST') throw e -} - -function main() { - var ctx = {} - fs.readFile(path.join(templateDir, 'project.html'), function(err, html) { - if (err) throw err - ctx.template = html.toString() - fs.readFile(projectFile, function(err, json) { - if (err) throw err - var projects = JSON.parse(json).projects - , index = path.join(targetDir, 'index.html') - - // write project index - fs.readFile(path.join(templateDir, 'index.html'), function(err, tpl) { - if (err) throw err - fs.mkdir(targetDir, 0775, function(err) { - if (err && err.code !== 'EEXIST') throw err - fs.unlink(index, function(err) { - if (err && err.code !== 'ENOENT') throw err - var vals = { projects: projects } - , html = mustache.to_html(tpl.toString(), vals) - fs.writeFile(index, html, function(err) { - if (err) throw err - console.log('* (project index)') - }) - }) - }) - }) - - // write project pages - ctx.n = 0 - projects.forEach(function(project) { - ctx.n += 1 - buildProject(project.name, project, ctx) - }) - }) - }) -} - -function buildProject(name, project, ctx) { - var dir = path.join(targetDir, name) - , index = path.join(dir, 'index.html') - - try { - fs.mkdirSync(dir, 0775) - } - catch (e) { - if (e.code != 'EEXIST') throw e - } - - fs.unlink(index, function(err) { - if (err && err.code !== 'ENOENT') throw err - project.name = name - fs.writeFile(index, mustache.to_html(ctx.template, project), function(err) { - if (err) console.error('error: ', err.message) - ctx.n -= 1 - console.log('* ' + name + (err ? ' (failed)' : '')) - if (ctx.n === 0) console.log('done projects') - }) - }) -} - -if (module == require.main) main() diff --git a/bin/publish.sh b/bin/publish.sh index 4a2eb4f..5e5f8b7 100755 --- a/bin/publish.sh +++ b/bin/publish.sh @@ -1,13 +1,13 @@ #!/bin/bash +# exit on errors +set -e + bail() { echo fail: $* exit 1 } -# exit on errors -set -e - publish_host=samhuri.net publish_dir=samhuri.net/public/ diff --git a/discussd/discussd.js b/discussd/discussd.js deleted file mode 100755 index cfd7091..0000000 --- a/discussd/discussd.js +++ /dev/null @@ -1,343 +0,0 @@ -#!/usr/bin/env node - -var fs = require('fs') - , http = require('http') - , path = require('path') - , parseURL = require('url').parse - , keys = require('keys') - , markdown = require('markdown') - , strftime = require('strftime').strftime - , DefaultOptions = { host: 'localhost' - , port: 2020 - , postsFile: path.join(__dirname, 'posts.json') - } - -function main() { - var options = parseArgs(DefaultOptions) - , db = new keys.Dirty('./discuss.dirty') - , context = { db: db - , posts: null - } - , server = http.createServer(requestHandler(context)) - , loadPosts = function(cb) { - readJSON(options.postsFile, function(err, posts) { - if (err) { - console.error('failed to parse posts file, is it valid JSON?') - console.dir(err) - process.exit(1) - } - if (context.posts === null) { - var n = posts.published.length - , t = strftime('%Y-%m-%d %I:%M:%S %p') - console.log('(' + t + ') ' + 'loaded discussions for ' + n + ' posts...') - } - context.posts = posts.published - if (typeof cb == 'function') cb() - }) - } - , listen = function() { - console.log(process.argv[0] + ' listening on ' + options.host + ':' + options.port) - server.listen(options.port, options.host) - } - loadPosts(function() { - fs.watchFile(options.postsFile, loadPosts) - if (db._loaded) { - listen() - } else { - db.db.on('load', listen) - } - }) -} - -function readJSON(f, cb) { - fs.readFile(f, function(err, buf) { - var data - if (!err) { - try { - data = JSON.parse(buf.toString()) - } catch (e) { - err = e - } - } - cb(err, data) - }) -} - -// returns a request handler that returns a string -function createTextHandler(options) { - if (typeof options === 'string') { - options = { body: options } - } else { - options = options || {} - } - var body = options.body || '' - , code = options.cody || 200 - , type = options.type || 'text/plain' - , n = body.length - return function(req, res) { - var headers = res.headers || {} - headers['content-type'] = type - headers['content-length'] = n - -// console.log('code: ', code) -// console.log('headers: ', JSON.stringify(headers, null, 2)) -// console.log('body: ', body) - - res.writeHead(code, headers) - res.end(body) - } -} - -// Cross-Origin Resource Sharing -var createCorsHandler = (function() { - var AllowedOrigins = [ 'http://samhuri.net' ] - - return function(handler) { - handler = handler || createTextHandler('ok') - return function(req, res) { - var origin = req.headers.origin - console.log('origin: ', origin) - console.log('index: ', AllowedOrigins.indexOf(origin)) - if (AllowedOrigins.indexOf(origin) !== -1) { - res.headers = { 'Access-Control-Allow-Origin': origin - , 'Access-Control-Request-Method': 'POST, GET' - , 'Access-Control-Allow-Headers': 'content-type' - } - handler(req, res) - } else { - BadRequest(req, res) - } - } - } -}()) - -var DefaultHandler = createTextHandler({ code: 404, body: 'not found' }) - , BadRequest = createTextHandler({ code: 400, body: 'bad request' }) - , ServerError = createTextHandler({ code: 500, body: 'server error' }) - , _routes = {} - -function route(method, pattern, handler) { - if (typeof pattern === 'function' && !handler) { - handler = pattern - pattern = '' - } - if (!pattern || typeof pattern.exec !== 'function') { - pattern = new RegExp('^/' + pattern) - } - var route = { pattern: pattern, handler: handler } - console.log('routing ' + method, pattern) - if (!(method in _routes)) _routes[method] = [] - _routes[method].push(route) -} - -function resolve(method, path) { - var rs = _routes[method] - , i = rs.length - , m - , r - while (i--) { - r = rs[i] - m = r.pattern.exec ? r.pattern.exec(path) : path.match(r.pattern) - if (m) return r.handler - } - console.warn('*** using default handler, this is probably not what you want') - return DefaultHandler -} - -function get(pattern, handler) { - route('GET', pattern, handler) -} - -function post(pattern, handler) { - route('POST', pattern, handler) -} - -function options(pattern, handler) { - route('OPTIONS', pattern, handler) -} - -function handleRequest(req, res) { - var handler = resolve(req.method, req.url) - try { - handler(req, res) - } catch (e) { - console.error('!!! error handling ' + req.method, req.url) - console.dir(e) - } -} - -function commentServer(context) { - return { get: getComments - , count: countComments - , post: postComment - } - - function addComment(post, name, email, url, body, timestamp) { - var comments = context.db.get(post) || [] - comments.push({ id: comments.length + 1 - , name: name - , email: email - , url: url - , body: body - , timestamp: timestamp || Date.now() - }) - context.db.set(post, comments) - console.log('[' + timestamp + '] comment on ' + post) - console.log('name:', name) - console.log('email:', email) - console.log('url:', url) - console.log('body:', body) - } - - function getComments(req, res) { - var post = parseURL(req.url).pathname.replace(/^\/comments\//, '') - , comments - if (context.posts.indexOf(post) === -1) { - console.warn('post not found: ' + post) - BadRequest(req, res) - return - } - comments = context.db.get(post) || [] - comments.forEach(function(c, i) { - c.id = c.id || (i + 1) - }) - res.respond({comments: comments.map(function(c) { - delete c.email - c.html = markdown.parse(c.body) - // FIXME discount has a race condition, sometimes gives a string - // with trailing garbage. - while (c.html.charAt(c.html.length - 1) !== '>') { - console.log("!!! removing trailing garbage from discount's html") - c.html = c.html.slice(0, c.html.length - 1) - } - return c - })}) - } - - function postComment(req, res) { - var body = '' - req.on('data', function(chunk) { body += chunk }) - req.on('end', function() { - var data, post, name, email, url, timestamp - try { - data = JSON.parse(body) - } catch (e) { - console.log('not json -> ' + body) - BadRequest(req, res) - return - } - post = (data.post || '').trim() - name = (data.name || 'anonymous').trim() - email = (data.email || '').trim() - url = (data.url || '').trim() - if (url && !url.match(/^https?:\/\//)) url = 'http://' + url - body = data.body || '' - if (!post || !body || context.posts.indexOf(post) === -1) { - console.warn('mising post, body, or post not found: ' + post) - console.warn('body: ', body) - BadRequest(req, res) - return - } - timestamp = +data.timestamp || Date.now() - addComment(post, name, email, url, body, timestamp) - res.respond() - }) - } - - function countComments(req, res) { - var post = parseURL(req.url).pathname.replace(/^\/count\//, '') - , comments - if (context.posts.indexOf(post) === -1) { - console.warn('post not found: ' + post) - BadRequest(req, res) - return - } - comments = context.db.get(post) || [] - res.respond({count: comments.length}) - } -} - -function requestHandler(context) { - var comments = commentServer(context) - get(/comments\//, createCorsHandler(comments.get)) - get(/count\//, createCorsHandler(comments.count)) - post(/comment\/?/, createCorsHandler(comments.post)) - options(createCorsHandler()) - - return function(req, res) { - console.log(req.method + ' ' + req.url) - res.respond = function(obj) { - var s = '' - var headers = res.headers || {} - if (obj) { - try { - s = JSON.stringify(obj) - } catch (e) { - ServerError(req, res) - return - } - headers['content-type'] = 'application/json' - } - headers['content-length'] = s.length - - /* - console.log('code: ', s ? 200 : 204) - console.log('headers:', headers) - console.log('body:', s) - */ - - res.writeHead(s ? 200 : 204, headers) - res.end(s) - } - handleRequest(req, res) - } -} - -function parseArgs(defaults) { - var expectingArg - , options = Object.keys(defaults).reduce(function(os, k) { - os[k] = defaults[k] - return os - }, {}) - process.argv.slice(2).forEach(function(arg) { - if (expectingArg) { - options[expectingArg] = arg - expectingArg = null - } else { - // remove leading dashes - while (arg.charAt(0) === '-') { - arg = arg.slice(1) - } - switch (arg) { - case 'h': - case 'host': - expectingArg = 'host' - break - - case 'p': - case 'port': - expectingArg = 'port' - break - - default: - console.warn('unknown option: ' + arg + ' (setting anyway)') - expectingArg = arg - } - } - }) - return options -} - -var missingParams = (function() { - var requiredParams = 'name email body'.split(' ') - return function(d) { - var anyMissing = false - requiredParams.forEach(function(p) { - var v = (d[p] || '').trim() - if (!v) anyMissing = true - }) - return anyMissing - } -}()) - -if (module == require.main) main() diff --git a/discussd/package.json b/discussd/package.json deleted file mode 100644 index 1b8f65c..0000000 --- a/discussd/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ "name" : "discussd" -, "description" : "comment server" -, "version" : "1.0.0" -, "homepage" : "http://samhuri.net/proj/samhuri.net" -, "author" : "Sami Samhuri " -, "repository" : - { "type" : "git" - , "url" : "https://github.com/samsonjs/samhuri.net.git" - } -, "bugs" : - { "mail" : "sami@samhuri.net" - , "url" : "https://github.com/samsonjs/samhuri.net/issues" - } -, "dependencies" : - { "dirty" : "0.9.x" - , "keys" : "0.1.x" - , "markdown" : "0.5.x" - , "strftime" : "0.6.x" - } -, "bin" : { "discussd" : "./discussd/discussd.js" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : - [ { "type" : "MIT" - , "url" : "http://github.com/samsonjs/samhuri.net/raw/master/LICENSE" - } - ] -} diff --git a/f/CappuccinoIssue725.zip b/f/CappuccinoIssue725.zip deleted file mode 100644 index bc4ff3b..0000000 Binary files a/f/CappuccinoIssue725.zip and /dev/null differ diff --git a/f/MacBookPro6,2-SSD.geekbench b/f/MacBookPro6,2-SSD.geekbench deleted file mode 100644 index bab62b4..0000000 --- a/f/MacBookPro6,2-SSD.geekbench +++ /dev/null @@ -1,172 +0,0 @@ - -5713 -21.8 - - - - - - - - - - - - - - - - - - - - - - - - -
    -4470 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -
    -8587 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -
    -4145 - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -
    -3150 - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -
    -
    diff --git a/f/MacBookPro6,2-SSD.xbench b/f/MacBookPro6,2-SSD.xbench deleted file mode 100644 index 8ff6441..0000000 Binary files a/f/MacBookPro6,2-SSD.xbench and /dev/null differ diff --git a/f/MacBookPro6,2.xbench b/f/MacBookPro6,2.xbench deleted file mode 100644 index 48344e8..0000000 Binary files a/f/MacBookPro6,2.xbench and /dev/null differ diff --git a/f/fiveshift.css b/f/fiveshift.css deleted file mode 100644 index 6024a44..0000000 --- a/f/fiveshift.css +++ /dev/null @@ -1,47 +0,0 @@ - -/* Fluid widths */ - -body -{ width: 100% -; min-width: 0 -; font-size: 80% -} - -#masthead -{ width: 100% } - -#masthead .grid_24 -{ text-align: center } - -#header .container_24, -#footer .container_24 -#masthead .container_24, /* doesn't seem to work */ -#content .container_24, /* doesn't seem to work */ -#content .container_24 .grid_15, /* doesn't seem to work */ -.sidebar, /* doesn't seem to work */ -{ width: 97% } - -#masthead .grid_24 { width: 97% } -#masthead .grid_24 .grid_7 { width: 100%; margin-bottom: 1em } -#masthead .grid_24 .grid_11 { width: 95% } -#masthead .hosts { width: 100%; padding-right: 10px } - -#masthead .hosts .host -{ width: 44% -; display: inline-block -; float: none -; clear: left -} - -#episode { min-height: 0 } -#episode h2 { font-size: 1.4em } -h5, #episode h5 { font-size: 0.8em; line-height: 1.2em } - -#episode p, -#episode #sponsors -{ font-size: 0.7em; line-height: 1.3em } - -#episode #episode_links { font-size: 0.7em; line-height: 1.2em } - -.player { width: 100% } -.player .transport { width: 65% } diff --git a/f/fiveshift.js b/f/fiveshift.js deleted file mode 100644 index 19c770c..0000000 --- a/f/fiveshift.js +++ /dev/null @@ -1,26 +0,0 @@ -if (!window.__fiveShiftInjected__) { - window.__fiveShiftInjected__ = true - - $(function() { - - // load custom css - var head = document.getElementsByTagName('head')[0] - , css = document.createElement('link') - css.rel = 'stylesheet' - css.type = 'text/css' - css.href = 'http://samhuri.net/f/fiveshift.css?t=' + +new Date() - head.appendChild(css) - - // These don't center properly via CSS for some reason - ;[ '#masthead .container_24' - , '#content .container_24' - , '#content .container_24 .grid_15' - , '.sidebar' - ].forEach(function(selector) { - $(selector).css('width', '97%') - }) - - // Fix up the viewport - $('meta[name="viewport"]').attr('content','width=device-width,initial-scale=1.0') - }) -} diff --git a/f/frank_abagnale_jr.pdf b/f/frank_abagnale_jr.pdf deleted file mode 100644 index 0c4d9ab..0000000 Binary files a/f/frank_abagnale_jr.pdf and /dev/null differ diff --git a/f/hi.js b/f/hi.js deleted file mode 100644 index 8e56b21..0000000 --- a/f/hi.js +++ /dev/null @@ -1 +0,0 @@ -alert('hi') diff --git a/harp.json b/harp.json new file mode 100644 index 0000000..76dbb39 --- /dev/null +++ b/harp.json @@ -0,0 +1,7 @@ +{ + "globals": { + "site": "samhuri.net", + "author": "Sami Samhuri", + "url": "http://samhuri.net" + } +} \ No newline at end of file diff --git a/assets/apple-touch-icon.acorn b/images/apple-touch-icon.acorn similarity index 100% rename from assets/apple-touch-icon.acorn rename to images/apple-touch-icon.acorn diff --git a/assets/s.acorn b/images/s.acorn similarity index 100% rename from assets/s.acorn rename to images/s.acorn diff --git a/assets/sjs.acorn b/images/sjs.acorn similarity index 100% rename from assets/sjs.acorn rename to images/sjs.acorn diff --git a/package.json b/package.json deleted file mode 100644 index 6cb8908..0000000 --- a/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ "name" : "samhuri.net" -, "description" : "samhuri.net" -, "version" : "1.0.0" -, "homepage" : "http://samhuri.net/proj/samhuri.net" -, "author" : "Sami Samhuri " -, "repository" : - { "type" : "git" - , "url" : "https://github.com/samsonjs/samhuri.net.git" - } -, "bugs" : - { "mail" : "sami@samhuri.net" - , "url" : "https://github.com/samsonjs/samhuri.net/issues" - } -, "dependencies" : { "mustache" : "0.3.x" } -, "bin" : { "discussd" : "./discussd/discussd.js" } -, "engines" : { "node" : ">=0.2.0" } -, "licenses" : - [ { "type" : "MIT" - , "url" : "http://github.com/samsonjs/samhuri.net/raw/master/LICENSE" - } - ] -} diff --git a/projects.json b/projects.json deleted file mode 100644 index 28a17da..0000000 --- a/projects.json +++ /dev/null @@ -1,45 +0,0 @@ -{ "projects" : - [ { "name" : "strftime" - , "description" : "strftime for JavaScript" - } - , { "name" : "bin" - , "description" : "~/bin" - } - , { "name" : "compiler" - , "description" : "an x86 compiler written in ruby" - } - , { "name" : "config" - , "description" : "important dot files (zsh, emacs, vim, screen)" - } - , { "name" : "format" - , "description" : "printf for JavaScript" - } - , { "name" : "gitter" - , "description" : "a GitHub client for Node (v3 API)" - } - , { "name" : "samhuri.net" - , "description" : "this site" - } - , { "name" : "ThePusher" - , "description" : "Github post receive hook router" - } - , { "name" : "lake" - , "description" : "A simple implementation of Scheme in C" - } - , { "name" : "mojo.el" - , "description" : "turn emacs into a sweet mojo editor" - } - , { "name" : "NorthWatcher" - , "description" : "cron for filesystem changes" - } - , { "name" : "batteries" - , "description" : "a general purpose node library" - } - , { "name" : "repl-edit" - , "description" : "edit Node repl commands with your text editor" - } - , { "name" : "cheat.el" - , "description" : "cheat from emacs" - } - ] -} diff --git a/public/.htaccess b/public/.htaccess index 6552181..16691c7 100644 --- a/public/.htaccess +++ b/public/.htaccess @@ -7,6 +7,10 @@ SetOutputFilter DEFLATE ExpiresActive On ExpiresDefault A259200 + + Options Indexes FollowSymLinks MultiViews + + # Set up caching on media files for 1 month ExpiresDefault A2419200 @@ -19,3 +23,7 @@ ExpiresDefault A259200 ExpiresDefault A1209600 Header append Cache-Control "private, must-revalidate" + +Redirect 301 /proj/ /projects/ +Redirect 301 /blog/sjs.rss /sjs.rss +Redirect 301 /blog/ /posts/ diff --git a/public/404.md b/public/404.md new file mode 100644 index 0000000..7c57d9e --- /dev/null +++ b/public/404.md @@ -0,0 +1 @@ +

    four oh four

    diff --git a/Chalk/chalk.js b/public/Chalk/chalk.js similarity index 100% rename from Chalk/chalk.js rename to public/Chalk/chalk.js diff --git a/Chalk/images/background.jpg b/public/Chalk/images/background.jpg similarity index 100% rename from Chalk/images/background.jpg rename to public/Chalk/images/background.jpg diff --git a/Chalk/images/chalk-sprites.png b/public/Chalk/images/chalk-sprites.png similarity index 100% rename from Chalk/images/chalk-sprites.png rename to public/Chalk/images/chalk-sprites.png diff --git a/Chalk/images/chalk-tile-erase.jpg b/public/Chalk/images/chalk-tile-erase.jpg similarity index 100% rename from Chalk/images/chalk-tile-erase.jpg rename to public/Chalk/images/chalk-tile-erase.jpg diff --git a/Chalk/images/chalk-tile-red.png b/public/Chalk/images/chalk-tile-red.png similarity index 100% rename from Chalk/images/chalk-tile-red.png rename to public/Chalk/images/chalk-tile-red.png diff --git a/Chalk/images/chalk-tile-white.png b/public/Chalk/images/chalk-tile-white.png similarity index 100% rename from Chalk/images/chalk-tile-white.png rename to public/Chalk/images/chalk-tile-white.png diff --git a/Chalk/images/chalk.png b/public/Chalk/images/chalk.png similarity index 100% rename from Chalk/images/chalk.png rename to public/Chalk/images/chalk.png diff --git a/Chalk/index.html b/public/Chalk/index.html similarity index 100% rename from Chalk/index.html rename to public/Chalk/index.html diff --git a/Chalk/stylesheets/chalk.css b/public/Chalk/stylesheets/chalk.css similarity index 100% rename from Chalk/stylesheets/chalk.css rename to public/Chalk/stylesheets/chalk.css diff --git a/Chalk/zepto.min.js b/public/Chalk/zepto.min.js similarity index 100% rename from Chalk/zepto.min.js rename to public/Chalk/zepto.min.js diff --git a/public/_data.json b/public/_data.json new file mode 100644 index 0000000..1e83ea8 --- /dev/null +++ b/public/_data.json @@ -0,0 +1,16 @@ +{ + "title": "samhuri.net", + "subtitle": "words mean things", + "url": "http://samhuri.net", + "latest": { + "title": "Structure of an Ember app", + "date": "February 3, 2014", + "timestamp": 1391479549, + "tags": [ + "ember.js" + ], + "author": "sjs", + "url": "/posts/2014.02.03-ember-structure", + "body": "

    I made a diagram of an Ember app. There’s a discussion about it on the\nEmber Discussion Forum. Here is the source file, created with OmniGraffle: Ember structure.graffle

    \n\n

    \"Structure

    \n" + } +} diff --git a/public/_layout.ejs b/public/_layout.ejs new file mode 100644 index 0000000..48834a5 --- /dev/null +++ b/public/_layout.ejs @@ -0,0 +1,53 @@ + + + + + <% if (typeof title != 'undefined') { %> + <%= title %> - <%= site %> + <% } else { %> + <%= site %> + <% } %> + + + + + + + + + + +
    +

    samhuri.net

    +
    + + + + <%- yield %> + + + + + + + diff --git a/templates/blog/link.mustache b/public/_link.ejs similarity index 100% rename from templates/blog/link.mustache rename to public/_link.ejs diff --git a/public/archive.ejs b/public/archive.ejs new file mode 100644 index 0000000..c9d4910 --- /dev/null +++ b/public/archive.ejs @@ -0,0 +1,9 @@ +
      + <% for (var slug in public.posts._data) { %> + <% var post = public.posts._data[slug]; %> +
    • + <%= post.date %> + <%= post.title %> +
    • + <% } %> +
    diff --git a/public/discussions.html b/public/discussions.html deleted file mode 100644 index 7f53000..0000000 --- a/public/discussions.html +++ /dev/null @@ -1,38 +0,0 @@ - - - -discussions - sjs's blog - - - - -
    -
    -

    -

    -

    -

    -

    -

    -

    -
    -
    - - - - - diff --git a/public/images/ch1-Z-G-4.gif b/public/images/ch1-Z-G-4.gif new file mode 100644 index 0000000..c8bada3 Binary files /dev/null and b/public/images/ch1-Z-G-4.gif differ diff --git a/public/images/download.png b/public/images/download.png new file mode 100644 index 0000000..3987548 Binary files /dev/null and b/public/images/download.png differ diff --git a/public/images/keyboard.jpg b/public/images/keyboard.jpg new file mode 100644 index 0000000..406541a Binary files /dev/null and b/public/images/keyboard.jpg differ diff --git a/public/images/menu.png b/public/images/menu.png new file mode 100644 index 0000000..637fda6 Binary files /dev/null and b/public/images/menu.png differ diff --git a/public/index.ejs b/public/index.ejs new file mode 100644 index 0000000..14ac4af --- /dev/null +++ b/public/index.ejs @@ -0,0 +1,9 @@ +<% var post = public._data.latest %> + + diff --git a/public/index.html b/public/index.html deleted file mode 100644 index 9709a5f..0000000 --- a/public/index.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - samhuri.net - - - - - - - - -
    -

    samhuri.net

    -
    - -Fork me on GitHub - - - - - - - - diff --git a/public/json-diff/closed.png b/public/json-diff/closed.png deleted file mode 100644 index 147c717..0000000 Binary files a/public/json-diff/closed.png and /dev/null differ diff --git a/public/json-diff/index.html b/public/json-diff/index.html deleted file mode 100644 index 2e19345..0000000 --- a/public/json-diff/index.html +++ /dev/null @@ -1,258 +0,0 @@ - - - JSON Diff - - - - - - - -

    Courtesy of tlrobinson. -
    - This version differs in that it supports null values,
    - downplays the significance of changed properties with the key key,
    - and provides links to jump from one change to the next.

    - -

    JSON Diff

    -
    -
      -
    • Paste some JSON in each of the text fields. Click "Compare" to see the diff.
    • -
    • Changed portions are displayed in yellow. Additions are displayed in green. Deletions are displayed in red.
    • -
    • It also works as a JSON viewer. Click the disclosure triangles to display/hide portions of the JSON.
    • -
    • Invalid JSON is indicated by the text fields turning red.
    • -
    • Swap the contents of the text areas by clicking "Swap". Clear them by clicking "Clear".
    • -
    -
    -
    - - - - - -
    - -
    -
    -
    -

    About

    -

    JSON Diff is a simple way to visualize and compare JSON.

    -

    Known Issues

    -
      -
    • Diff algorithm not very intelligent when dealing with arrays
    • -
    • Probably doesn't work in IE
    • -
    -
    - -
    -
    -

    - © 2006-2010 Thomas Robinson. Some rights reserved.

    - - - diff --git a/public/json-diff/json-diff.css b/public/json-diff/json-diff.css deleted file mode 100644 index 04dc054..0000000 --- a/public/json-diff/json-diff.css +++ /dev/null @@ -1,73 +0,0 @@ -body { - background-color: lightblue; -} - -#results li > span, #results ul > span { - -moz-border-radius: 5px; - -webkit-border-radius: 5px; - padding-right: 5px; - padding-left: 5px; -} - -#results li { - margin-top: 1px; - padding-left: 15px; -} -#results ul { - padding-left: 15px; - margin-left: -15px; - padding-top: 0px; - margin-top: 0px; - background: url(open.png) no-repeat 2px 5px; - list-style-type: none; -} -#results ul[closed="yes"] { - background: url(closed.png) no-repeat 2px 5px; -} -#results ul[closed="yes"] > * { - display: none; -} -#results ul[closed="yes"] > *:first-child { - display: block; -} -.typeName { - color: gray; -} -.changed { - background-color: #fcff7f; -} -.changed.key { - background-color: #eee; -} - -.added { - background-color: #8bff7f; -} -.removed { - background-color: #fd7f7f; -} - -textarea { - width: 49%; - height: 200px; -} - -.contentbox { - border: 1px dashed black; - background-color: white; - padding: 15px; - margin: 10px; -} - -h2 { - text-align: center; - margin: 0px;; -} - -#results { - padding-left: 40px; -} - -#inputs { - text-align: center; -} \ No newline at end of file diff --git a/public/json-diff/open.png b/public/json-diff/open.png deleted file mode 100644 index 1d48c6a..0000000 Binary files a/public/json-diff/open.png and /dev/null differ diff --git a/public/posts/2006.02.08-first-post.md b/public/posts/2006.02.08-first-post.md new file mode 100644 index 0000000..69e6879 --- /dev/null +++ b/public/posts/2006.02.08-first-post.md @@ -0,0 +1,10 @@ +Title: First Post! +Date: February 8, 2006 +Timestamp: 1139368860 +Author: sjs +Tags: life +---- + +so it's 2am and i should be asleep, but instead i'm setting up a blog. i got a new desk last night and so today i finally got my apartment re-arranged and it's much better now. that's it for now... time to sleep. + +(speaking of sleep, this new sleeping bag design makes so much sense. awesome.) diff --git a/public/posts/2006.02.08-touch-screen-on-steroids.md b/public/posts/2006.02.08-touch-screen-on-steroids.md new file mode 100644 index 0000000..bb32607 --- /dev/null +++ b/public/posts/2006.02.08-touch-screen-on-steroids.md @@ -0,0 +1,14 @@ +Title: Touch Screen on Steroids +Date: February 8, 2006 +Timestamp: 1139407560 +Author: sjs +Tags: technology, touch +---- + +If you thought the PowerBook's two-finger scrolling was cool check out this touch screen: + +Multi-Touch Interaction Research + +> "While touch sensing is commonplace for single points of contact, multi-touch sensing enables a user to interact with a system with more than one finger at a time, as in chording and bi-manual operations. Such sensing devices are inherently also able to accommodate multiple users simultaneously, which is especially useful for larger interaction scenarios such as interactive walls and tabletops." + +This is really amazing. Forget traditional tablet PCs... this is revolutionary and useful in so many applications. I hope this kind of technology is mainstream by 2015. diff --git a/public/posts/2006.02.15-urban-extreme-gymnastics.md b/public/posts/2006.02.15-urban-extreme-gymnastics.md new file mode 100644 index 0000000..882de02 --- /dev/null +++ b/public/posts/2006.02.15-urban-extreme-gymnastics.md @@ -0,0 +1,10 @@ +Title: Urban Extreme Gymnastics? +Date: February 15, 2006 +Timestamp: 1140028860 +Author: sjs +Tags: amusement +---- + +This crazy russian goes all over the place scaling buildings, doing all sorts of flips, bouncing off the walls literally. He'd be impossible to catch. + +Russian parkour (urban extreme gymnastics) diff --git a/public/posts/2006.02.18-girlfriend-x.md b/public/posts/2006.02.18-girlfriend-x.md new file mode 100644 index 0000000..6194e32 --- /dev/null +++ b/public/posts/2006.02.18-girlfriend-x.md @@ -0,0 +1,12 @@ +Title: Girlfriend X +Date: February 18, 2006 +Timestamp: 1140292200 +Author: sjs +Tags: crazy, funny +---- + +This is hilarious! Someone wrote software that manages a "parallel" dating style. + +> In addition to storing each woman's contact information and picture, the Girlfriend profiles include a Score Card where you track her sexual preferences, her menstrual cycles and how she styles her pubic hair. + +It's called [Girlfriend X](http://www.wired.com/news/columns/0,70231-0.html), but that's a link to an article about it. I didn't go to the actual website. I just thing it's amusing someone went through the trouble to do this. Maybe there's a demand for it. *\*shrug\** diff --git a/public/posts/2006.02.18-jump-to-viewcontroller-in-textmate.md b/public/posts/2006.02.18-jump-to-viewcontroller-in-textmate.md new file mode 100644 index 0000000..381afd7 --- /dev/null +++ b/public/posts/2006.02.18-jump-to-viewcontroller-in-textmate.md @@ -0,0 +1,8 @@ +Title: Jump to view/controller in TextMate +Date: February 18, 2006 +Timestamp: 1140303060 +Author: sjs +Tags: hacking, rails, textmate, rails, textmate +---- + +Duane came up with a way to jump to the controller method for the view you're editing, or vice versa in TextMate while coding using Rails. This is a huge time-saver, thanks! diff --git a/public/posts/2006.02.18-some-textmate-snippets-for-rails-migrations.md b/public/posts/2006.02.18-some-textmate-snippets-for-rails-migrations.md new file mode 100644 index 0000000..512f84b --- /dev/null +++ b/public/posts/2006.02.18-some-textmate-snippets-for-rails-migrations.md @@ -0,0 +1,52 @@ +Title: Some TextMate snippets for Rails Migrations +Date: February 18, 2006 +Timestamp: 1140331680 +Author: sjs +Tags: textmate, rails, hacking, rails, snippets, textmate +---- + +My arsenal of snippets and macros in TextMate is building as I read through the rails canon, Agile Web Development... I'm only 150 pages in so I haven't had to add much so far because I started with the bundle found on the rails wiki. The main ones so far are for migrations. + +Initially I wrote a snippet for adding a table and one for dropping a table, but I don't want to write it twice every time! If I'm adding a table in **up** then I probably want to drop it in **down**. + +What I did was create one snippet that writes both lines, then it's just a matter of cut & paste to get it in **down**. The drop_table line should be inserted in the correct method, but that doesn't seem possible. I hope I'm wrong! + +Scope should be *source.ruby.rails* and the triggers I use are above the snippets. + +mcdt: **M**igration **C**reate and **D**rop **T**able + + create_table "${1:table}" do |t| + $0 + end + ${2:drop_table "$1"} + +mcc: **M**igration **C**reate **C**olumn + + t.column "${1:title}", :${2:string} + +marc: **M**igration **A**dd and **R**emove **C**olumn + + add_column "${1:table}", "${2:column}", :${3:string} + ${4:remove_column "$1", "$2"} + +I realize this might not be for everyone, so here are my original 4 snippets that do the work of *marc* and *mcdt*. + +mct: **M**igration **C**reate **T**able + + create_table "${1:table}" do |t| + $0 + end + +mdt: **M**igration **D**rop **T**able + + drop_table "${1:table}" + +mac: **M**igration **A**dd **C**olumn + + add_column "${1:table}", "${2:column}", :${3:string} + +mrc: **M**igration **R**remove **C**olumn + + remove_column "${1:table}", "${2:column}" + +I'll be adding more snippets and macros. There should be a central place where the rails bundle can be improved and extended. Maybe there is... diff --git a/public/posts/2006.02.20-obligatory-post-about-ruby-on-rails.md b/public/posts/2006.02.20-obligatory-post-about-ruby-on-rails.md new file mode 100644 index 0000000..3e7d2d9 --- /dev/null +++ b/public/posts/2006.02.20-obligatory-post-about-ruby-on-rails.md @@ -0,0 +1,215 @@ +Title: Obligatory Post about Ruby on Rails +Date: February 20, 2006 +Timestamp: 1140424260 +Author: sjs +Tags: rails, coding, hacking, migration, rails, testing +Styles: typocode +---- + +

    I'm a Rails newbie and eager to learn. I welcome any suggestions or criticism you have. You can direct them to my inbox or leave me a comment below.

    + +

    I finally set myself up with a blog. I mailed my dad the address and mentioned that it was running Typo, which is written in Ruby on Rails. The fact that it is written in Rails was a big factor in my decision. I am currently reading Agile Web Development With Rails and it will be great to use Typo as a learning tool, since I will be modifying my blog anyways regardless of what language it's written in.

    + +

    Clearly Rails made an impression on me somehow or I wouldn't be investing this time on it. But my dad asked me a very good question:

    + +> Rails? What is so special about it? I looked at your page and it looks pretty normal to me. I miss the point of this new Rails technique for web development. + +

    It's unlikely that he was surprised at my lengthy response, but I was. I have been known to write him long messages on topics that interest me. However, I've only been learning Rails for two weeks or so. Could I possibly have so much to say about it already? Apparently I do.

    Ruby on Rails background

    + + +

    I assume a pretty basic knowledge of what Rails is, so if you're not familiar with it now's a good time to read something on the official Rails website and watch the infamous 15-minute screencast, where Rails creator, David Heinemeier Hansson, creates a simple blog application.

    + + +

    The screencasts are what sparked my curiosity, but they hardly scratch the surface of Rails. After that I spent hours reading whatever I could find about Rails before deciding to take the time to learn it well. As a result, a lot of what you read here will sound familiar if you've read other blogs and articles about Rails. This post wasn't planned so there's no list of references yet. I hope to add some links though so please contact me if any ideas or paraphrasing here is from your site, or if you know who I should give credit to.

    + + +

    Rails through my eyes

    + + +

    Rails is like my Black & Decker toolkit. I have a hammer, power screwdriver, tape measure, needle-nose pliers, wire cutters, a level, etc. This is exactly what I need—no more, no less. It helps me get things done quickly and easily that would otherwise be painful and somewhat difficult. I can pick up the tools and use them without much training. Therefore I am instantly productive with them.

    + + +

    The kit is suitable for many people who need these things at home, such as myself. Companies build skyscrapers and huge malls and apartments, and they clearly need more powerful tools than I. There are others that just need to drive in a nail to hang a picture, in which case the kit I have is overkill. They're better off just buying and using a single hammer. I happen to fall in the big grey middle chunk, not the other two.

    + + +

    I'm a university student. I code because it's satisfying and fun to create software. I do plan on coding for a living when I graduate. I don't work with ancient databases, or create monster sites like Amazon, Google, or Ebay. The last time I started coding a website from scratch I was using PHP, that was around the turn of the millennium. [It was a fan site for a favourite band of mine.]

    + + +

    After a year or so I realized I didn't have the time to do it properly (ie. securely and cleanly) if I wanted it to be done relatively soon. A slightly customized MediaWiki promptly took it's place. It did all that I needed quite well, just in a less specific way.

    + + +

    The wiki is serving my site extremely well, but there's still that itch to create my own site. I feel if Rails was around back then I may have been able to complete the project in a timely manner. I was also frustrated with PHP. Part of that is likely due to a lack of experience and of formal programming education at that time, but it was still not fun for me. It wasn't until I started learning Rails that I thought "hey, I could create that site pretty quickly using this!"

    + + +

    Rails fits my needs like a glove, and this is where it shines. Many professionals are making money creating sites in Rails, so I'm not trying to say it's for amateurs only or something equally silly.

    + + +

    Web Frameworks and iPods?

    + + +

    Some might say I have merely been swept up in hype and am following the herd. You may be right, and that's okay. I'm going to tell you a story. There was a guy who didn't get one of the oh-so-shiny iPods for a long time, though they looked neat. His discman plays mp3 CDs, and that was good enough for him. The latest iPod, which plays video, was sufficiently cool enough for him to forget that everyone at his school has an iPod and he would be trendy just like them now.

    + + +

    Shocker ending: he is I, and I am him. Now I know why everyone has one of those shiny devices. iPods and web frameworks have little in common except that many believe both the iPod and Rails are all hype and flash. I've realized that something creating this kind of buzz may actually just be a good product. I feel that this is the only other thing the iPod and Rails have in common: they are both damn good. Enough about the iPod, everyone hates hearing about it. My goal is to write about the other thing everyone is tired of hearing about.

    + + +

    Why is Rails special?

    + + +

    Rails is not magic. There are no exclusive JavaScript libraries or HTML tags. We all have to produce pages that render in the same web browsers. My dad was correct, there is nothing special about my website either. It's more or less a stock Typo website.

    + + +

    So what makes developing with Rails different? For me there are four big things that set Rails apart from the alternatives:

    + + +
      +
    1. Separating data, function, and design
    2. +
    3. Readability (which is underrated)
    4. +
    5. Database migrations
    6. +
    7. Testing is so easy it hurts
    8. +
    + + +

    MVC 101 (or, Separating data, function, and design)

    + + +

    Now I'm sure you've heard about separating content from design. Rails takes that one step further from just using CSS to style your website. It uses what's known as the MVC paradigm: Model-View-Controller. This is a tried and tested development method. I'd used MVC before in Cocoa programming on Mac OS X, so I was already sold on this point.

    + + +
      +
    • The model deals with your data. If you're creating an online store you have a product model, a shopping cart model, a customer model, etc. The model takes care of storing this data in the database (persistence), and presenting it to you as an object you can manipulate at runtime.
    • +
    + + +
      +
    • The view deals only with presentation. That's it, honestly. An interface to your app.
    • +
    + + +
      +
    • The controller binds the model to the view, so that when the user clicks on the Add to cart link the controller is wired to call the add_product method of the cart model and tell it which product to add. Then the controller takes the appropriate action such as redirecting the user to the shopping cart view.
    • +
    + + +

    Of course this is not exclusive to Rails, but it's an integral part of it's design.

    + + +

    Readability

    + + +

    Rails, and Ruby, both read amazingly like spoken English. This code is more or less straight out of Typo. You define relationships between objects like this:

    + + +
    class Article < Content
    +  has_many :comments, :dependent => true, :order => "created_at ASC"
    +  has_many :trackbacks, :dependent => true, :order => "created_at ASC"
    +  has_and_belongs_to_many :categories, :foreign_key => 'article_id'
    +  has_and_belongs_to_many :tags, :foreign_key => 'article_id'
    +  belongs_to :user
    +  ...
    + +

    dependent => true means if an article is deleted, it's comments go with it. Don't worry if you don't understand it all, this is just for you to see some actual Rails code.

    + + +

    In the Comment model you have:

    + + +
    class Comment < Content
    +  belongs_to :article
    +  belongs_to :user
    +
    +  validates_presence_of :author, :body
    +  validates_against_spamdb :body, :url, :ip
    +  validates_age_of :article_id
    +  ...
    + +

    (I snuck in some validations as well)

    + + +

    But look how it reads! Read it out loud. I'd bet that my mom would more or less follow this, and she's anything but a programmer. That's not to say programming should be easy for grandma, but code should be easily understood by humans. Let the computer understand things that are natural for me to type, since we're making it understand a common language anyways.

    + + +

    Ruby and Ruby on Rails allow and encourage you to write beautiful code. That is so much more important than you may realize, because it leads to many other virtues. Readability is obvious, and hence maintainability. You must read code to understand and modify it. Oh, and happy programmers will be more productive than frustrated programmers.

    + + +

    Database Migrations

    + + +

    Here's one more life-saver: migrations. Migrations are a way to version your database schema from within Rails. So you have a table, call it albums, and you want to add the date the album was released. You could modify the database directly, but that's not fun. Even if you only have one server, all your configuration will be in one central place, the app. And Rails doesn't care if you have PostgreSQL, MySQL, or SQLite behind it. You can develop and test on SQLite and deploy on MySQL and the migrations will just work in both environments.

    + + +
    class AddDateReleased < ActiveRecord::Migration
    +  def self.up
    +    add_column "albums", "date_released", :datetime
    +    Albums.update_all "date_released = now()"
    +  end
    +
    +  def self.down
    +    remove_column "albums", "date_released"
    +  end
    +end
    + +

    Then you run the migration (rake migrate does that) and boom, your up to date. If you're wondering, the self.down method indeed implies that you can take this the other direction as well. Think rake migrate VERSION=X.

    + + +

    Along with the other screencasts is one on migrations featuring none other than David Hansson. You should take a look, it's the third video.

    + + +

    Testing so easy it hurts

    + + +

    To start a rails project you type rails project_name and it creates a directory structure with a fresh project in it. This includes a directory appropriately called test which houses unit tests for the project. When you generate models and controllers it creates test stubs for you in that directory. Basically, it makes it so easy to test that you're a fool not to do it. As someone wrote on their site: It means never having to say "I introduced a new bug while fixing another."

    + + +

    Rails builds on the unit testing that comes with Ruby. On a larger scale, that means that Rails is unlikely to flop on you because it is regularly tested using the same method. Ruby is unlikely to flop for the same reason. That makes me look good as a programmer. If you code for a living then it's of even more value to you.

    + + +

    I don't know why it hurts. Maybe it hurts developers working with other frameworks or languages to see us have it so nice and easy.

    + + +

    Wrapping up

    + + +

    Rails means I have fun doing web development instead of being frustrated (CSS hacks aside). David Hansson may be right when he said you have to have been soured by Java or PHP to fully appreciate Rails, but that doesn't mean you won't enjoy it if you do like Java or PHP.

    + + +

    Justin Gehtland rewrote a Java app using Rails and the number of lines of code of the Rails version was very close to that of the XML configuration for the Java version. Java has strengths, libraries available now seems to be a big one, but it's too big for my needs. If you're like me then maybe you'll enjoy Rails as much as I do.

    + + +

    You're not done, you lied to me!

    + + +

    Sort of... there are a few things that it seems standard to include when someone writes about how Rails saved their life and gave them hope again. For completeness sake, I feel compelled to mention some principles common amongst those who develop Rails, and those who develop on Rails. It's entirely likely that there's nothing new for you here unless you're new to Rails or to programming, in which case I encourage you to read on.

    + + +

    DRY

    + + +

    Rails follows the DRY principle religiously. That is, Don't Repeat Yourself. Like MVC, I was already sold on this. I had previously encountered it in The Pragmatic Programmer. Apart from telling some_model it belongs_to :other_model and other_model that it has_many :some_models nothing has jumped out at me which violates this principle. However, I feel that reading a model's code and seeing it's relationships to other models right there is a Good Thingâ„¢.

    + + +

    Convention over configuration (or, Perceived intelligence)

    + + +

    Rails' developers also have the mantra "convention over configuration", which you can see from the video there. (you did watch it, didn't you? ;) Basically that just means Rails has sane defaults, but is still flexible if you don't like the defaults. You don't have to write even one line of SQL with Rails, but if you need greater control then you can write your own SQL. A standard cliché: it makes the simple things easy and the hard possible.

    + + +

    Rails seems to have a level of intelligence which contributes to the wow-factor. After these relationships are defined I can now filter certain negative comments like so:

    + + +
    article = Article.find :first
    +for comment in article.comments do
    +  print comment unless comment.downcase == 'you suck!'
    +end
    + +

    Rails knows to look for the field article_id in the comments table of the database. This is just a convention. You can call it something else but then you have to tell Rails what you like to call it.

    + + +

    Rails understands pluralization, which is a detail but it makes everything feel more natural. If you have a Person model then it will know to look for the table named people.

    + + +

    Code as you learn

    + + +

    I love how I've only been coding in Rails for a week or two and I can do so much already. It's natural, concise and takes care of the inane details. I love how I know that I don't even have to explain that migration example. It's plainly clear what it does to the database. It doesn't take long to get the basics down and once you do it goes fast.

    + diff --git a/public/posts/2006.02.20-textmate-snippets-for-rails-assertions.md b/public/posts/2006.02.20-textmate-snippets-for-rails-assertions.md new file mode 100644 index 0000000..9977d2f --- /dev/null +++ b/public/posts/2006.02.20-textmate-snippets-for-rails-assertions.md @@ -0,0 +1,16 @@ +Title: TextMate Snippets for Rails Assertions +Date: February 20, 2006 +Timestamp: 1140508320 +Author: sjs +Tags: textmate, rails, coding, rails, snippets, testing, textmate +---- + +This time I've got a few snippets for assertions. Using these to type up your tests quickly, and then hitting **⌘R** to run the tests without leaving TextMate, makes testing your Rails app that much more convenient. Just when you thought it was already too easy! (Don't forget that you can use **⌥⌘↓** to move between your code and the corresponding test case.) + +This time I'm posting the .plist files to make it easier for you to add them to TextMate. All you need to do is copy these to **~/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Snippets**. + +

    Assertion Snippets for Rails

    + +If anyone would rather I list them all here I can do that as well. Just leave a comment. + +*(I wanted to include a droplet in the zip file that will copy the snippets to the right place, but my 3-hour attempt at writing the AppleScript to do so left me feeling quite bitter. Maybe I was just mistaken in thinking it would be easy to pick up AppleScript.)* diff --git a/public/posts/2006.02.21-textmate-insert-text-into-self-down.md b/public/posts/2006.02.21-textmate-insert-text-into-self-down.md new file mode 100644 index 0000000..4cb5522 --- /dev/null +++ b/public/posts/2006.02.21-textmate-insert-text-into-self-down.md @@ -0,0 +1,62 @@ +Title: TextMate: Insert text into self.down +Date: February 21, 2006 +Timestamp: 1140562500 +Author: sjs +Tags: textmate, rails, hacking, commands, macro, rails, snippets, textmate +Styles: typocode +---- + +

    UPDATE: I got everything working and it's all packaged up here. There's an installation script this time as well.

    + +

    Thanks to a helpful thread on the TextMate mailing list I have the beginning of a solution to insert text at 2 (or more) locations in a file.

    + + +

    I implemented this for a new snippet I was working on for migrations, rename_column. Since the command is the same in self.up and self.down simply doing a reverse search for rename_column in my hackish macro didn't return the cursor the desired location.

    That's enough introduction, here's the program to do the insertion:

    + + +
    #!/usr/bin/env ruby
    +def indent(s)
    +  s =~ /^(\s*)/
    +  ' ' * $1.length
    +end
    +
    +up_line = 'rename_column "${1:table}", "${2:column}", "${3:new_name}"$0'
    +down_line = "rename_column \"$$1\", \"$$3\", \"$$2\"\n"
    +
    +# find the end of self.down and insert 2nd line
    +lines = STDIN.read.to_a.reverse
    +ends_seen = 0
    +lines.each_with_index do |line, i|
    +  ends_seen += 1    if line =~ /^\s*end\b/
    +  if ends_seen == 2
    +    lines[i..i] = [lines[i], indent(lines[i]) * 2 + down_line]
    +    break
    +  end
    +end
    +
    +# return the new text, escaping special chars
    +print up_line + lines.reverse.to_s.gsub('[$`\\]', '\\\\\1').gsub('\\$\\$', '$')
    + +

    Save this as a command in your Rails, or syncPeople on Rails, bundle. The command options should be as follows:

    + + +
      +
    • Save: Nothing
    • +
    • Input: Selected Text or Nothing
    • +
    • Output: Insert as Snippet
    • +
    • Activation: Whatever you want, I'm going to use a macro described below and leave this empty
    • +
    • Scope Selector: source.ruby.rails
    • +
    + + +

    The first modification it needs is to get the lines to insert as command line arguments so we can use it for other snippets. Secondly, regardless of the Re-indent pasted text setting the text returned is indented incorrectly.

    + + +The macro I'm thinking of to invoke this is tab-triggered and will simply: +
      +
    • Select word (⌃W)
    • +
    • Delete (⌫)
    • +
    • Select to end of file (⇧⌘↓)
    • +
    • Run command "Put in self.down"
    • +
    + diff --git a/public/posts/2006.02.21-textmate-move-selection-to-self-down.md b/public/posts/2006.02.21-textmate-move-selection-to-self-down.md new file mode 100644 index 0000000..5e96fcb --- /dev/null +++ b/public/posts/2006.02.21-textmate-move-selection-to-self-down.md @@ -0,0 +1,29 @@ +Title: TextMate: Move selection to self.down +Date: February 21, 2006 +Timestamp: 1140510360 +Author: sjs +Tags: textmate, rails, hacking, hack, macro, rails, textmate +---- + +

    UPDATE: This is obsolete, see this post for a better solution.

    + +

    Duane's comment prompted me to think about how to get the drop_table and remove_column lines inserted in the right place. I don't think TextMate's snippets are built to do this sort of text manipulation. It would be nicer, but a quick hack will suffice for now.

    Use MCDT to insert:

    + +
    create_table "table" do |t|
    +
    +end
    +drop_table "table"
    + +

    Then press tab once more after typing the table name to select the code drop_table "table". I created a macro that cuts the selected text, finds def self.down and pastes the line there. Then it searches for the previous occurence of create_table and moves the cursor to the next line, ready for you to add some columns.

    + + +

    I have this bound to ⌃⌥⌘M because it wasn't in use. If your Control key is to the left the A key it's quite comfortable to hit this combo. Copy the following file into ~/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Macros.

    + + +

    Move selection to self.down

    + + +

    This works for the MARC snippet as well. I didn't tell you the whole truth, the macro actually finds the previous occurence of (create_table|add_column).

    + + +

    The caveat here is that if there is a create_table or add_column between self.down and the table you just added, it will jump back to the wrong spot. It's still faster than doing it all manually, but should be improved. If you use these exclusively, the order they occur in self.down will be opposite of that in self.up. That means either leaving things backwards or doing the re-ordering manually. =/

    diff --git a/public/posts/2006.02.22-intelligent-migration-snippets-0.1-for-textmate.md b/public/posts/2006.02.22-intelligent-migration-snippets-0.1-for-textmate.md new file mode 100644 index 0000000..f83345d --- /dev/null +++ b/public/posts/2006.02.22-intelligent-migration-snippets-0.1-for-textmate.md @@ -0,0 +1,44 @@ +Title: Intelligent Migration Snippets 0.1 for TextMate +Date: February 22, 2006 +Timestamp: 1140607680 +Author: sjs +Tags: mac os x, textmate, rails, hacking, migrations, snippets +---- + +*This should be working now. I've tested it under a new user account here.* + +*This does requires the syncPeople bundle to be installed to work. That's ok, because you should get the [syncPeople on Rails bundle][syncPeople] anyways.* + +When writing database migrations in Ruby on Rails it is common to create a table in the `self.up` method and then drop it in `self.down`. The same goes for adding, removing and renaming columns. + +I wrote a Ruby program to insert code into both methods with a single snippet. All the TextMate commands and macros that you need are included. + +### See it in action ### + +I think this looks cool in action. Plus I like to show off what what TextMate can do to people who may not use it, or don't have a Mac. It's just over 30 seconds long and weighs in at around 700kb. + +

    + Download + Download Demo Video +

    + +### Features ### + +There are 3 snippets which are activated by the following tab triggers: + + * __mcdt__: Migration Create and Drop Table + * __marc__: Migration Add and Remove Column + * __mnc__: Migration Rename Column + +### Installation ### + +Run **Quick Install.app** to install these commands to your + Download + Download Intelligent Migration Snippets +

    + +This is specific to Rails migrations, but there are probably other uses for something like this. You are free to use and distribute this code. + +[syncPeople]: http://blog.inquirylabs.com/ diff --git a/public/posts/2006.02.23-sjs-rails-bundle-0.2-for-textmate.md b/public/posts/2006.02.23-sjs-rails-bundle-0.2-for-textmate.md new file mode 100644 index 0000000..ef6bfc6 --- /dev/null +++ b/public/posts/2006.02.23-sjs-rails-bundle-0.2-for-textmate.md @@ -0,0 +1,31 @@ +Title: SJ's Rails Bundle 0.2 for TextMate +Date: February 23, 2006 +Timestamp: 1140743880 +Author: sjs +Tags: textmate, rails, coding, bundle, macros, rails, snippets, textmate +Styles: typocode +---- + +Everything that you've seen posted on my blog is now available in one bundle. Snippets for Rails database migrations and assertions are all included in this bundle. + +There are 2 macros for class-end and def-end blocks, bound to ⌃C and ⌃D respectively. Type the class or method definition, except for class or def, and then type the keyboard shortcut and the rest is filled in for you. + +I use an underscore to denote the position of the cursor in the following example: + + +
    method(arg1, arg2_)
    + +Typing ⌃D at this point results in this code: + + +
    def method(arg1, arg2)
    +  _
    +end
    + +There is a list of the snippets in Features.rtf, which is included in the disk image. Of course you can also browse them in the Snippets Editor built into TextMate. + +Without further ado, here is the bundle: + +

    Download Download SJ's Rails Bundle 0.2

    + +This is a work in progress, so any feedback you have is very helpful in making the next release better. diff --git a/public/posts/2006.03.03-generate-selfdown-in-your-rails-migrations.md b/public/posts/2006.03.03-generate-selfdown-in-your-rails-migrations.md new file mode 100644 index 0000000..35deca5 --- /dev/null +++ b/public/posts/2006.03.03-generate-selfdown-in-your-rails-migrations.md @@ -0,0 +1,8 @@ +Title: Generate self.down in your Rails migrations +Date: March 3, 2006 +Timestamp: 1141450680 +Author: sjs +Tags: rails, textmate, migrations, rails, textmate +---- + +Scott wrote a really cool program that will scan `self.up` and then consult db/schema.rb to automatically fill in `self.down` for you. Brilliant! diff --git a/public/posts/2006.03.03-i-dont-mind-fairplay-either.md b/public/posts/2006.03.03-i-dont-mind-fairplay-either.md new file mode 100644 index 0000000..9b6070c --- /dev/null +++ b/public/posts/2006.03.03-i-dont-mind-fairplay-either.md @@ -0,0 +1,22 @@ +Title: I don't mind FairPlay either +Date: March 3, 2006 +Timestamp: 1141451760 +Author: sjs +Tags: apple, mac os x, life, drm, fairplay, ipod, itunes +---- + +I think that Jim is right about Apple's DRM not being all that evil. + +I buy music from the iTunes Music Store *because* I bought an iPod. The fact I can't play them on another device doesn't matter to me. With my purchased songs I can: + + * listen to the songs I buy all I want + * burn them to CD + * stream them to my amplifier via AirPort Express + +I don't buy a ton of music from the iTMS, but I can't tell the difference between any of those songs and the songs I ripped from CDs and they're all mixed in one collection. That's good enough for me. + +I dislike DRM as much as the next guy, but like CSS encryption on DVDs, FairPlay is something I can live with. + +It reminds me of how here in North America I have to live with the crappy cell phone companies that lock their phones to their networks. If it's something I need or want, sometimes I'll live with restrictions because there are no alternatives yet. + +*__Update:__ It's almost settled. The pope got an iPod so all that's left is to see if he buys any music off of iTunes. If he does, then it can't be evil. heh...* diff --git a/public/posts/2006.03.03-spore.md b/public/posts/2006.03.03-spore.md new file mode 100644 index 0000000..11deefb --- /dev/null +++ b/public/posts/2006.03.03-spore.md @@ -0,0 +1,10 @@ +Title: Spore +Date: March 3, 2006 +Timestamp: 1141450980 +Author: sjs +Tags: amusement, technology, cool, fun, games +---- + +This game that Jim blogged about is probably the coolest game I've seen. + +You really just have to watch the video, I won't bother explaining it here. I don't really play games much, but this I would play. diff --git a/public/posts/2006.04.04-zsh-terminal-goodness-on-os-x.md b/public/posts/2006.04.04-zsh-terminal-goodness-on-os-x.md new file mode 100644 index 0000000..6b6113f --- /dev/null +++ b/public/posts/2006.04.04-zsh-terminal-goodness-on-os-x.md @@ -0,0 +1,10 @@ +Title: zsh terminal goodness on OS X +Date: April 4, 2006 +Timestamp: 1144187820 +Author: sjs +Tags: mac os x, apple, osx, terminal, zsh +---- + +Apple released the OS X 10.4.6 update which fixed a really annoying bug for me. Terminal (and iTerm) would fail to open a new window/tab when your shell is zsh. iTerm would just open then immediately close the window, while Terminal would display the message: [Command completed] in a now-useless window. + +Rebooting twice to get the fix was reminiscent of Windows, but well worth it. diff --git a/public/posts/2006.05.07-os-x-and-fitts-law.md b/public/posts/2006.05.07-os-x-and-fitts-law.md new file mode 100644 index 0000000..6f943e1 --- /dev/null +++ b/public/posts/2006.05.07-os-x-and-fitts-law.md @@ -0,0 +1,8 @@ +Title: OS X and Fitt's law +Date: May 7, 2006 +Timestamp: 1147059780 +Author: sjs +Tags: mac os x, apple, mac, os, usability, x +---- + +I've realized that OS X really does obey Fitt's law in all 4 corners now. Apple menu in the top left, Spotlight top right, and the bottom 2 are always accessible for drag n drop, unless the dock is hidden. I rarely ever use it because I usually have pretty good chunks of the desktop showing, but it is useful. diff --git a/public/posts/2006.05.07-wikipediafs-on-linux-in-python.md b/public/posts/2006.05.07-wikipediafs-on-linux-in-python.md new file mode 100644 index 0000000..485f739 --- /dev/null +++ b/public/posts/2006.05.07-wikipediafs-on-linux-in-python.md @@ -0,0 +1,10 @@ +Title: WikipediaFS on Linux, in Python +Date: May 7, 2006 +Timestamp: 1147060140 +Author: sjs +Tags: hacking, python, linux, fuse, linux, mediawiki, python, wikipediafs +---- + +Till now I've been using my own version of pywikipedia for scripting MediaWiki, and it works well. But I read about WikipediaFS and had to check it out. It's a user space filesystem for Linux that's built using the Python bindings for FUSE. What it does is mounts a filesystem that represents your wiki, with articles as text files. You can use them just like any other files with mv, cp, ls, vim, and so on. + +There hasen't been any action on that project for 13 months though, and it doesn't work on my wiki (MediaWiki 1.4.15) so I'm going to try and make it work after I upgrade to MediaWiki 1.6.3 tonight. This will be pretty cool when it works. I haven't looked at the code yet but it's only 650 lines. diff --git a/public/posts/2006.06.05-ich-bin-auslnder-und-spreche-nicht-gut-deutsch.md b/public/posts/2006.06.05-ich-bin-auslnder-und-spreche-nicht-gut-deutsch.md new file mode 100644 index 0000000..45c6740 --- /dev/null +++ b/public/posts/2006.06.05-ich-bin-auslnder-und-spreche-nicht-gut-deutsch.md @@ -0,0 +1,14 @@ +Title: Ich bin Ausländer und spreche nicht gut Deutsch +Date: June 5, 2006 +Timestamp: 1149527460 +Author: sjs +Tags: life, munich, seekport, work +---- + +How's this for an update: I'm working in Munich for the summer at a European search engine called Seekport. The search engine isn't all they do, as right now I'm programming a desktop widget that shows live scores & news from World Cup matches (in English and Arabic). I'm building it on top of the Yahoo! Widget Engine because it needs to run on Windows. Even though I quite like the Y! Engine, I would still prefer to be coding in straight HTML, CSS & JavaScript like Dashboard programmers get to use. The Y! Engine uses XML (it is somewhat HTML-like) and JavaScript. + +The place I'm living in is like a dormitory for younger people. I share a bathroom & kitchen with a German guy named Sebastian who is 21 and an artist; a stonecutter actually. I only met him briefly yesterday, but he seems nice. I'm going to teach him English, and he'll teach me German, though his English is much better than my German. It's a pretty quiet place, and we get breakfast included, dinner can be bought for €2,50, and Internet access is included as well. I brought my Mac Mini with me, and as soon as I find an AC adapter I'll be ready to go with the 'net at home. I probably won't blog again till then, since I'm at work right now. + +Germany is great so far, and as soon as I get learning some German I'll be a much happier person. I consider it rude of me to expect everyone to converse with me in English, like I have to do right now. + +(Oh, and they sell beer by the litre in Germany! They call it a maß.) diff --git a/public/posts/2006.06.09-never-buy-a-german-keyboard.md b/public/posts/2006.06.09-never-buy-a-german-keyboard.md new file mode 100644 index 0000000..b25b341 --- /dev/null +++ b/public/posts/2006.06.09-never-buy-a-german-keyboard.md @@ -0,0 +1,14 @@ +Title: Never buy a German keyboard! +Date: June 9, 2006 +Timestamp: 1149841020 +Author: sjs +Tags: apple, apple, german, keyboard +---- + +Nothing personal, but the backtick/tilde is located where the rest of the left shift key should be, and the return key is double-height, forcing the backslash/bar to the right of the dash/underscore (that'd be the apostrophe/double quote for pretty much everyone else who types qwerty). Note that I'm talking about using a German keyboard with an English layout. The German layout is flat out impossible for coding. + +German Apple Keyboard + +For some reason it gets even worse with a German Apple keyboard. Square brackets, where for art though? Through trial and error I found them using Alt/Opt+5/6... non-Apple German keyboards I've seen use Alt Gr+8/9, which is just as bad but at least they were labeled. I know why coders here don't use the German layout! I feel uneasy just talking about it. + +Here's a text file with each character of the 4 rows in it, normal and then shifted, in qwerty, qwertz, and dvorak. I personally think that some ways the German keys change must be some sick joke (double quote moved up to shift-2, single quote almost staying put, angle brackets being shoved aside only to put the semi-colon and colon on different keys as well). If you ask me lots of that could be avoided by getting rid of the key that replaced the backtick/tilde, and putting the 3 vowels with the umlaut (ü, ö, and ä) on Alt Gr/Opt+[aou]. But hey, I don't type in German so what do I know. diff --git a/public/posts/2006.06.10-theres-nothing-regular-about-regular-expressions.md b/public/posts/2006.06.10-theres-nothing-regular-about-regular-expressions.md new file mode 100644 index 0000000..e83f312 --- /dev/null +++ b/public/posts/2006.06.10-theres-nothing-regular-about-regular-expressions.md @@ -0,0 +1,21 @@ +Title: There's nothing regular about regular expressions +Date: June 10, 2006 +Timestamp: 1149928080 +Author: sjs +Tags: technology, book, regex +---- + +I'm almost half way reading Jeffrey Friedl's book Mastering Regular Expressions and I have to say that for a book on something that could potentially bore you to tears, he really does an excellent job of keeping it interesting. Even though a lot of the examples are contrived (I'm sure out of necessity), he also uses real examples of regexes that he's actually used at Yahoo!. + +As someone who has to know how everything works it's also an excellent lesson in patience, as he frequently says "here, take this knowledge and just accept it for now until I can explain why in the next chapter (or in 3 chapters!)". But it's all with good reason and when he does explain he does it well. + +Reading about the different NFA and DFA engines and which tools use which made me go "ahhh, /that's/ why I can't do that in grep!" It's not just that I like to know how things work either, he's 100% correct about having to know information like that to wield the power of regexes in all situations. This book made me realize that regex implementations can be wildly different and that you really need to consider the job before jumping into using a specific regex flavour, as he calls them. I'm fascinated by learning why DFA regex implementations would successfully allow `^\w+=.(\\\n.)*` to match certain lines, allowing for trailing backslashes to mean continuation but why NFA engines would fail to do the same without tweaking it a bit. + +It requires more thinking than the last 2 computer books I read, *Programming Ruby* (the "pixaxe" book) and *Agile Web Development With Rails* so it's noticeably slower reading. It's also the kind of book I will read more than once, for sure. There's just no way I can glean everything from it in one reading. If you use regular expressions at all then you need this book. This is starting to sound like an advertisement so I'll say no more. + +QOTD, p. 329, about matching nested pairs of parens: + + \(([^()]|\(([^()]|\(([^()]|\(([^()])*\))*\))*\))*\) + Wow, that's ugly. + +(Don't worry, there's a much better solution on the next 2 pages after that quote.) diff --git a/public/posts/2006.06.11-apple-pays-attention-to-detail.md b/public/posts/2006.06.11-apple-pays-attention-to-detail.md new file mode 100644 index 0000000..5805727 --- /dev/null +++ b/public/posts/2006.06.11-apple-pays-attention-to-detail.md @@ -0,0 +1,8 @@ +Title: Apple pays attention to detail +Date: June 11, 2006 +Timestamp: 1150014600 +Author: sjs +Tags: technology, mac os x, apple +---- + +I think this has to be one of the big reasons why people who love their Mac, love their Mac (or other Apple product). I usually just have cheap PC speakers plugged into my Mac mini, but I didn't bring any with me to Munich and the internal Mac mini speaker isn't very loud, so I'm using headphones to watch movies. My Mac remembers the volume setting when the headphones ore plugged in, and when they're not, so I don't accidentally blow my ears. It's like my iPod pausing when the headphones are unplugged. It's excruciating attention to the smallest, (seemingly) most unimportant detail. I love it, and I'm hooked. diff --git a/public/posts/2006.07.06-working-with-the-zend-framework.md b/public/posts/2006.07.06-working-with-the-zend-framework.md new file mode 100644 index 0000000..5048948 --- /dev/null +++ b/public/posts/2006.07.06-working-with-the-zend-framework.md @@ -0,0 +1,41 @@ +Title: Working with the Zend Framework +Date: July 6, 2006 +Timestamp: 1152196560 +Author: sjs +Tags: coding, technology, php, framework, php, seekport, zend +---- + +At Seekport I'm currently working on an app to handle +the config of their business-to-business search engine. It's web-based and I'm using PHP, since +that's what they're re-doing the front-end in. Right now it's a big mess of Perl, the main +developer (for the front-end) is gone, and they're having trouble managing it. I have read +through it, and it's pretty dismal. They have config mixed with logic and duplicated code all +over the place. There's an 1100 line sub in one of the perl modules. Agh! + +Anyway, I've been looking at basically every damn PHP framework there is and most of them +aren't that great (sorry to the devs, but they're not). It's not really necessary for my little +project, but it helps in both writing and maintaining it. Many of them are unusable because +they're still beta and have bugs, and I need to develop the app not debug a framework. Some of +them are nice, but not really what I'm looking for, such as Qcodo, which otherwise look really cool. + +CakePHP and Symfony seem to want to be Rails so badly, but fall short in many ways, code beauty +being the most obvious one. + +I could go on about them all, I looked at over a dozen and took at least 5 of them for a +test-drive. The only one I really think has a chance to be the PHP framework is the Zend Framework. I really don't find it that amazing, but +it feels right, whereas the others feel very thrown-together. In other words, it does a good +job of not making it feel like PHP. ;-) + +Nothing they're doing is relovutionary, and I question the inclusion of things like PDF +handling when they don't even seem to have relationships figured out, but it provides a nice +level of convenience above PHP without forcing you into their pattern of thinking. A lot of the +other frameworks I tried seemed like one, big, unbreakable unit. With Zend I can really tell +that nothing is coupled. + +So I'll probably be writing some notes here about my experience with this framework. I also +hope to throw Adobe's Spry into the mix. +That little JS library is a lot of fun. diff --git a/public/posts/2006.07.13-ubuntu-linux-for-linux-users-please.md b/public/posts/2006.07.13-ubuntu-linux-for-linux-users-please.md new file mode 100644 index 0000000..d840cf0 --- /dev/null +++ b/public/posts/2006.07.13-ubuntu-linux-for-linux-users-please.md @@ -0,0 +1,14 @@ +Title: Ubuntu: Linux for Linux users please +Date: July 13, 2006 +Timestamp: 1152804840 +Author: sjs +Tags: linux, linux, ubuntu +---- + +Ubuntu is a fine Linux distro, which is why it's popular. I still use Gentoo on my servers but Ubuntu is fast to set up for a desktop. Linux for humans it certainly is, but dammit sometimes I want Linux like I'm used to. + +It should ship with build-essentials (gcc & others) installed. It *shouldn't* ask me if I'm sure I want to restart at the GDM login screen. I have no session open and already clicked twice to choose Restart. + +Other things aren't quite ready for humans yet. Network config needs some work. It's very slow to apply changes. Connecting to Windows printers should be easier (ie. let us browse to find them, or just search and present a list). Fonts aren't amazing yet, though Mac OS X has spoiled me as far as fonts are concerned. + +Other than these things I think Ubuntu Dapper is a fine release. It installed on my work laptop without a problem and detected the volume keys and wireless network card flawlessly. diff --git a/public/posts/2006.07.17-ruby-and-rails-have-spoiled-me-rotten.md b/public/posts/2006.07.17-ruby-and-rails-have-spoiled-me-rotten.md new file mode 100644 index 0000000..21fed1f --- /dev/null +++ b/public/posts/2006.07.17-ruby-and-rails-have-spoiled-me-rotten.md @@ -0,0 +1,16 @@ +Title: Ruby and Rails have spoiled me rotten +Date: July 17, 2006 +Timestamp: 1153140000 +Author: sjs +Tags: rails, ruby, php, coding, framework, php, rails, ruby, zend +---- + +It's true. I'm sitting here coding in PHP using the Zend Framework and all I can think about is how much nicer Rails is, or how much easier it is to do [x] in Ruby. It's not that the Zend Framework is bad or anything, it's quite nice, but you just can't match Ruby's expressiveness in a language like PHP. Add the amazing convenience Rails builds on top of Ruby and that's a really hard combo to compete with. + +I'd love to be using mixins instead of mucking around with abstract classes and interfaces, neither of which will just let you share a method between different classes. Writing proxy methods in these tiny in-between classes is annoying. (ie. inherit from Zend_class, then my real classes inherit from the middle-man class) I *could* add things to Zend's classes, but then upgrades are a bitch. I miss Ruby. I could use something like whytheluckystiff's PHP mixins, which is a clever hack, but still a hack. + +I keep looking at Rails code to see how things are done there, and I already coded a nearly complete prototype in Rails as a reference. I could have finished the thing in Rails by now, seriously. I'm still playing catch-up writing validations and model classes for all my objects, stuff I could've had for free using Rails, with an extra 10 mins to add validations and make sure they're all working nicely. + +It's no wonder David H. Hansson wasn't able to write a framework he was happy with in PHP. After using Rails everything seems like a chore. I'm just coding solved problems over again in an inferior language. + +But hey, I'm learning things and I still got to use Ruby even if the code won't be used later. I guess this experience will just make me appreciate the richness of Ruby and Rails even more. diff --git a/public/posts/2006.07.19-late-static-binding.md b/public/posts/2006.07.19-late-static-binding.md new file mode 100644 index 0000000..b192ee1 --- /dev/null +++ b/public/posts/2006.07.19-late-static-binding.md @@ -0,0 +1,47 @@ +Title: Late static binding +Date: July 19, 2006 +Timestamp: 1153329780 +Author: sjs +Tags: php, coding, coding, php +---- + +*Update: This has been discussed and will be uh, sort of fixed, in PHP6. You'll be able to use static::my_method() to get the real reference to self in class methods. Not optimal, but still a solution I guess.* + +As colder on ##php (freenode) told me today, class methods in PHP don't have what they call late static binding. What's that? It means that this code: + +
    +
    +class Foo
    +{
    +  public static function my_method()
    +  {
    +    echo "I'm a " . get_class() . "!\n";
    +  }
    +}
    +
    +class Bar extends Foo
    +{}
    +
    +Bar::my_method();
    +
    +
    + +outputs "I'm a Foo!", instead of "I'm a Bar!". That's not fun. + +Using __CLASS__ in place of get_class() makes zero difference. You end up with proxy methods in each subclass of Foo that pass in the real name of the calling class, which sucks. + +
    +
    +class Bar extends Foo
    +{
    +  public static function my_method()
    +  {
    +    return parent::my_method( get_class() );
    +  }
    +}
    +
    +
    + +I was told that they had a discussion about this on the internal PHP list, so at least they're thinking about this stuff. Too bad PHP5 doesn't have it. I guess I should just be glad I won't be maintaining this code. + +The resident PHP coder said "just make your code simpler", which is what I was trying to do by removing duplication. Too bad that plan sort of backfired. I guess odd things like this are where PHP starts to show that OO was tacked on as an after-thought. diff --git a/public/posts/2006.07.21-class-method-instance-method-it-doesnt-matter-to-php.md b/public/posts/2006.07.21-class-method-instance-method-it-doesnt-matter-to-php.md new file mode 100644 index 0000000..210ded7 --- /dev/null +++ b/public/posts/2006.07.21-class-method-instance-method-it-doesnt-matter-to-php.md @@ -0,0 +1,56 @@ +Title: Class method? Instance method? It doesn't matter to PHP +Date: July 21, 2006 +Timestamp: 1153493760 +Author: sjs +Tags: php, coding +---- + +*Update: This has been discussed for PHP6. A little late, but I guess better than never.* + +I made a mistake while I was coding, for shame! Anyway this particular mistake was that I invoked a class method on the wrong class. The funny part was that this method was an instance method in the class which I typed by mistake. In the error log I saw something like "Invalid use of $this in class function." + +I knew for a fact I hadn't used $this in a class method, so it was kind of a confusing error. I went to the file in question and found out that it was calling an instance method as a class method. Now that is some crazy shit. + +I would fully expect the PHP parser to give me an error like "No class method [foo] in class [blah]", rather than try and execute it as a class method. The syntax is completely different; you use :: to call a class method and -> to call an instance method. And you use the name of a class when you call a class method. + +This code: + +
    
    +class Foo {
    +  public static function static_fun()
    +  {
    +    return "This is a class method!\n";
    +  }
    +
    +  public function not_static()
    +  {
    +    return "This is an instance method!\n";
    +  }
    +}
    +
    +echo '<pre>';
    +echo "From Foo:\n";
    +echo Foo::static_fun();
    +echo Foo::not_static();
    +echo "\n";
    +
    +echo "From \$foo = new Foo():\n";
    +$foo = new Foo();
    +echo $foo->static_fun();
    +echo $foo->not_static();
    +echo '</pre>';
    +
    + +Produces: + +
    
    +From Foo:
    +This is a class method!
    +This is an instance method!
    +
    +From $foo = new Foo():
    +This is a class method!
    +This is an instance method!
    +
    + +What the fuck?! http://www.php.net/manual/en/language.oop5.static.php is lying to everyone. diff --git a/public/posts/2006.08.22-where-are-my-headphones.md b/public/posts/2006.08.22-where-are-my-headphones.md new file mode 100644 index 0000000..90fb878 --- /dev/null +++ b/public/posts/2006.08.22-where-are-my-headphones.md @@ -0,0 +1,8 @@ +Title: Where are my headphones? +Date: August 22, 2006 +Timestamp: 1156257060 +Author: sjs +Tags: life, seekport +---- + +Some people left Seekport this month and 2 of the remaining employees moved into the office I’m working in. That’s fine, and I’m leaving at the end of the week, but man I’m going crazy. This guy’s pounding on his keyboard like it’s a fucking whack-a-mole game! I don’t know what kind of keyboard he learned to type on but it must’ve been horrible. It sounds like he must go through at least 10 of those things in a year. I don’t know if I’ll make it till Friday without yelling "AGH! STOP THE MADNESS YOU CRAZY BASTARD YOU JUST HAVE TO TOUCH THE KEYS!" diff --git a/public/posts/2006.09.16-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo.md b/public/posts/2006.09.16-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo.md new file mode 100644 index 0000000..7450836 --- /dev/null +++ b/public/posts/2006.09.16-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo.md @@ -0,0 +1,10 @@ +Title: Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo +Date: September 16, 2006 +Timestamp: 1158469860 +Author: sjs +Tags: amusement, buffalo +---- + +Wouldn't the sentence 'I want to put a hyphen between the words Fish and And and And and Chips in my Fish-And-Chips sign' have been clearer if quotation marks had been placed before Fish, and between Fish and and, and and and And, and And and and, and and and And, and And and and, and and and Chips, as well as after Chips? + +→ Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo diff --git a/public/posts/2006.09.22-some-features-you-might-have-missed-in-itunes-7.md b/public/posts/2006.09.22-some-features-you-might-have-missed-in-itunes-7.md new file mode 100644 index 0000000..e271cdc --- /dev/null +++ b/public/posts/2006.09.22-some-features-you-might-have-missed-in-itunes-7.md @@ -0,0 +1,50 @@ +Title: Some features you might have missed in iTunes 7 +Date: September 22, 2006 +Timestamp: 1158969540 +Author: sjs +Tags: apple, apple, itunes +---- + +New menu + +Besides the big changes in iTunes 7 there have been some minor changes that are still pretty useful. + +Here's a quick recap of a few major features: + + * Coverflow built in, new views to flip through album covers and video thumbnails + * iTunes Music Store is now just the iTunes Store + * New look, no more brushed metal + * The menu on the left is more structured and easier to navigate (for me) + * Games support + +And now some of the smaller gems are listed below. + +

    Video controls

    + +iTunes video controls + +Similar to the Quicktime full screen controls, iTunes now sports video controls as well. It was really annoying to have to exit fullscreen to control the video, and now we don't have to. The controls are available when you have a floating video window open as well as when you're full screen. + +

    Smart playlists

    + +It's always bothered me that I couldn't remove tracks from smart playlists. After all they are supposed to be smart, so they should remember customizations to them since even the basic ones do that. They're getting smarter. You still can't add arbitrary tracks to one, but I've never wanted to do that except just now to see if you could. + +### Gapless playback (and more) ### + +Gapless playback + +You can set tracks to be part of a gapless album, and your iPod makes use of that information too. Sweet. Another new flag is "Skip when shuffling". + +There's also a new field for audio named "Album Artist", but I have no idea what that means. + +

    More video metadata

    + +iTunes video controls + +For videos you can now set the Show, Season Number, Episode Number, and Episode ID for each video. Why they let you do this for Movies and Music Videos I'm not sure, but there it is. + +

    What's still missing?

    + +I want to be able to change more than one movie's type to Movie, Music Video, or TV Show at once. Manually doing it for more than one season of a show gets old very fast, and I'm reluctant to write a program to let you do just that but I may if I have time. + +I'm sure I have other gripes, but honestly iTunes is a full-featured app and while there's room for improvement they do get a lot right with it as well. diff --git a/public/posts/2006.12.17-coping-with-windows-xp-activiation-on-a-mac.md b/public/posts/2006.12.17-coping-with-windows-xp-activiation-on-a-mac.md new file mode 100644 index 0000000..30c5135 --- /dev/null +++ b/public/posts/2006.12.17-coping-with-windows-xp-activiation-on-a-mac.md @@ -0,0 +1,106 @@ +Title: Coping with Windows XP activiation on a Mac +Date: December 17, 2006 +Timestamp: 1166427000 +Author: sjs +Tags: parallels, windows, apple, mac os x, bootcamp +---- + +**Update:** This needs to be run at system startup, before you log in. I have XP Home and haven't been able to get it to run that way yet. + +I can't test my method until I get XP Pro, if I get XP Pro at all. However chack left a comment saying that he got it to work on XP Pro, so it seems we've got a solution here. + +
    + +### What is this about? ### + +I recently deleted my Windows XP disk image for Parallels Desktop and created a Boot Camp partition for a new Windows XP installation. I created a new VM in Parallels and it used my Boot Camp partition without a problem. The only problem is that Windows XP Home wants to re-activate every time you change from Parallels to Boot Camp or vice versa. It's very annoying, so what can we do about it? + +I was reading the Parallels forums and found out that you can backup your activation and restore it later. After reading that I developed a solution for automatically swapping your activation on each boot so you don't have to worry about it. + +I try and stick to Linux and OS X especially for any shell work, and on Windows I would use zsh on cygwin if I use any shell at all, but I think I have managed to hack together a crude batch file to solve this activation nuisance. It's a hack but it sure as hell beats re-activating twice or more every day. It also reinforced my love of zsh and utter dislike of the Windows "shell". + +If anyone actually knows how to write batch files I'd like to hear any suggestions you might have. + +
    + +### Make sure things will work ### + +You will probably just want to test my method of testing for Parallels and Boot Camp first. The easiest way is to just open a command window and run this command: + + ipconfig /all | find "Parallels" + +If you see a line of output like **"Description . . . . : Parallels Network Adapter"** and you are in Parallels then the test works. If you see no output and you are in Boot Camp then the test works. + +*If you see no output in Parallels or something is printed and you're in Boot Camp, then please double check that you copied the command line correctly, and that you really are running Windows where you think you are. ;-)* + +If you're lazy then you can download this test script and run it in a command window. Run it in both Parallels and Boot Camp to make sure it gets them both right. The output will either be "Boot Camp" or "Parallels", and a line above that which you can just ignore. + +
    + +**NOTE:** If you're running Windows in Boot Camp right now then do Step #2 before Step #1. + +
    + +## Step #1 ## + +Run Windows in Parallels, activate it, then open a command window and run: + + mkdir C:\Windows\System32\Parallels + copy C:\Windows\System32\wpa.* C:\Windows\System32\Parallels + +Download backup-parallels-wpa.bat + +
    + +## Step #2 ## + +Run Windows using Boot Camp, activate it, then run: + + mkdir C:\Windows\System32\BootCamp + copy C:\Windows\System32\wpa.* C:\Windows\System32\BootCamp + +Download backup-bootcamp-wpa.bat + +
    + +## Step #3: Running the script at startup ## + +Now that you have your activations backed up you need to have the correct ones copied into place every time your system boots. Save this file anywhere you want. + +If you have XP Pro then you can get it to run using the Group Policy editor. Save the activate.bat script provided here anywhere and then have it run as a system service. Go Start -> Run... -> gpedit.msc [enter] Computer Configuration -> Windows Settings -> Scripts (Startup/Shutdown) -> Startup -> Add. + +

    If you have XP Home then the best you can do is run this script from your Startup folder (Start -> All Programs -> Startup), but that is not really going to work because eventually Windows will not even let you log in until you activate it. What a P.O.S.

    + + @echo off + + ipconfig /all | find "Parallels" > network.tmp + for /F "tokens=14" %%x in (network.tmp) do set parallels=%x + del network.tmp + + if defined parallels ( + echo Parallels + copy C:\Windows\System32\Parallels\wpa.* C:\Windows\System32 + ) else ( + echo Boot Camp + copy C:\Windows\System32\BootCamp\wpa.* C:\Windows\System32 + ) + +Download activate.bat + +
    + +### You're done! ### + +That's all you have to do. You should now be able to run Windows in Boot Camp and Parallels as much as you want without re-activating the stupid thing again! + +If MS doesn't get their act together with this activation bullshit then maybe the Parallels folks might have to include something hack-ish like this by default. + +This method worked for me and hopefully it will work for you as well. I'm interested to know if it does or doesn't so please leave a comment or e-mail me. + +
    + +#### Off-topic rant #### + +I finally bought Windows XP this week and I'm starting to regret it because of all the hoops they make you jump through to use it. I only use it to fix sites in IE because it can't render a web page properl and I didn't want to buy it just for that. I thought that it would be good to finally get a legit copy since I was using a pirated version and was sick of working around validation bullshit for updates. Now I have to work around MS's activation bullshit and it's just as bad! Screw Microsoft for putting their customers through this sort of thing. Things like this and the annoying balloons near the system tray just fuel my contempt for Windows and reinforce my love of Linux and Mac OS X. + +I don't make money off any of my sites, which is why I didn't want to have to buy stupid Windows. I hate MS so much for making shitty IE the standard browser. diff --git a/public/posts/2007.03.06-full-screen-cover-flow.md b/public/posts/2007.03.06-full-screen-cover-flow.md new file mode 100644 index 0000000..84401b6 --- /dev/null +++ b/public/posts/2007.03.06-full-screen-cover-flow.md @@ -0,0 +1,12 @@ +Title: Full-screen Cover Flow +Date: March 6, 2007 +Timestamp: 1173217860 +Author: sjs +Tags: apple, coverflow, itunes +---- + +Cover Flow now comes in a full-screen flavour. It's pretty sweet, but unfortunately the remote controls iTunes exactly the same so you need a mouse to flick through the covers. + +That made me wonder if Front Row used this full-screen Cover Flow view for albums now, but it doesn't. I hope Apple gets on this and adds it to Front Row and the Apple TV. I'm sure it's already on their list. + +I would love to be able to flick through my albums with the remote right now, but I'm not going to install one of those 3rd-party remote config tools. Guess I have to wait for Apple to do it. diff --git a/public/posts/2007.03.08-digg-v4-reply-to-replies-greasemonkey-script.md b/public/posts/2007.03.08-digg-v4-reply-to-replies-greasemonkey-script.md new file mode 100644 index 0000000..5452dc1 --- /dev/null +++ b/public/posts/2007.03.08-digg-v4-reply-to-replies-greasemonkey-script.md @@ -0,0 +1,14 @@ +Title: Digg v4: Reply to replies (Greasemonkey script) +Date: March 8, 2007 +Timestamp: 1173424740 +Author: sjs +Tags: coding, digg, firefox, userscript +---- + +It's nearly identical to the previous one but works with Digg v4 and should be slightly more efficient. I'm working on making it faster because I believe it is quite inefficient as it is. It was David Bendit's (the original author) first script though so kudos to him for starting this thing because I love it. I just hate a slow greasemonkey script on pages with hundreds of comments. + +Please leave me some comments if you appreciate this, or have any feedback on the code. + +Happy Digging! + +Digg this script! diff --git a/public/posts/2007.03.25-diggscuss-0.9.md b/public/posts/2007.03.25-diggscuss-0.9.md new file mode 100644 index 0000000..06395d2 --- /dev/null +++ b/public/posts/2007.03.25-diggscuss-0.9.md @@ -0,0 +1,16 @@ +Title: Diggscuss 0.9 +Date: March 25, 2007 +Timestamp: 1174834980 +Author: sjs +Tags: coding, digg, firefox, userscript +---- + +The biggest change is that it uses XPath for the dirty work, which makes it quite a bit more readable. It's 100 lines longer than the previous version, but it does twice as much. + +Now both a [reply] and a [quote] link are added to each comment. Replying to parent comments now adds @username: to the comment field as well as the links added by the script. + +Regression: The link to the parent comment is no longer displayed. If you miss this then let me know and I will add it back in. + +Any comments, criticism or feature requests are welcome just leave me a comment here or on userscripts.org. + +Happy Digging! diff --git a/public/posts/2007.04.04-a-triple-booting-schizophrenic-macbook.md b/public/posts/2007.04.04-a-triple-booting-schizophrenic-macbook.md new file mode 100644 index 0000000..4d803e9 --- /dev/null +++ b/public/posts/2007.04.04-a-triple-booting-schizophrenic-macbook.md @@ -0,0 +1,37 @@ +Title: A triple-booting, schizophrenic MacBook +Date: April 4, 2007 +Timestamp: 1175754600 +Author: sjs +Tags: linux, mac os x, windows +---- + +The steps are well documented so I won’t get into detail here but if you have a backup and can wipe your disk all you do is: + + * Install OS X to a single partition filling your disk (optionally use your existing OS X intall) + * Install rEFIt (no need to reboot just yet) + * Re-partition your disk into 3 partitions with diskutil resizeVolume, reboot and confirm it all works + * Boot the Vista install DVD and install to disk0s4 aka Partition 4 + * Install Gentoo (or other distro) to disk0s3 aka /dev/sda3 + +With MacPorts and Gentoo/MacOSX the Gentoo install is superfluous but I’ll spare 12G just to see Gentoo run on this fine machine. Setting up the hardware should be fun. Right now I’m compiling X, (package 77 of 94) and the Core Duo is crunching code very nicely with 2G to work with, without any swap. I fully intend to put off creating a swap file unless I have to. Needless to say I’ll be running fluxbox or Xfce, none of that Gnome or KDE stuff. If I ever need a swap file I will eat my keyboard. + +*[edit: 25 minutes to compile X.org, not too shabby!]* + +My initial experience with Vista is quite good. Sadly the same old registry hack is required to swap Caps lock and Control but I was just glad it worked. I really like the new Start menu and the eye-candy is fairly pleasant for the most part. Till now I’d only used RC2 on a machine incapable of running Aero Glass and it looked terrible. I switched to Windows Classic just like I do with XP. Not so with Aero at its finest though. Without thinking about the price Vista is a nice upgrade to Windows. But because of the price and uncertainty of running Aero Glass I still hesitate to urge non-geeks to upgrade. + +OS X is OS X. It’s my favourite desktop OS right now because of apps like LaunchBar/Quicksilver and TextMate, a generally excellent UI, good old *nix stability, zsh out of the box! When I need WireShark or the GIMP X11 is there waiting. Mac notebooks are great and tight integration with the hardware is a clear advantage for OS X. + +Oh yeah, I also have a Parallels VM for Windows 3.11. It boots in about second to the C:\> prompt and then another second to type win and Windows to start. Without TCP/IP there’s not much to do though (I’m not going to write a driver for Parallels’ ethernet adapter). + +
      +
    1. +
        +
      • Dual head setups are more work than plugging in a 2nd monitor, which is too much work. +
      • X requires a restart to enable or disable a 2nd display. +
      • Overall clunkiness such as displaying the houndstooth background before the WM starts, +
      • and/or going through a screwed up mode with a black & white scrambled screen for a seconds before getting to the houndstooth. +
      + back up ↑ +
    + +Like I said the X.org boys are doing amazing work. Hopefully soon after the current eye-candy craze is over they’ll get to more important work that needs to be done. diff --git a/public/posts/2007.04.11-activerecord-base.find_or_create-and-find_or_initialize.md b/public/posts/2007.04.11-activerecord-base.find_or_create-and-find_or_initialize.md new file mode 100644 index 0000000..5d8eab7 --- /dev/null +++ b/public/posts/2007.04.11-activerecord-base.find_or_create-and-find_or_initialize.md @@ -0,0 +1,112 @@ +Title: ActiveRecord::Base.find_or_create and find_or_initialize +Date: April 11, 2007 +Timestamp: 1176287040 +Author: sjs +Tags: activerecord, coding, rails, ruby +---- + +I've extended ActiveRecord with `find_or_create(params)` and `find_or_initialize(params)`. Those are actually just wrappers around `find_or_do(action, params)` which does the heavy lifting. + +They work exactly as you'd expect them to work with possibly one gotcha. If you pass in an `id` attribute then it will just find that record directly. If it fails it will try and find the record using the other params as it would have done normally. + +Enough chat, here's the self-explanatory code: + + + + +
    1
    +2
    +3
    +4
    +
    # extend ActiveRecord::Base with find_or_create and find_or_initialize.
    +ActiveRecord::Base.class_eval do
    +  include ActiveRecordExtensions
    +end
    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +
    module ActiveRecordExtensions
    +  def self.included(base)
    +    base.extend(ClassMethods)
    +  end
    +  
    +  module ClassMethods
    +    def find_or_initialize(params)
    +      find_or_do('initialize', params)
    +    end
    +
    +    def find_or_create(params)
    +      find_or_do('create', params)
    +    end
    +    
    +    private
    +    
    +    # Find a record that matches the attributes given in the +params+ hash, or do +action+
    +    # to retrieve a new object with the given parameters and return that.
    +    def find_or_do(action, params)
    +      # if an id is given just find the record directly
    +      self.find(params[:id])
    +
    +    rescue ActiveRecord::RecordNotFound => e
    +      attrs = {}     # hash of attributes passed in params
    +
    +      # search for valid attributes in params
    +      self.column_names.map(&:to_sym).each do |attrib|
    +        # skip unknown columns, and the id field
    +        next if params[attrib].nil? || attrib == :id
    +
    +        attrs[attrib] = params[attrib]
    +      end
    +
    +      # no valid params given, return nil
    +      return nil if attrs.empty?
    +
    +      # call the appropriate ActiveRecord finder method
    +      self.send("find_or_#{action}_by_#{attrs.keys.join('_and_')}", *attrs.values)
    +    end
    +  end
    +end
    + diff --git a/public/posts/2007.04.16-getting-to-know-vista.md b/public/posts/2007.04.16-getting-to-know-vista.md new file mode 100644 index 0000000..0eeffa1 --- /dev/null +++ b/public/posts/2007.04.16-getting-to-know-vista.md @@ -0,0 +1,64 @@ +Title: Getting to know Vista +Date: April 16, 2007 +Timestamp: 1176746940 +Author: sjs +Tags: windows +---- + +### It looks pretty good! ### + +After figuring out how to minimise the translucency of the window decorations I think Aero looks ok. Window titles, on both windows and the taskbar, can be difficult to read at a glance which is really stupid if you ask me. But it’s better than Luna! They really lay the effects on thick but overall I find it pretty pleasant and it runs well on my MacBook’s Intel 945 video chip. + +Ah yes, the Sidebar is nowhere to be seen on my desktop. It’s a nice-looking waste of space. + +### But it’s not all useful ### + +Sadly The new task switcher (Win-tab) is terrible. Before using it I wondered why they didn’t replace Alt-tab completely. Now I know and I am grateful to MS for not replacing it. Alt-tab easily wins. Especially since it displays thumbnails of windows. + +Three gripes with Win-tab fancy-shmanciness: + + * It’s too slow + * It responds even when I just tap Win-tab to quickly switch, then I’m stuck until I hit the Windows key to choose a window + * Windows from all my monitors are gathered onto the main one, which is just lame + +### It’s stable (so far) ### + +Besides the fact it is aesthetically pleasing [subjective] it also has just worked for me so far. Nothing has crashed or broken which is almost miraculous. Not that I had a terrible time with XP, but it was still frail old Windows at times. I’m equally pleased with Apple’s drivers for Windows which probably adds to the experience. I’ve used XP machines with proper drivers, and those without and the differenc is night & day. I’ve had uptimes in months on a stable XP notebook. + + +### Never thought this day would come... ### + +But I actually like the Start menu. Really, I do. You hit the Windows key, type a few letters and boom you launch your app or search your computer, or the web (Google in Firefox, my default search). It’s not QuickSilver or LaunchBar; it’s not supposed to be. For the average Joe this is cool, and for the average power user it’s very useful. For the casual Windows user it’s great. It even learns. + +I don’t love it though. I knew before using it that the new method of navigating through the All Programs menu would be weird. It is, but I guess it may be better than the previous fly-out scheme (which I don’t care for either). I guess the All Programs menu is more or less legacy now though and I don’t see myself using it often. + + +### I’m a command line junkie ### + +They fixed at least one glaring bug. I used the cmd.exe shell a little bit even though I hate it. I was happy to find that Tab completion works for more than the current directory now. Before Vista it would complete the same entries from PWD no matter how deep you tried to drill down into the filesystem. Other than that it seems to be the same crummy shell. *[edit—apparently this is fixed in XP as well, my mistake]* + +I installed the Windows PowerShell (PoSH) but haven’t really put an effort to learn it yet. The syntax is unorthodox coming from *nix shells (zsh), but it’s sort of refreshing and it lives up to the Power part of its name. I really like the fact that collections of (say) files can be passed around and iterated over, filtered, etc. not as filenames but as real objects with corresponding methods and metadata. Built-in support for XML is pretty nifty too. + +I’ve often longed for a shell which acted like a normal shell for the most part, but allowed irb-like interpretation of arbitrary Ruby code as well. The PowerShell seems like it could be something similar to what I’ve wanted. Too bad it’s proprietary and only runs on Windows. If I use Vista a lot this summer I could end up getting into it more though. It’s quite interesting. + +### Random ### + +The good: + + * Slideshow button in Explorer + * Doesn’t look like a Fisher-Price design + * Restarts when I click Restart (after 3 clicks it damn well better) + * Seems stable, at least initially which means the installation & driver situation really has improved + * I don’t want to kill anyone while using it + +The bad: + + * Flicker while changing video modes, displaying UAC prompts, etc. (not so bad really, but stands out on an otherwise smooth desktop) + * Long black screen on boot after installing updates + * Disappearing / magical menu bar debacle + * The shell still sucks + * It tries to be too fancy, with the dynamic Start menu icon and the like + +### My conclusion ### + +Perhaps the scores of talented developers at Microsoft *can* save them despite their obvious shortcomings in management. .NET seems like a decent platform, but we’ll have to see how I like it once I actually use it. So far I don’t hate Vista and considering the previous versions of Windows that’s a pretty good review coming from me. I’m still recommending Macs to my family and friends, but who knows what the future holds. I don’t hate Vista and by the end of the summer I may even [gasp] like it, and/or .NET. I haven’t used an IDE since VB6 and MS has always had a decent IDE (albeit with a crummy text editor). I’m expecting to enjoy it. If there’s one thing MS knows it’s the value of good dev tools and developers. diff --git a/public/posts/2007.04.26-quickly-inserting-millions-of-rows-with-mysql-innodb.md b/public/posts/2007.04.26-quickly-inserting-millions-of-rows-with-mysql-innodb.md new file mode 100644 index 0000000..cedc573 --- /dev/null +++ b/public/posts/2007.04.26-quickly-inserting-millions-of-rows-with-mysql-innodb.md @@ -0,0 +1,52 @@ +Title: Quickly inserting millions of rows with MySQL/InnoDB +Date: April 26, 2007 +Timestamp: 1177596360 +Author: sjs +Tags: linux, mysql +---- + +The absolute first thing you should do is check your MySQL configuration to make sure it’s sane for the system you’re using. I kept getting a ‘The table is too large’ error on my Gentoo box after inserting several million rows because the default config limits the InnoDB tablespace size to 128M. It was also tuned for a box with as little as 64M of RAM. That’s cool for a small VPS or your old Pentium in the corner collecting dust. For a modern server, workstation, or even notebook with gigs of RAM you’ll likely want to make some changes. + +### Tweaking my.cnf ### + +Here are the relevant settings you can tweak in order to work with large datasets efficiently. These are set in your my.cnf file, which varies in location. + +On Gentoo it resides at /etc/mysql/my.cnf. + +When MySQL 5.x is installed via DarwinPorts on Mac OS X you need to copy one of the defaults from /opt/local/share/mysql5/mysql/ to /opt/local/etc/mysql5/my.cnf and then modify it accordingly. + +If you use another system you’re on your own. If you can’t figure it out, please put down the text editor and leave the poor config file alone! Jokes aside this really is not difficult if you’re used to configuring *nix programs. + +### innodb_buffer_pool_size ### + +This determines how much memory MySQL uses for table indexes and data. You can set it as low as 8-10M, or high as 50-80% of your memory on a dedicated MySQL server. I have RAM to burn[1] in my workstation so I set this to 200M, 20% of my 1GB. + +[1] I run Fluxbox on Gentoo, I use 200-300M of my 1GB on average and with 200M for MySQL 409M are in use at this moment. Gotta love those lightweight window managers! + +### innodb_additional_mem_pool_size ### + +According to [a post on a MySQL mailing list](http://lists.mysql.com/mysql/129247), modern OSs have fast enough mallocs and this variable has little effect on performance. I set mine to 16M before reading that post, so I’ll just leave it at that. + +### innodb_data_file_path ### + +On Gentoo this one bit me right in the ass, and I mentioned it above. It specifies how large the files used to store your data can be, and how many of them there are. The default setting is almost sane: ibdata1:10M:autoextend:max:128M. Limiting the total size to 128M caused my test to fail after inserting several million rows. + +Simply removing max:128M solves the problem. The resulting setting tells the InnoDB engine to use one file, named ibdata1 which is initially 10M in size and grows as required. + +### innodb_log_file_size ### + +The default Gentoo config says they (whoever they are) keep this at 25% of innodb_buffer_pool_size so I did just that. 50M in my case. + +### innodb_log_buffer_size ### + +Again I only went as far as the Gentoo config to learn about this setting. They had it at 8M and recommend increasing it if you have large transactions. I can’t think of any particularly large transactions I currently use but I doubled it to 16M anyway. + +### Save my.cnf and restart mysqld ### + +That’s it for the MySQL config. Restart mysqld however you do that on your platform. sudo /etc/init.d/mysql restart should look familiar to many *nix users. + +Now you should be able to insert dozens and indeed hundreds of millions of rows into your InnoDB tables. Sadly this brought little performance gains to the table. MySQL wraps single queries in implicit transactions. Wrapping everything in a transaction may work, but inevitably something will go wrong and you may want the ability to resume inserting the rows instead of starting all over. + +The solution now is to execute SET AUTOCOMMIT=0 before inserting the data, and then issuing a COMMIT when you’re done. With all that in place I’m inserting 14,000,000 rows into both MyISAM and InnoDB tables in 30 minutes. MyISAM is still ~ 2 min faster, but as I said earlier this is adequate for now. Prior to all this it took several hours to insert 14,000,000 rows so I am happy. + +Now you can enjoy the speed MyISAM is known for with your InnoDB tables. Consider the data integrity a bonus! ;-) diff --git a/public/posts/2007.04.30-funny-how-code-can-be-beautiful.md b/public/posts/2007.04.30-funny-how-code-can-be-beautiful.md new file mode 100644 index 0000000..154b158 --- /dev/null +++ b/public/posts/2007.04.30-funny-how-code-can-be-beautiful.md @@ -0,0 +1,25 @@ +Title: Funny how code can be beautiful +Date: April 30, 2007 +Timestamp: 1177942020 +Author: sjs +Tags: haskell +---- + +While reading a Haskell tutorial I came across the following code for defining the Fibonacci numbers: + + fib = 1 : 1 : [ a + b | (a, b) <- zip fib (tail fib) ] + +After reading it a few times and understanding how it works I couldn’t help but think how beautiful it is. I don’t mean that it’s aesthetically pleasing to me; the beautiful part is the meaning and simplicity. Lazy evaluation is sweet. + +Haskell is the most challenging real language I have tried to wrap my head around. I haven’t done much with any functional languages yet but they are truly fascinating. I’m beginning to understand monads[1] but I’m quite sure I don’t see the whole picture yet. + +Erlang looks like it may be more suited to real world apps so I would like to learn that some time. The pragmatic guys have a book on Erlang in the works, and I love every book of theirs which I have read. + +Going deeper down the functional rabbit-hole you’ll find things like this polyglot quine, which absolutely blows my mind. I used to be impressed by the JAPH sigs or some of the various obfuscated contest winners but that first one definitely cleans the rest up with a perfect 10 in geekiness. + +[1] The following links have all been helpful while trying to wrap my head around monads. + + * A Gentle Introduction to Haskell (link is directly to chapter 9) + * What the hell are Monads? + * Monads on WikiBooks + * Monads for the Working Haskell Programmer diff --git a/public/posts/2007.05.01-typo-and-i-are-friends-again.md b/public/posts/2007.05.01-typo-and-i-are-friends-again.md new file mode 100644 index 0000000..b83a660 --- /dev/null +++ b/public/posts/2007.05.01-typo-and-i-are-friends-again.md @@ -0,0 +1,14 @@ +Title: Typo and I are friends again +Date: May 1, 2007 +Timestamp: 1178081497 +Author: sjs +Tags: typo +---- + +

    I've been really frustrated with Typo recently. For some reason changing my last post would cause MySQL to timeout and I'd have to kill the rogue ruby process manually before any other changes to the DB would work, instead of hanging for a minute or two then timing out. Luckily I was able to disable the post using the command line client, the bug only manifested itself when issuing an UPDATE with all the fields present. Presumably the body was tripping things up because most other fields are simple booleans, numbers, or very short strings. + +Add to that the random HTTP 500 errors which were very noticeable while I was trying to fix that post and I was about to write my own blog or switch to WordPress. + +I don't love WP so I decided to just upgrade Typo instead. I was using Typo 2.6, and the current stable version is 4.1. They skipped version 3 to preclude any confusion that may have ensued between Typo v3 and the CMS Typo3. So it really isn't a big upgrade and it went perfectly. I checked out a new copy of the repo because I had some difficulty getting svn switch --relocate to work, configured the database settings and issued a rake db:migrate, copied my theme over and it all just worked. Bravo Typo team, that's how an upgrade should work. + +No more random 500 errors, things seem faster (better caching perhaps), and that troublesome post is troublesome no more. I am happy with Typo again. diff --git a/public/posts/2007.05.03-a-scheme-parser-in-haskell-part-1.md b/public/posts/2007.05.03-a-scheme-parser-in-haskell-part-1.md new file mode 100644 index 0000000..09a34a8 --- /dev/null +++ b/public/posts/2007.05.03-a-scheme-parser-in-haskell-part-1.md @@ -0,0 +1,67 @@ +Title: A Scheme parser in Haskell: Part 1 +Date: May 3, 2007 +Timestamp: 1178178470 +Author: sjs +Tags: coding, haskell +---- + +From Write Yourself a Scheme in 48 hours: + +

    +

    Basically, a monad is a way of saying "there's some extra information attached to this value, which most functions don't need to worry about". In this example, the "extra information" is the fact that this action performs IO, and the basic value is nothing, represented as "()". Monadic values are often called "actions", because the easiest way to think about the IO monad is a sequencing of actions that each might affect the outside world.

    +
    + +I really like this tutorial. I'm only on part 3.3 of 12, parsing, but I'm new to Haskell so I'm learning left, right & centre. The exercises are taking me hours of reading and experimenting, and it's lots of fun! ghc's errors are usually quite helpful and of course ghci is a big help as well. + +I'm going to explain one of the exercises because converting between the various syntax for dealing with monads wasn't plainly obvious to me. Perhaps I wasn't paying enough attention to the docs I read. In any case if you're interested in Haskell at all, I recommend the tutorial and if you're stuck on exercise 3.3.1 like I was then come on back here. Whether you're following the tutorial or not the point of this post should stand on its own with a basic knowledge of Haskell. + +Last night I rewrote parseNumber using do and >>= (bind) notations (ex. 3.3.1). Here's parseNumber using the liftM method given in the tutorial: + +
    parseNumber :: Parser LispVal
    +parseNumber :: liftM (Number . read) $ many1 digit
    +
    +Okay that's pretty simple right? Let's break it down, first looking at the right-hand side of the $ operator, then the left. + + * many1 digit reads as many decimal digits as it can. + * Number . read is a function composition just like we're used to using in math. It applies read to its argument, then applies Number to that result. + * liftM is concisely and effectively defined elsewhere, and I'll borrow their description: + +
    +

    liftM f m lets a non-monadic function f operate on the contents of monad m

    +
    + +liftM's type is also quite telling: liftM :: (Monad m) => (a -> b) -> (m a -> m b) + +In a nutshell liftM turns a function from a to b to a function from a monad containing a to a monad containing b. + +That results in a function on the left-hand side of $, which operates on and outputs a monad. The content of the input monad is a String. The content of the output monad is a LispVal (defined earlier in the tutorial). Specifically it is a Number. + +The $ acts similar to a pipe in $FAVOURITE_SHELL, and is right associative which means the expression on the right is passed to the expression (function) on the left. It's exactly the same as (liftM (Number . read)) (many1 digit) except it looks cleaner. If you know LISP or Scheme (sadly I do not) then it's analogous to the apply function. + +So how does a Haskell newbie go about re-writing that using other notations which haven't even been explained in the tutorial? Clearly one must search the web and read as much as they can until they understand enough to figure it out (which is one thing I like about the tutorial). If you're lazy like me, here are 3 equivalent pieces of code for you to chew on. parseNumber's type is Parser LispVal (Parser is a monad). + + +Familiar liftM method: +
    parseNumber -> liftM (Number . read) $ many1 digit
    +
    + +Using do notation: +
    parseNumber -> do digits <- many1 digit
    +                  return $ (Number . read) digits
    +
    +If you're thinking "Hey a return, I know that one!" then the devious masterminds behind Haskell are certainly laughing evilly right now. return simply wraps up it's argument in a monad of some sort. In this case it's the Parser monad. The return part may seem strange at first. Since many1 digit yields a monad why do we need to wrap anything? The answer is that using <- causes digits to contain a String, stripped out of the monad which resulted from many1 digit. Hence we no longer use liftM to make (Number . read) monads, and instead need to use return to properly wrap it back up in a monad. + +In other words liftM eliminates the need to explicitly re-monadize the contents as is necessary using do. + + +Finally, using >>= (bind) notation: +
    parseNumber -> many1 digit >>= \digits ->
    +               return $ (Number . read) digits
    +
    +At this point I don't think this warrants much of an explanation. The syntactic sugar provided by do should be pretty obvious. Just in case it's not, >>= passes the contents of its left argument (a monad) to the function on its right. Once again return is needed to wrap up the result and send it on its way. + +When I first read about Haskell I was overwhelmed by not knowing anything, and not being able to apply my previous knowledge of programming to anything in Haskell. One piece of syntax at a time I am slowly able to understand more of the Haskell found in the wild. + +I'm currently working on ex. 3.3.4, which is parsing R5RS compliant numbers (e.g. #o12345670, #xff, #d987). I'll probably write something about that once I figure it out, but in the meantime if you have any hints I'm all ears. + +*Update #1: I should do more proof-reading if I'm going to try and explain things. I made some changes in wording.* diff --git a/public/posts/2007.05.05-a-new-way-to-look-at-networking.md b/public/posts/2007.05.05-a-new-way-to-look-at-networking.md new file mode 100644 index 0000000..ec77f0d --- /dev/null +++ b/public/posts/2007.05.05-a-new-way-to-look-at-networking.md @@ -0,0 +1,20 @@ +Title: A New Way to Look at Networking +Date: May 5, 2007 +Timestamp: 1178406600 +Author: sjs +Tags: technology, networking +---- + +Van Jacobson gave a Google Tech Talk on some of his ideas of how a modern, global network could work more effectively, and with more trust in the data which changes many hands on its journey to its final destination. + + + +The man is very smart and his ideas are fascinating. He has the experience and knowledge to see the big picture and what can be done to solve some of the new problems we have. He starts with the beginning of the phone networks and then goes on to briefly explain the origins of the ARPAnet, which evolved into the modern Internet and TCP/IP and the many other protocols we use daily (often behind the scenes). + +He explains the problems that were faced while using the phone networks for data, and how they were solved by realizing that a new problem had risen and needed a new, different solution. He then goes to explain how the Internet has changed significantly from the time it started off in research centres, schools, and government offices into what it is today (lots of identical bytes being redundantly pushed to many consumers, where broadcast would be more appropriate and efficient). + +If you have some time I really suggest watching this talk. I would love to research some of the things he spoke about if I ever got the chance. I'm sure they'll be on my mind anyway and inevitably I'll end up playing around with layering crap onto IPV6 and what not. Deep down I love coding in C and I think developing a protocol would be pretty fun. I'd learn a lot in any case. diff --git a/public/posts/2007.05.05-gotta-love-the-ferry-ride.md b/public/posts/2007.05.05-gotta-love-the-ferry-ride.md new file mode 100644 index 0000000..6f923d6 --- /dev/null +++ b/public/posts/2007.05.05-gotta-love-the-ferry-ride.md @@ -0,0 +1,10 @@ +Title: Gotta Love the Ferry Ride +Date: May 5, 2007 +Timestamp: 1178364300 +Author: sjs +Tags: life, photo, bc, victoria +---- + +I lived in Victoria for over a year before I ever rode the ferry between Vancouver Island and Tsawwassen (ignoring the time I was in BC with my family about 16 years ago, that is). I always just flew in and out of Victoria directly. The ferry is awesome and the view is incredible, navigating through all those little islands. Last time I rode the ferry I snapped this shot. It's possibly the best picture I've taken on that trip. + +Sunset diff --git a/public/posts/2007.05.09-dtrace-ruby-goodness-for-sun.md b/public/posts/2007.05.09-dtrace-ruby-goodness-for-sun.md new file mode 100644 index 0000000..2a62bca --- /dev/null +++ b/public/posts/2007.05.09-dtrace-ruby-goodness-for-sun.md @@ -0,0 +1,10 @@ +Title: dtrace + Ruby = Goodness for Sun +Date: May 9, 2007 +Timestamp: 1178725500 +Author: sjs +Tags: ruby, dtrace, sun +---- + +Suddenly I feel the urge to try out Solaris for i386 again. Last time I gave it a shot was when it was first released, and all I ever got out of the CD was a white screen. It's been 2-3 years since then and it should be well-tested. I'll try to install it into a VM first using the ISO and potentially save myself a CD. (I don't even think I have blank CDs lying around anymore, only DVDs.) + +The culprit. diff --git a/public/posts/2007.05.09-i-cant-wait-to-see-what-matt-stone-trey-parker-do-with-this.md b/public/posts/2007.05.09-i-cant-wait-to-see-what-matt-stone-trey-parker-do-with-this.md new file mode 100644 index 0000000..77a00d3 --- /dev/null +++ b/public/posts/2007.05.09-i-cant-wait-to-see-what-matt-stone-trey-parker-do-with-this.md @@ -0,0 +1,18 @@ +Title: I Can't Wait to See What Trey Parker & Matt Stone Do With This +Date: May 9, 2007 +Timestamp: 1178746440 +Author: sjs +Tags: crazy +---- + +I'd just like to say, bwa ha ha ha! + +Summary: Paris Hilton drove with a suspended license and is facing 45 days in jail. Now she's reaching out to lord knows who on her MySpace page to petition The Governator to pardon her. I might cry if I weren't pissing myself laughing. + +Paris Hilton is out of her mind, living in some fantasy world separate from Earth. Pathetic doesn't begin to describe this plea for help from her own stupidity. She knowingly and willingly disobeyed the law, got busted, and then proceeded to claim that: + +> *"She provides hope for young people all over the U.S. __and the world__. She provides beauty and excitement to (most of) our __otherwise mundane__ lives."* + +I take this as a learning experience. For example, I learned that the US is no longer part of the world. + +Flat out crazy, insane, not of sound mind. She is not any sort of hope, inspiration or role model for anyone. diff --git a/public/posts/2007.05.10-enumerable-pluck-and-string-to_proc-for-ruby.md b/public/posts/2007.05.10-enumerable-pluck-and-string-to_proc-for-ruby.md new file mode 100644 index 0000000..2de0199 --- /dev/null +++ b/public/posts/2007.05.10-enumerable-pluck-and-string-to_proc-for-ruby.md @@ -0,0 +1,125 @@ +Title: Enumurable#pluck and String#to_proc for Ruby +Date: May 10, 2007 +Timestamp: 1178838840 +Author: sjs +Tags: ruby, extensions +---- + +I wanted a method analogous to Prototype's pluck and invoke in Rails for building lists for options_for_select. Yes, I know about options_from_collection_for_select. + +I wanted something more general that I can use anywhere - not just in Rails - so I wrote one. In a second I'll introduce Enumerable#pluck, but first we need some other methods to help implement it nicely. + +First you need Symbol#to_proc, which shouldn't need an introduction. If you're using Rails you have this already. + +
    Symbol#to_proc
    class Symbol
    +  # Turns a symbol into a proc.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| p.birthdate }
    +  #   people.map(&:birthdate)
    +  #
    +  def to_proc
    +    Proc.new {|thing, *args| thing.send(self, *args)}
    +  end
    +end
    +
    + +Next we define String#to_proc, which is nearly identical to the Array#to_proc method I previously wrote about. + +
    String#to_proc
    class String
    +  # Turns a string into a proc.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| p.birthdate.year }
    +  #   people.map(&'birthdate.year')
    +  #
    +  def to_proc
    +    Proc.new do |*args|
    +      split('.').inject(args.shift) do |thing, msg|
    +        thing = thing.send(msg.to_sym, *args)
    +      end
    +    end
    +  end
    +end
    +
    + +Finally there's Enumerable#to_proc which returns a proc that passes its parameter through each of its members and collects their results. It's easier to explain by example. + +
    Enumerable#to_proc
    module Enumerable
    +  # Effectively treats itself as a list of transformations, and returns a proc
    +  # which maps values to a list of the results of applying each transformation
    +  # in that list to the value.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| [p.birthdate, p.email] }
    +  #   people.map(&[:birthdate, :email])
    +  #
    +  def to_proc
    +    @procs ||= map(&:to_proc)
    +    Proc.new do |thing, *args|
    +      @procs.map do |proc|
    +        proc.call(thing, *args)
    +      end
    +    end
    +  end
    +end
    + +Here's the cool part, Enumerable#pluck for Ruby in all its glory. + +
    Enumerable#pluck
    module Enumerable
    +  # Use this to pluck values from objects, especially useful for ActiveRecord models.
    +  # This is analogous to Prototype's Enumerable.pluck method but more powerful.
    +  #
    +  # You can pluck values simply, like so:
    +  #   >> people.pluck(:last_name)  #=> ['Samhuri', 'Jones', ...]
    +  #
    +  # But with Symbol#to_proc defined this is effectively the same as:
    +  #   >> people.map(&:last_name)   #=> ['Samhuri', 'Jones', ...]
    +  #
    +  # Where pluck's power becomes evident is when you want to do something like:
    +  #   >> people.pluck(:name, :address, :phone)
    +  #        #=> [['Johnny Canuck', '123 Maple Lane', '416-555-124'], ...]
    +  #
    +  # Instead of:
    +  #   >> people.map { |p| [p.name, p.address, p.phone] }
    +  #
    +  #   # map each person to: [person.country.code, person.id]
    +  #   >> people.pluck('country.code', :id)
    +  #        #=> [['US', 1], ['CA', 2], ...]
    +  #
    +  def pluck(*args)
    +    # Thanks to Symbol#to_proc, Enumerable#to_proc and String#to_proc this Just Works(tm)
    +    map(&args)
    +  end
    +end
    + +I wrote another version without using the various #to_proc methods so as to work with a standard Ruby while only patching 1 module. + +
    module Enumerable
    +  # A version of pluck which doesn't require any to_proc methods.
    +  def pluck(*args)
    +    procs = args.map do |msgs|
    +      # always operate on lists of messages
    +      if String === msgs
    +        msgs = msgs.split('.').map {|a| a.to_sym} # allow 'country.code'
    +      elsif !(Enumerable === msgs)
    +        msgs = [msgs]
    +      end
    +      Proc.new do |orig|
    +        msgs.inject(orig) { |thing, msg| thing = thing.send(msg) }
    +      end
    +    end
    +
    +    if procs.size == 1
    +      map(&procs.first)
    +    else
    +      map do |thing|
    +        procs.map { |proc| proc.call(thing) }
    +      end
    +    end
    +  end
    +end
    + +It's just icing on the cake considering Ruby's convenient block syntax, but there it is. Do with it what you will. You can change or extend any of these to support drilling down into hashes quite easily too. + +*Update #1: Fixed a potential performance issue in Enumerable#to_proc by saving the results of to_proc in @procs.* \ No newline at end of file diff --git a/public/posts/2007.05.10-rails-plugins-link-dump.md b/public/posts/2007.05.10-rails-plugins-link-dump.md new file mode 100644 index 0000000..a831497 --- /dev/null +++ b/public/posts/2007.05.10-rails-plugins-link-dump.md @@ -0,0 +1,15 @@ +Title: Rails Plugins (link dump) +Date: May 10, 2007 +Timestamp: 1178756520 +Author: sjs +Tags: rails +---- + +Some Rails plugins I find useful: + + * Simply Helpful + * Focus-fu + * Sexy Migrations + * TextMate Footnotes (just awesome) + * acts\_as\_taggable\_on\_steroids + * acts\_as\_textiled diff --git a/public/posts/2007.05.15-dumping-objects-to-the-browser-in-rails.md b/public/posts/2007.05.15-dumping-objects-to-the-browser-in-rails.md new file mode 100644 index 0000000..f2dc095 --- /dev/null +++ b/public/posts/2007.05.15-dumping-objects-to-the-browser-in-rails.md @@ -0,0 +1,32 @@ +Title: Dumping Objects to the Browser in Rails +Date: May 15, 2007 +Timestamp: 1179261480 +Author: sjs +Tags: rails +---- + +Here's an easy way to solve a problem that may have nagged you as it did me. Simply using foo.inspect to dump out some object to the browser dumps one long string which is barely useful except for short strings and the like. The ideal output is already available using the PrettyPrint module so we just need to use it. + + +Unfortunately typing
    <%= PP.pp(@something, '') %>
    to quickly debug some possibly large object (or collection) can get old fast so we need a shortcut. + + +Taking the definition of Object#pp_s from the extensions project it's trivial to create a helper method to just dump out an object in a reasonable manner. + + +
    /app/helpers/application_helper.rb
    def dump(thing)
    +  s = StringIO.new
    +  PP.pp(thing, s)
    +  s.string
    +end
    + +Alternatively you could do as the extensions folks do and actually define Object#pp_s so you can use it in your logs or anywhere else you may want to inspect an object. If you do this you probably want to change the dump helper method accordingly in case you decide to change pp_s in the future. + + +
    lib/local_support/core_ext/object.rb
    class Object
    +  def pp_s
    +    pps = StringIO.new
    +    PP.pp(self, pps)
    +    pps.string
    +  end
    +end
    diff --git a/public/posts/2007.05.16-cheating-at-life-in-general.md b/public/posts/2007.05.16-cheating-at-life-in-general.md new file mode 100644 index 0000000..f39be95 --- /dev/null +++ b/public/posts/2007.05.16-cheating-at-life-in-general.md @@ -0,0 +1,17 @@ +Title: Cheating at Life in General +Date: May 16, 2007 +Timestamp: 1179308760 +Author: sjs +Tags: cheat, vim, emacs, textmate +---- + +*NB: My definition of life is slightly skewed by my being somewhat of a geek* + +Luckily no one in the real world cares if you cheat. Most of life is open-book, but for the times when you just need to find something quick the answer, of course, is to [cheat](http://cheat.errtheblog.com/) profusely. + + +I've only checked out a few of the cheat sheets but they are of high quality and their wiki-like nature means if they suck and you have time you can help out. I was very pleased to find that there are a number of zsh cheats already. + +They certainly know the way to my heart! Ruby, Rails, TextMate*, vim*, zsh, screen. That'll do snake. That'll do. + +*\* There are cheats for emacs, jEdit, and [e](http://www.e-texteditor.com/) too if TextMate and/or vim don't tickle your fancy.* diff --git a/public/posts/2007.05.18-iphone-humour.md b/public/posts/2007.05.18-iphone-humour.md new file mode 100644 index 0000000..535ff7d --- /dev/null +++ b/public/posts/2007.05.18-iphone-humour.md @@ -0,0 +1,14 @@ +Title: iPhone Humour +Date: May 18, 2007 +Timestamp: 1179513240 +Author: sjs +Tags: apple, funny, iphone +---- + +Love it or hate it - even though it's not even out yet - the iPhone has spawned at least 2 good jokes. + +[The other iPhone lawsuit](http://www.geekculture.com/joyoftech/joyarchives/910.html) (GeekCulture.com) + +[A comment on slashdot](http://apple.slashdot.org/comments.pl?sid=235163&cid=19174829): + +> "I'm waiting for the iPhone-shuffle, no display, just a button to call a random person on your contacts list." diff --git a/public/posts/2007.05.22-inspirado.md b/public/posts/2007.05.22-inspirado.md new file mode 100644 index 0000000..ad28447 --- /dev/null +++ b/public/posts/2007.05.22-inspirado.md @@ -0,0 +1,18 @@ +Title: Inspirado +Date: May 22, 2007 +Timestamp: 1179865380 +Author: sjs +Tags: rails, inspirado +---- + +spyderous is a Gentoo dev and I read his posts via the Gentoo planet (and again on the freedesktop.org planet). + +He recently mentioned an idea to foster participation in Gentoo (or any other project) by aggregating personal project plans for people to browse. I thought it sounded cool so I started coding and came up with what I call inspirado. + +It's fairly basic so far but it's only a week old. It is RESTful and you can get XML for most pages by appending .xml to the URL (or by using curl and setting the HTTP Accept header). Eventually Atom and/or RSS should be available as well. + +Note that everything you see there is purely for testing purposes and any changes you make are most likely going to be blown away. + +There are several features on my TODO list but I'd love to hear about any you might have. Write to sami.samhuri@gmail.com if you have suggestions or anything else to say. + +(Inspirado is, of course, a Rails app.) diff --git a/public/posts/2007.05.26-finnish-court-rules-css-ineffective-at-protecting-dvds.md b/public/posts/2007.05.26-finnish-court-rules-css-ineffective-at-protecting-dvds.md new file mode 100644 index 0000000..01441fb --- /dev/null +++ b/public/posts/2007.05.26-finnish-court-rules-css-ineffective-at-protecting-dvds.md @@ -0,0 +1,8 @@ +Title: Finnish court rules CSS ineffective at protecting DVDs +Date: May 26, 2007 +Timestamp: 1180175040 +Author: sjs +Tags: drm +---- + +It's nice to see people making sane calls on issues like this. Ars has a nice summary and there's also a press release. diff --git a/public/posts/2007.06.08-301-moved-permanently.md b/public/posts/2007.06.08-301-moved-permanently.md new file mode 100644 index 0000000..b447228 --- /dev/null +++ b/public/posts/2007.06.08-301-moved-permanently.md @@ -0,0 +1,8 @@ +Title: 301 moved permanently +Date: June 8, 2007 +Timestamp: 1181350800 +Author: sjs +Tags: life +---- + +Last weekend I moved out of the apartment I lived in for the last 3 1/2 years. Moving was a cinch thanks to a friend's garage, conveniently placed smack between my old place and the new one. Google maps tells me that I moved just under 3.4 km, which is 2.1 mi for the metric impaired, so it wasn't much of a move at all! My roommate and I live in the basement of a house split into 3 apartments. Our upstairs neighbours are friendly and seem pretty cool, except one lady upstairs seems a bit strange. It's a great place though and in the winter the wood stove fireplace is going to be awesome. diff --git a/public/posts/2007.06.08-so-long-typo-and-thanks-for-all-the-timeouts.md b/public/posts/2007.06.08-so-long-typo-and-thanks-for-all-the-timeouts.md new file mode 100644 index 0000000..12e9d7c --- /dev/null +++ b/public/posts/2007.06.08-so-long-typo-and-thanks-for-all-the-timeouts.md @@ -0,0 +1,35 @@ +Title: so long typo (and thanks for all the timeouts) +Date: June 8, 2007 +Timestamp: 1181350860 +Author: sjs +Tags: mephisto, typo +---- + +Well for just over a year Typo ran the show. I thought I had worked out most of the kinks with Typo and Dreamhost but the latest problem I ran into was pretty major. I couldn't post new articles. If the stars aligned perfectly and I sacrificed baby animals and virgins, every now and then I could get it to work. Ok, all I really had to do was refresh several dozen times, waiting 1 minute for it to timeout every time, but it sucked nonetheless. + +Recently I had looked at converting Typo to Mephisto and it seemed pretty painless. I installed Mephisto and followed whatever instructions I found via Google and it all just worked, with one caveat. The Typo converter for Mephisto only supports Typo's schema version 56, while my Typo schema was at version 61. Rather than migrate backwards I brought Mephisto's Typo converter up to date instead. If you're interested, download the patch. The patch is relative to vendor/plugins, so patch accordingly. + +After running that code snippet to fix my tags, I decided to completely ditch categories in favour of tags. I tagged each new Mephisto article with a tag for each Typo category it had previously belonged to. I fired up RAILS_ENV=production script/console and typed something similar to the following: + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    require 'converters/base'
    +require 'converters/typo'
    +articles = Typo::Article.find(:all).map {|a| [a, Article.find_by_permalink(a.permalink)] }
    +articles.each do |ta, ma|
    +  next if ma.nil?
    +  ma.tags << Tag.find_or_create(ta.categories.map(&:name))
    +end
    + + +When I say something similar I mean exactly that. I just typed that from memory so it may not work, or even be syntactically correct. If any permalinks changed then you'll have to manually add new tags corresponding to old Typo categories. The only case where this bit me was when I had edited the title of an article, in which case the new Mephisto permalink matched the new title while the Typo permalink matched the initial title, whatever it was. + +I really dig Mephisto so far. It's snappier than Typo and the admin interface is slick. I followed the herd and went with the scribbish theme. Perhaps I'll get around to customizing it sometime, but who knows maybe I'll like a white background for a change. diff --git a/public/posts/2007.06.14-more-scheming-with-haskell.md b/public/posts/2007.06.14-more-scheming-with-haskell.md new file mode 100644 index 0000000..007edc3 --- /dev/null +++ b/public/posts/2007.06.14-more-scheming-with-haskell.md @@ -0,0 +1,96 @@ +Title: More Scheming with Haskell +Date: June 14, 2007 +Timestamp: 1181783340 +Author: sjs +Tags: coding, haskell, scheme +---- + +It's been a little while since I wrote about Haskell and the Scheme interpreter I've been using to learn and play with both Haskell and Scheme. I finished the tutorial and got myself a working Scheme interpreter and indeed it has been fun to use it for trying out little things now and then. (Normally I would use Emacs or Dr. Scheme for that sort of thing.) There certainly are interesting things to try floating around da intranet. And also things to read and learn from, such as misp (via Moonbase). + +*I'm going to describe two new features of my Scheme in this post. The second one is more interesting and was more fun to implement (cond).* + +### Pasing Scheme integers ### + +Last time I left off at parsing R5RS compliant numbers, which is exercise 3.3.4 if you're following along the tutorial. Only integers in binary, octal, decimal, and hexadecimal are parsed right now. The syntaxes for those are #b101010, #o52, 42 (or #d42), and #x2a, respectively. To parse these we use the readOct, readDec, readHex, and readInt functions provided by the Numeric module, and import them thusly: + + import Numeric (readOct, readDec, readHex, readInt) + +In order to parse binary digits we need to write a few short functions to help us out. For some reason I couldn't find binDigit, isBinDigit and readBin in their respective modules but luckily they're trivial to implement. The first two are self-explanatory, as is the third if you look at the implementation of its relatives for larger bases. In a nutshell readBin says to: "read an integer in base 2, validating digits with isBinDigit." + +
    -- parse a binary digit, analagous to decDigit, octDigit, hexDigit
    +binDigit :: Parser Char
    +binDigit = oneOf "01" 
    +
    +-- analogous to isDigit, isOctdigit, isHexDigit
    +isBinDigit :: Char - Bool
    +isBinDigit c = (c == '0' || c == '1')
    +
    +-- analogous to readDec, readOct, readHex
    +readBin :: (Integral a) = ReadS a
    +readBin = readInt 2 isBinDigit digitToInt
    + +The next step is to augment parseNumber so that it can handle R5RS numbers in addition to regular decimal numbers. To refresh, the tutorial's parseNumber function looks like this: + + parseNumber :: Parser LispVal + parseNumber = liftM (Number . read) $ many1 digit + +Three more lines in this function will give us a decent starting point: + + parseNumber = do char '#' + base <- oneOf "bdox" + parseDigits base + +Translation: First look for an R5RS style base, and if found call parseDigits with the given base to do the dirty work. If that fails then fall back to parsing a boring old string of decimal digits. + +That brings us to actually parsing the numbers. parseDigits is simple, but there might be a more Haskell-y way of doing this. + +
    -- Parse a string of digits in the given base.
    +parseDigits :: Char - Parser LispVal
    +parseDigits base = many1 d >>= return
    +    where d = case base of
    +                'b' -> binDigit
    +                'd' -> digit
    +                'o' -> octDigit
    +                'x' -> hexDigit
    +
    + +The trickiest part of all this was figuring out how to use the various readFoo functions properly. They return a list of pairs so head grabs the first pair and fst grabs the first element of the pair. Once I had that straight it was smooth sailing. Having done this, parsing R5RS characters (#\a, #\Z, #\?, ...) is a breeze so I won't bore you with that. + +### The cond function ### + +It still takes me some time to knit together meaningful Haskell statements. Tonight I spent said time cobbling together an implementation of cond as a new special form. Have a look at the code. The explanation follows. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +
    eval env (List (Atom "cond" : List (Atom "else" : exprs) : [])) =
    +    liftM last $ mapM (eval env) exprs
    +eval env (List (Atom "cond" : List (pred : conseq) : rest)) = 
    +    do result <- eval env $ pred
    +       case result of
    +         Bool False -> case rest of
    +                         [] -> return $ List []
    +                         _ -> eval env $ List (Atom "cond" : rest)
    +         _ -> liftM last $ mapM (eval env) conseq
    + + + * __Lines 1-2:__ Handle else clauses by evaluating the given expression(s), returning the last result. It must come first or it's overlapped by the next pattern. + * __Line 3:__ Evaluate a cond by splitting the first condition into predicate and consequence, tuck the remaining conditions into rest for later. + * __Line 4:__ Evaluate pred + * __Line 5:__ and if the result is: + * __Line 6:__ #f then look at the rest of the conditions. + * __Line 7:__ If there are no more conditions return the empty list. + * __Line 8:__ Otherwise call ourselves recursively with the remaining conditions. + * __Line 9:__ Anything other than #f is considered true and causes conseq to be evaluated and returned. Like else, conseq can be a sequence of expressions. + +So far my Scheme weighs in at 621 lines, 200 more than the tutorial's final code listing. Hopefully I'll keep adding things on my TODO list and it will grow a little bit more. Now that I have cond it will be more fun to expand my stdlib.scm as well. diff --git a/public/posts/2007.06.14-testspec-on-rails-declared-awesome-just-one-catch.md b/public/posts/2007.06.14-testspec-on-rails-declared-awesome-just-one-catch.md new file mode 100644 index 0000000..fa82be9 --- /dev/null +++ b/public/posts/2007.06.14-testspec-on-rails-declared-awesome-just-one-catch.md @@ -0,0 +1,96 @@ +Title: test/spec on rails declared awesome, just one catch +Date: June 14, 2007 +Timestamp: 1181830860 +Author: sjs +Tags: bdd, rails, test/spec +---- + +This last week I've been getting to know test/spec via err's test/spec on rails plugin. I have to say that I really dig this method of testing my code and I look forward to trying out some actual BDD in the future. + +I did hit a little snag with functional testing though. The method of declaring which controller to use takes the form: + + + + + +
    
    +
    use_controller :foo
    + + +and can be placed in the setup method, like so: + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    # in test/functional/sessions_controller_test.rb
    +
    +context "A guest" do
    +  fixtures :users
    +
    +  setup do
    +    use_controller :sessions
    +  end
    +
    +  specify "can login" do
    +    post :create, :username => 'sjs', :password => 'blah'
    +    response.should.redirect_to user_url(users(:sjs))
    +    ...
    +  end
    +end
    + + +This is great and the test will work. But let's say that I have another controller that guests can access: + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +
    # in test/functional/foo_controller_test.rb
    +
    +context "A guest" do
    +  setup do
    +    use_controller :foo
    +  end
    +
    +  specify "can do foo stuff" do
    +    get :fooriffic
    +    status.should.be :success
    +    ...
    +  end
    +end
    + + +This test will pass on its own as well, which is what really tripped me up. When I ran my tests individually as I wrote them, they passed. When I ran rake test:functionals this morning and saw over a dozen failures and errors I was pretty alarmed. Then I looked at the errors and was thoroughly confused. Of course the action fooriffic can't be found in SessionsController, it lives in FooController and that's the controller I said to use! What gives?! + +The problem is that test/spec only creates one context with a specific name, and re-uses that context on subsequent tests using the same context name. The various setup methods are all added to a list and each one is executed, not just the one in the same context block as the specs. I can see how that's useful, but for me right now it's just a hinderance as I'd have to uniquely name each context. "Another guest" just looks strange in a file by itself, and I want my tests to work with my brain not against it. + +My solution was to just create a new context each time and re-use nothing. Only 2 lines in test/spec need to be changed to achieve this, but I'm not sure if what I'm doing is a bad idea. My tests pass and right now that's basically all I care about though. diff --git a/public/posts/2007.06.15-begging-the-question.md b/public/posts/2007.06.15-begging-the-question.md new file mode 100644 index 0000000..cd827e5 --- /dev/null +++ b/public/posts/2007.06.15-begging-the-question.md @@ -0,0 +1,23 @@ +Title: Begging the question +Date: June 15, 2007 +Timestamp: 1181933340 +Author: sjs +Tags: english, life, pedantry +---- + +I'm currently reading SICP since it's highly recommended by many people, available for free, and interesting. The fact that I have a little Scheme interpreter to play with makes it much more fun since I can add missing functionality to it as I progress through the book, thereby learning more Haskell in the process. Yay! + +Anyway I was very pleased to see the only correct usage of the phrase "begs the question" I have seen in a while. It's a pet peeve of mine, but I have submitted myself to the fact that the phrase is so oft used to mean "begs for the following question to be asked..." that it may as well be re-defined. In its correct usage the sentence seems to hang there if you try to apply the commonly mistaken meaning to it. That's all very hazy so here's the usage in SICP (emphasis my own): + +
    As a case in point, consider the problem of computing square roots. We can define the square-root function as √x = the y such that y ≥ 0 and y² = x + +This describes a perfectly legitimate mathematical function. We could use it to recognize whether one number is the square root of another, or to derive facts about square roots in general. On the other hand, the definition does not describe a procedure. Indeed, it tells us almost nothing about how to actually find the square root of a given number. It will not help matters to rephrase this definition in pseudo-Lisp: + +
    (define (sqrt x)
    +  (the y (and (= y 0)
    +              (= (square y) x))))
    + +This only begs the question. +
    + +Begging the question is to assume what one is trying to prove (or here, define) and use that as the basis for a conclusion. Read the Wikipedia article for a better definition and some nice examples. diff --git a/public/posts/2007.06.18-back-on-gentoo-trying-new-things.md b/public/posts/2007.06.18-back-on-gentoo-trying-new-things.md new file mode 100644 index 0000000..66c838a --- /dev/null +++ b/public/posts/2007.06.18-back-on-gentoo-trying-new-things.md @@ -0,0 +1,26 @@ +Title: Back on Gentoo, trying new things +Date: June 18, 2007 +Timestamp: 1182215100 +Author: sjs +Tags: emacs, gentoo, linux, vim +---- + +I started using my Gentoo box for development again and there are a few things about Linux I didn't realize I had been missing. + +### Shell completion is awesome out of the box ### + +zsh has an impressive completion system but I just don't feel the urge to ever customize it extensively. I just use the basic completion stuff on OS X because it's easy. On Gentoo I have rake tasks and all sorts of other crap completed for me by including a few lines in my .zshrc (iirc a script does this automatically anyway). Generally Linux distros try to knit everything together nicely so you never even think about things like whether or not a package will have readline support, and default configs will be tweaked and enhanced beyond the official zsh package. + +### Linux is stable. Really stable. ### + +While people bash Microsoft daily for tying the GUI layer to the kernel, Apple seems to get away with it scot-free. I don't know if it's caused by my external display hooked up to the dock, or the Prolific Firewire chip in my external disk enclosure but something causes the mysterious "music plays till the end of the song, mouse can be moved, but nothing works" bug now and then and all I can do is a hard reset. + +On Linux I currently use Fluxbox so everything is rock solid and fast (except Firefox! ;-), but in the extremely rare event that shit does hit the fan usually only a single app will crash, though sometimes X (and hence many others) go with it. A sudo /etc/init.d/gdm restart fixes that. The only times I've had to hard reset Linux was because of a random bug (strangely similar to my MacBook bug) with Nvidia's driver with dual head setups. All this is pretty moot since Linux is generally just stable. + +Those are 2 relatively small things but the added comfort they provide is very nice. + +In the spirit of switching things up I'm going to forgo my usual routine of using gvim on Linux and try out emacs. I've been frustrated with vim's lack of a decent file browser and I've never much liked the tree plugin. Vim is a fantastic editor when it comes to navigating, slicing, and dicing text. After that it sort of falls flat though. After getting hooked on TextMate I have come to love integration with all sorts of external apps such as Subversion, rake, and the shell because it makes my work easier. Emacs seems to embrace that sort of philosophy and I'm more impressed with the efforts to integrate Rails development into Emacs than vim. I'm typing this post using the Textile mode for Emacs and the markup is rendered giving me a live preview of my post. It's not WYSIWYG like Typo's preview but it's still pretty damn cool. I think can get used to emacs. + +I'm just waiting for a bunch of crap to compile – because I use Gentoo – and soon I'll have a Gtk-enabled Emacs to work in. If I can paste to and from Firefox then I'll be happy. I'll have to open this in vim or gedit to paste it into Firefox, funny! + +I'm also going to try replacing a couple of desktop apps with web alternatives. I'm starting with 2 no-brainers: mail and feeds with Gmail and Google Reader. I never got into the Gmail craze and never really even used Gmail very much. After looking at the shortcuts I think I can get used to it. Seeing j/k for up/down is always nice. Thunderbird is ok but there isn't a mail client on Linux that I really like, except mutt. That played a part in my Gmail choice. I hadn't used G-Reader before either and it seems alright, but it'll be hard to beat NetNewsWire. diff --git a/public/posts/2007.06.20-reinventing-the-wheel.md b/public/posts/2007.06.20-reinventing-the-wheel.md new file mode 100644 index 0000000..44a1247 --- /dev/null +++ b/public/posts/2007.06.20-reinventing-the-wheel.md @@ -0,0 +1,19 @@ +Title: Reinventing the wheel +Date: June 20, 2007 +Timestamp: 1182356820 +Author: sjs +Tags: emacs, snippets +---- + +Emacs is very impressive. I only felt lost and unproductive for minutes and now it seems natural to use and get around in. I've got ElSchemo set as the default scheme, and running inferior processes interactively is an absolute dream. My scheme doesn't have readline support (which bothers me to the point where I've thought about adding it just so I can use the thing) but when running it under Emacs there's absoutely no need for anything like that since I have the power of my editor when interacting with any program. + +There has been a considerable amount of work done to aide in Rails development which makes Emacs especially comfortable for me. I now know why people have Emacs windows maximized on their screens. Because of its age Emacs is a handy window manager that basically eliminates the need for anything like GNU screen or a window manager such as Rat poison (which is great if you like screen), just maximize that Emacs "frame" or open one for each display and get to it. If you need a shell you just split the window and run your shell, when you're done you can easily switch back to your editing and your shell will wait in the background until you need it again. With rails-mode on I can run script/console (or switch back to it) with C-c C-c s c. My zsh alias for script/console is sc and I have other similarly succint ones for other stuff, so I took right to the shortcuts for all the handy things that I no longer have to switch applications to do: + + * C-c C-c . – Run the tests for this file. If I'm in a unit test it runs it, if I'm in the model it runs the corresponding unit tests. + * C-c C-c w s – Run the web server (script/server). + * C-c C-c t – Run tests. The last value entered is the default choice, and the options are analogous to the rake test:* tasks. + * and so on... + +The Rails integration is simply stunning and I could go on all day about the mature indentation support, the Speedbar and what not, but I won't. I'm fairly sure that Emacs has taken the place of TextMate as my weapon of choice now, on all platforms. And after only 2 days! + +Anyway, the point of all this was to mention the one thing that's missing: support for intelligent snippets which insert text at more than one point in the document (well, they appear to do so). I don't have any E-Lisp-fu to break out and solve the deficiency but if it ever bugs me enough I might try implementing it for Emacs one day. If they were useful to me outside of writing migrations I might have more incentive to do so, but I guess they aren't useful in normal editing situations (maybe I just haven't recognised the need). diff --git a/public/posts/2007.06.22-embrace-the-database.md b/public/posts/2007.06.22-embrace-the-database.md new file mode 100644 index 0000000..ea41339 --- /dev/null +++ b/public/posts/2007.06.22-embrace-the-database.md @@ -0,0 +1,34 @@ +Title: Embrace the database +Date: June 22, 2007 +Timestamp: 1182507240 +Author: sjs +Tags: activerecord, rails, ruby +---- + +If you drink the Rails koolaid you may have read the notorious single layer of cleverness post by DHH. [5th post on the archive page] In a nutshell he states that it's better to have a single point of cleverness when it comes to business logic. The reasons for this include staying agile, staying in Ruby all the time, and being able to switch the back-end DB at any time. Put the logic in ActiveRecord and use the DB as a dumb data store, that is the Rails way. It's simple. It works. You don't need to be a DBA to be a Rails developer. + +Stephen created a Rails plugin called dependent-raise which imitates a foreign key constraint inside of Rails. I want to try this out because I believe that data integrity is fairly important, but it's really starting to make me think about this single point of cleverness idea. + +Are we not reinventing the wheel by employing methods such as this in our code? Capable DBs already do this sort of thing for us. I don't necessarily think it's bad to implement this sort of thing, but I think it's a symptom of NIH syndrome. Instead of reinventing this kind of thing why don't we embrace the DB as a semi-intelligent data store? The work has been done all we have to do is exploit it via Rails. + +There are a few reasons that the Rails folks choose not to do so but perhaps some of them could be worked around. Adapting your solution as you progress and realise that things aren't exactly as you thought they were... I believe the word for that sort of thing is agility. + +### Database agnosticism ### + +From SQLite to Oracle, just configure the connection, migrate, and run your app on any database. One of the biggest Rails myths that is backed by the Rails team themselves. It takes a fair amount of work to ensure that any significant app is fully agnostic. Sure you can develop on SQLite and deploy on MySQL without much trouble but there are significant diffirences between RDBMSs that will manifest themselves if you create an app that's more than a toy. Oh, you used finder_sql? Sorry but chances are your app is no longer DB agnostic. FAIL. + +**Solution:** Drop the lie. Tell people the truth. Theoretically, theory and practice are the same; in practice they are not. Be honest that it's *possible* to be DB-agnostic but can be a challenge. Under no circumstances should we shun something useful in the name of claiming to be DB-agnostic. + +### Staying agile ### + +If we start making use of FK constraints then we'll have to make changes to both our DB and our code. This makes change more time-consuming and error-prone which means change is less likely to happen. This goes against the grain of an agile methodology. Or does it? + +**Solution:** Rails should use the features of the DB to keep data intact and fall back on an AR-only solution only if the DB doesn't support the operation. There doesn't need to be any duplication in logic rules either. If Rails could recognise a FK constraint that cascades on delete it could set up the `has_many :foos, :dependent => :destroy` relation for us. In fact I only see our code becoming DRYer (maybe even too DRY[1]). + +### Staying in Ruby ### + +Using the DB from within Ruby is a solved problem. I don't see why this couldn't be extended to handle more of the DB as well. Use Ruby, but use it intelligently by embracing outside tools to get the job done. + +Many relationships could be derived from constraints as people have pointed out before. There are benefits to using the features of a decent RDBMS, and in some cases I think that we might be losing by not making use of them. I am not saying we should move everything to the DB, I am saying that we should exploit the implemented and debugged capabilities of our RDBMSs the best we can while practicing the agile methods we know and love, all from within Ruby. + +[1] I make liberal use of annotate_models as it is. diff --git a/public/posts/2007.06.23-emacs-for-textmate-junkies.md b/public/posts/2007.06.23-emacs-for-textmate-junkies.md new file mode 100644 index 0000000..697d34c --- /dev/null +++ b/public/posts/2007.06.23-emacs-for-textmate-junkies.md @@ -0,0 +1,140 @@ +Title: Emacs for TextMate junkies +Date: June 23, 2007 +Timestamp: 1182565020 +Author: sjs +Tags: emacs, textmate +---- + +*Update #1: What I first posted will take out your < key by mistake (it's available via `C-q <`), it has since been revised to Do The Right Thing.* + +*Update #2: Thanks to an anonymouse[sic] commenter this code is a little cleaner.* + +*Update #3: I should read the Emacs manual sometime, especially since I have it in dead-tree form. Check out skeleton pairs in the Emacs manual.* + +Despite my current infatuation with Emacs there are many reasons I started using TextMate, especially little time-savers that are very addictive. I'll talk about one of those features tonight. When you have text selected in TextMate and you hit say the ' (single quote) then TextMate will surround the selected text with single quotes. The same goes for double quotes, parentheses, brackets, and braces. This little trick is one of my favourites so I had to come up with something similar in Emacs. It was easy since a mailing list post has a solution for surrounding the current region with tags, which served as a great starting point. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    (defun surround-region-with-tag (tag-name beg end)
    +      (interactive "sTag name: \nr")
    +      (save-excursion
    +        (goto-char beg)
    +        (insert "<" tag-name ">")
    +        (goto-char (+ end 2 (length tag-name)))
    +        (insert "</" tag-name ">")))
    + + +With a little modification I now have the following in my ~/.emacs file: + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +
    ;; help out a TextMate junkie
    +
    +(defun wrap-region (left right beg end)
    +  "Wrap the region in arbitrary text, LEFT goes to the left and RIGHT goes to the right."
    +  (interactive)
    +  (save-excursion
    +    (goto-char beg)
    +    (insert left)
    +    (goto-char (+ end (length left)))
    +    (insert right)))
    +
    +(defmacro wrap-region-with-function (left right)
    +  "Returns a function which, when called, will interactively `wrap-region-or-insert' using LEFT and RIGHT."
    +  `(lambda () (interactive)
    +     (wrap-region-or-insert ,left ,right)))
    +
    +(defun wrap-region-with-tag-or-insert ()
    +  (interactive)
    +  (if (and mark-active transient-mark-mode)
    +      (call-interactively 'wrap-region-with-tag)
    +    (insert "<")))
    +
    +(defun wrap-region-with-tag (tag beg end)
    +  "Wrap the region in the given HTML/XML tag using `wrap-region'. If any
    +attributes are specified then they are only included in the opening tag."
    +  (interactive "*sTag (including attributes): \nr")
    +  (let* ((elems    (split-string tag " "))
    +         (tag-name (car elems))
    +         (right    (concat "</" tag-name ">")))
    +    (if (= 1 (length elems))
    +        (wrap-region (concat "<" tag-name ">") right beg end)
    +      (wrap-region (concat "<" tag ">") right beg end))))
    +
    +(defun wrap-region-or-insert (left right)
    +  "Wrap the region with `wrap-region' if an active region is marked, otherwise insert LEFT at point."
    +  (interactive)
    +  (if (and mark-active transient-mark-mode)
    +      (wrap-region left right (region-beginning) (region-end))
    +    (insert left)))
    +
    +(global-set-key "'"  (wrap-region-with-function "'" "'"))
    +(global-set-key "\"" (wrap-region-with-function "\"" "\""))
    +(global-set-key "`"  (wrap-region-with-function "`" "`"))
    +(global-set-key "("  (wrap-region-with-function "(" ")"))
    +(global-set-key "["  (wrap-region-with-function "[" "]"))
    +(global-set-key "{"  (wrap-region-with-function "{" "}"))
    +(global-set-key "<"  'wrap-region-with-tag-or-insert) ;; I opted not to have a wrap-with-angle-brackets
    + + +Download wrap-region.el + +That more or less sums up why I like Emacs so much. I wanted that functionality so I implemented it (barely! It was basically done for me), debugged it by immediately evaluating sexps and then trying it out, and then once it worked I reloaded my config and used the wanted feature. That's just awesome, and shows one strength of open source. diff --git a/public/posts/2007.06.24-floating-point-in-elschemo.md b/public/posts/2007.06.24-floating-point-in-elschemo.md new file mode 100644 index 0000000..6b157e6 --- /dev/null +++ b/public/posts/2007.06.24-floating-point-in-elschemo.md @@ -0,0 +1,448 @@ +Title: Floating point in ElSchemo +Date: June 24, 2007 +Timestamp: 1182711180 +Author: sjs +Tags: elschemo, haskell, scheme +---- + +### Parsing floating point numbers ### + +The first task is extending the LispVal type to grok floats. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    type LispInt = Integer
    +type LispFloat = Float
    +
    +-- numeric data types
    +data LispNum = Integer LispInt
    +             | Float LispFloat
    +
    +-- data types
    +data LispVal = Atom String
    +             | List [LispVal]
    +             | DottedList [LispVal] LispVal
    +             | Number LispNum
    +             | Char Char
    +             | String String
    +             | ...
    + + +The reason for using the new LispNum type and not just throwing a new Float Float constructor in there is so that functions can accept and operate on parameters of any supported numeric type. First the floating point numbers need to be parsed. For now I only parse floating point numbers in decimal because the effort to parse other bases is too great for the benefits gained (none, for me). + +ElSchemo now parses negative numbers so I'll start with 2 helper functions that are used when parsing both integers and floats: + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    parseSign :: Parser Char
    +parseSign = do try (char '-')
    +           <|> do optional (char '+')
    +                  return '+'
    +
    +applySign :: Char -> LispNum -> LispNum
    +applySign sign n = if sign == '-' then negate n else n
    + + +parseSign is straightforward as it follows the convention that a literal number is positive unless explicitly marked as negative with a leading minus sign. A leading plus sign is allowed but not required. + +applySign takes a sign character and a LispNum and negates it if necessary, returning a LispNum. + +Armed with these 2 functions we can now parse floating point numbers in decimal. Conforming to R5RS an optional #d prefix is allowed. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +
    parseFloat :: Parser LispVal
    +parseFloat = do optional (string "#d")
    +                sign <- parseSign
    +                whole <- many1 digit
    +                char '.'
    +                fract <- many1 digit
    +                return . Number $ applySign sign (makeFloat whole fract)
    +    where makeFloat whole fract = Float . fst . head . readFloat $ whole ++ "." ++ fract
    + + +The first 6 lines should be clear. Line 7 simply applies the parsed sign to the parsed number and returns it, delegating most of the work to makeFloat. makeFloat in turn delegates the work to the readFloat library function, extracts the result and constructs a LispNum for it. + +The last step for parsing is to modify parseExpr to try and parse floats. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +
    -- Integers, floats, characters and atoms can all start with a # so wrap those with try.
    +-- (Left factor the grammar in the future)
    +parseExpr :: Parser LispVal
    +parseExpr = (try parseFloat)
    +        <|> (try parseInteger)
    +        <|> (try parseChar)
    +        <|> parseAtom
    +        <|> parseString
    +        <|> parseQuoted
    +        <|> do char '('
    +               x <- (try parseList) <|> parseDottedList
    +               char ')'
    +               return x
    +        <|> parseComment
    + + +### Displaying the floats ### + + +That's it for parsing, now let's provide a way to display these suckers. LispVal is an instance of show, where show = showVal so showVal is our first stop. Remembering that LispVal now has a single Number constructor we modify it accordingly: + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    showVal (Number n) = showNum n
    +
    +showNum :: LispNum -> String
    +showNum (Integer contents) = show contents
    +showNum (Float contents) = show contents
    +
    +instance Show LispNum where show = showNum
    + + +One last, and certainly not least, step is to modify eval so that numbers evaluate to themselves. + + + eval env val@(Number _) = return val + +There's a little more housekeeping to be done such as fixing integer?, number?, implementing float? but I will leave those as an exercise to the reader, or just wait until I share the full code. As it stands now floating point numbers can be parsed and displayed. If you fire up the interpreter and type 2.5 or -10.88 they will be understood. Now try adding them: + + (+ 2.5 1.1) + Invalid type: expected integer, found 2.5 + +Oops, we don't know how to operate on floats yet! + +### Operating on floats ### + +Parsing was the easy part. Operating on the new floats is not necessarily difficult, but it was more work than I realized it would be. I don't claim that this is the best or the only way to operate on any LispNum, it's just the way I did it and it seems to work. There's a bunch of boilerplate necessary to make LispNum an instance of the required classes, Eq, Num, Real, and Ord. I don't think I have done this properly but for now it works. What is clearly necessary is the code that operates on different types of numbers. I think I've specified sane semantics for coercion. This will be very handy shortly. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +
    lispNumEq :: LispNum -> LispNum -> Bool
    +lispNumEq (Integer arg1) (Integer arg2) = arg1 == arg2
    +lispNumEq (Integer arg1) (Float arg2) = (fromInteger arg1) == arg2
    +lispNumEq (Float arg1) (Float arg2) = arg1 == arg2
    +lispNumEq (Float arg1) (Integer arg2) = arg1 == (fromInteger arg2)
    +
    +instance Eq LispNum where (==) = lispNumEq
    +
    +lispNumPlus :: LispNum -> LispNum -> LispNum
    +lispNumPlus (Integer x) (Integer y) = Integer $ x + y
    +lispNumPlus (Integer x) (Float y)   = Float $ (fromInteger x) + y
    +lispNumPlus (Float x)   (Float y)   = Float $ x + y
    +lispNumPlus (Float x)   (Integer y) = Float $ x + (fromInteger y)
    +
    +lispNumMinus :: LispNum -> LispNum -> LispNum
    +lispNumMinus (Integer x) (Integer y) = Integer $ x - y
    +lispNumMinus (Integer x) (Float y)   = Float $ (fromInteger x) - y
    +lispNumMinus (Float x)   (Float y)   = Float $ x - y
    +lispNumMinus (Float x)   (Integer y) = Float $ x - (fromInteger y)
    +
    +lispNumMult :: LispNum -> LispNum -> LispNum
    +lispNumMult (Integer x) (Integer y) = Integer $ x * y
    +lispNumMult (Integer x) (Float y)   = Float $ (fromInteger x) * y
    +lispNumMult (Float x)   (Float y)   = Float $ x * y
    +lispNumMult (Float x)   (Integer y) = Float $ x * (fromInteger y)
    +
    +lispNumDiv :: LispNum -> LispNum -> LispNum
    +lispNumDiv (Integer x) (Integer y) = Integer $ x `div` y
    +lispNumDiv (Integer x) (Float y)   = Float $ (fromInteger x) / y
    +lispNumDiv (Float x)   (Float y)   = Float $ x / y
    +lispNumDiv (Float x)   (Integer y) = Float $ x / (fromInteger y)
    +
    +lispNumAbs :: LispNum -> LispNum
    +lispNumAbs (Integer x) = Integer (abs x)
    +lispNumAbs (Float x) = Float (abs x)
    +
    +lispNumSignum :: LispNum -> LispNum
    +lispNumSignum (Integer x) = Integer (signum x)
    +lispNumSignum (Float x) = Float (signum x)
    +
    +instance Num LispNum where
    +    (+) = lispNumPlus
    +    (-) = lispNumMinus
    +    (*) = lispNumMult
    +    abs = lispNumAbs
    +    signum = lispNumSignum
    +    fromInteger x = Integer x
    +
    +
    +lispNumToRational :: LispNum -> Rational
    +lispNumToRational (Integer x) = toRational x
    +lispNumToRational (Float x) = toRational x
    +
    +instance Real LispNum where
    +    toRational = lispNumToRational
    +
    +
    +lispIntQuotRem :: LispInt -> LispInt -> (LispInt, LispInt)
    +lispIntQuotRem n d = quotRem n d
    +
    +lispIntToInteger :: LispInt -> Integer
    +lispIntToInteger x = x
    +
    +lispNumLessThanEq :: LispNum -> LispNum -> Bool
    +lispNumLessThanEq (Integer x) (Integer y) = x <= y
    +lispNumLessThanEq (Integer x) (Float y)   = (fromInteger x) <= y
    +lispNumLessThanEq (Float x)   (Integer y) = x <= (fromInteger y)
    +lispNumLessThanEq (Float x)   (Float y)   = x <= y
    +
    +instance Ord LispNum where (<=) = lispNumLessThanEq
    + + +Phew, ok with that out of the way now we can actually extend our operators to work with any type of LispNum. Our Scheme operators are defined using the functions numericBinop and numBoolBinop. First we'll slightly modify our definition of primitives: + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
    +primitives = [("+", numericBinop (+)),
    +              ("-", subtractOp),
    +              ("*", numericBinop (*)),
    +              ("/", floatBinop (/)),
    +              ("mod", integralBinop mod),
    +              ("quotient", integralBinop quot),
    +              ("remainder", integralBinop rem),
    +              ("=", numBoolBinop (==)),
    +              ("<", numBoolBinop (<)),
    +              (">", numBoolBinop (>)),
    +              ("/=", numBoolBinop (/=)),
    +              (">=", numBoolBinop (>=)),
    +              ("<=", numBoolBinop (<=)),
    +              ...]
    + + +Note that mod, quotient, and remainder are only defined for integers and as such use integralBinop, while division (/) is only defined for floating point numbers using floatBinop. subtractOp is different to support unary usage, e.g. (- 4) => -4, but it uses numericBinop internally when more than 1 argument is given. On to the implementation! First extend unpackNum to work with any LispNum, and provide separate unpackInt and unpackFloat functions to handle both kinds of LispNum. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    unpackNum :: LispVal -> ThrowsError LispNum
    +unpackNum (Number (Integer n)) = return $ Integer n
    +unpackNum (Number (Float n)) = return $ Float n
    +unpackNum notNum = throwError $ TypeMismatch "number" notNum
    +
    +unpackInt :: LispVal -> ThrowsError Integer
    +unpackInt (Number (Integer n)) = return n
    +unpackInt (List [n]) = unpackInt n
    +unpackInt notInt = throwError $ TypeMismatch "integer" notInt
    +
    +unpackFloat :: LispVal -> ThrowsError Float
    +unpackFloat (Number (Float f)) = return f
    +unpackFloat (Number (Integer f)) = return $ fromInteger f
    +unpackFloat (List [f]) = unpackFloat f
    +unpackFloat notFloat = throwError $ TypeMismatch "float" notFloat
    + + +The initial work of separating integers and floats into the LispNum abstraction, and the code I said would be handy shortly, are going to be really handy here. There's relatively no change in numericBinop except for the type signature. integralBinop and floatBinop are just specific versions of the same function. I'm sure there's a nice Haskelly way of doing this with less repetition, and I welcome such corrections. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +
    numericBinop :: (LispNum -> LispNum -> LispNum) -> [LispVal] -> ThrowsError LispVal
    +numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
    +numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op
    +
    +integralBinop :: (LispInt -> LispInt -> LispInt) -> [LispVal] -> ThrowsError LispVal
    +integralBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
    +integralBinop op params = mapM unpackInt params >>= return . Number . Integer . foldl1 op
    +
    +floatBinop :: (LispFloat -> LispFloat -> LispFloat) -> [LispVal] -> ThrowsError LispVal
    +floatBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
    +floatBinop op params = mapM unpackFloat params >>= return . Number . Float . foldl1 op
    +
    +subtractOp :: [LispVal] -> ThrowsError LispVal
    +subtractOp num@[_] = unpackNum (head num) >>= return . Number . negate
    +subtractOp params = numericBinop (-) params
    +
    +numBoolBinop :: (LispNum -> LispNum -> Bool) -> [LispVal] -> ThrowsError LispVal
    +numBoolBinop op params = boolBinop unpackNum op params
    + + +That was a bit of work but now ElSchemo supports floating point numbers, and if you're following along then your Scheme might too if I haven't missed any important details! + + +Next time I'll go over some of the special forms I have added, including short-circuiting and and or forms and the full repetoire of let, let*, and letrec. Stay tuned! diff --git a/public/posts/2007.06.25-emacs-tagify-region-or-insert-tag.md b/public/posts/2007.06.25-emacs-tagify-region-or-insert-tag.md new file mode 100644 index 0000000..36feb3d --- /dev/null +++ b/public/posts/2007.06.25-emacs-tagify-region-or-insert-tag.md @@ -0,0 +1,12 @@ +Title: Emacs: tagify-region-or-insert-tag +Date: June 25, 2007 +Timestamp: 1182809580 +Author: sjs +Tags: emacs, tagify +---- + +After axing half of wrap-region.el I renamed it to tagify.el and improved it ever so slightly. It's leaner, and does more! + +tagify-region-or-insert-tag does the same thing as wrap-region-with-tag except if there is no region it now inserts the opening and closing tags and sets point in between them. I have this bound to C-z t, as I use C-z as my personal command prefix. + +< is bound to tagify-region-or-insert-self which really doesn't warrant an explanation. diff --git a/public/posts/2007.06.25-propaganda-makes-me-sick.md b/public/posts/2007.06.25-propaganda-makes-me-sick.md new file mode 100644 index 0000000..b0cea27 --- /dev/null +++ b/public/posts/2007.06.25-propaganda-makes-me-sick.md @@ -0,0 +1,37 @@ +Title: Propaganda makes me sick +Date: June 25, 2007 +Timestamp: 1182768900 +Author: sjs +Tags: propaganda +---- + +Things like this in modern times are surprising. Can't people spot this phony crap for what it is? + +First they put away the dealers, keep our kids safe and off the streets
    +Then they put away the prostitutes, keep married men cloistered at home
    +Then they shooed away the bums, and they beat and bashed the queers
    +Turned away asylum-seekers, fed us suspicions and fears
    +We didn't raise our voice, we didn't make a fuss
    +It´s funny there was no one left to notice, when they came for us
    +
    +Looks like witches are in season, you better fly your flag and be aware
    +Of anyone who might fit the description, diversity is now our biggest fear
    +Now with our conversations tapped, and our differences exposed
    +How ya supposed to love your neighbour, with our minds and curtains +closed?
    +We used to worry 'bout big brother
    +Now we got a big father and an even bigger mother

    +
    +And still you believe, this aristocracy gives a fuck about you
    +They put the mock in democracy, and you swallowed every hook
    +The sad truth is, you'd rather follow the school into the net
    +'Cause swimming alone at sea, is not the kind of freedom that you +actually want
    +So go back to your crib, and suck on a tit
    +Bask in the warmth of your diaper, you're sitting in shit
    +And piss, while sucking on a giant pacifier
    +A country of adult infants, a legion of mental midgets
    +A country of adult infants, a country of adult infants
    +All regaining their unconsciousness
    +
    +—from the song Regaining Unconsciousness, by NOFX diff --git a/public/posts/2007.06.26-rtfm.md b/public/posts/2007.06.26-rtfm.md new file mode 100644 index 0000000..1aae5a0 --- /dev/null +++ b/public/posts/2007.06.26-rtfm.md @@ -0,0 +1,10 @@ +Title: RTFM! +Date: June 26, 2007 +Timestamp: 1182806340 +Author: sjs +Tags: emacs, rtfm +---- + +I should read the Emacs manual sometime, especially since I have it in dead-tree form. Check out skeleton pairs in the Emacs manual, or better yet C-h f skeleton-pair-insert-maybe. skeleton-pair has already been massaged to do what you most likely want if you set the correct options. Cool. I like Emacs more every day. + +This renders wrap-region useless, which is great! I like a trim .emacs and .emacs.d. diff --git a/public/posts/2007.06.28-recent-ruby-and-rails-regales.md b/public/posts/2007.06.28-recent-ruby-and-rails-regales.md new file mode 100644 index 0000000..41bbdd7 --- /dev/null +++ b/public/posts/2007.06.28-recent-ruby-and-rails-regales.md @@ -0,0 +1,26 @@ +Title: Recent Ruby and Rails Regales +Date: June 28, 2007 +Timestamp: 1183058580 +Author: sjs +Tags: rails, rails on rules, regular expressions, ruby, sake, secure associations, regex +---- + +Some cool Ruby and [the former on] Rails things are springing up and I haven't written much about the two Rs lately, though I work with them daily. + +### Rails on Rules ### + +My friend Jim Roepcke is researching and implementing a plugin/framework designed to work with Rails called Rails on Rules. His inspiration is the rule system from WebObjects' Direct to Web. He posted a good example for me, but this baby isn't just for template/view logic. If some of the Rails conventions were specified in a default set of rules which the developer could further customize then you basically have a nice way of doing things that you would otherwise code by hand. I think it would be a boon for the ActiveScaffold project. We're meeting up to talk about this soon and I'll have more to say after then, but it sounds pretty cool. + +### Sake Bomb! ### + +I've noticed a trend among some recent posts about Rake: the authors keep talking about booze. Are we nothing but a bunch of booze hounds?! Well one can hope. There's some motivation to learn more about a tool, having more time to drink after work. This week Chris Wanstrath dropped a Sake Bomb on the Ruby community. Like piston, sake is something you can just pick up and use instantly. Interestingly the different pronunciations of rake and sake help me from confusing the two on the command line... so far. + +### Secure Associations (for Rails) ### + +Jordan McKible released the secure_associations plugin. It lets you protect your models' *_id attributes from mass-assignment via belongs_to_protected and has_many_protected. It's a mild enhancement, but an enhancement nonetheless. This is useful to enough people that it should be in Rails proper. + +### Regular expressions and strings with embedded objects ### + +taw taught me a new technique for simplifying regular expressions by transforming the text in a reversible manner. In one example he replaced literal strings in SQL - which are easily parsed via a regex - with what he calls embedded objects. They're just tokens to identify the temporarily removed strings, but the important thing is that they don't interfere with the regexes that operate on the other parts of the SQL, which would have been very difficult to get right with the strings inside it. If I made it sound complicated just read the post, he explains it well. + +If you believe anything Steve Yegge says then that last regex trick may come in handy for Q&D parsing in any language, be it Ruby, NBL, or whataver. diff --git a/public/posts/2007.06.30-controlling-volume-via-the-keyboard-on-linux.md b/public/posts/2007.06.30-controlling-volume-via-the-keyboard-on-linux.md new file mode 100644 index 0000000..708cb9b --- /dev/null +++ b/public/posts/2007.06.30-controlling-volume-via-the-keyboard-on-linux.md @@ -0,0 +1,12 @@ +Title: Controlling volume via the keyboard on Linux +Date: June 30, 2007 +Timestamp: 1183245180 +Author: sjs +Tags: alsa, linux, ruby, volume +---- + +I was using Amarok's global keyboard shortcuts to control the volume of my music via the keyboard but I wanted to control the system volume as well. A quick script later and now I can control both, and thanks to libnotify I get some feedback on what happened. It's not as pretty as OS X's volume control or Growl but it'll certainly do. + +↓ Download volume.rb + +I save this as ~/bin/volume and call it thusly: volume + and volume -. I bind Alt-+ and Alt—to those in my fluxbox config. If you don't have a preferred key binding program I recommend trying xbindkeys. apt-get install, emerge, paludis -i, or rpm -i as needed. diff --git a/public/posts/2007.07.03-a-textmate-tip-for-emacs-users.md b/public/posts/2007.07.03-a-textmate-tip-for-emacs-users.md new file mode 100644 index 0000000..39d834a --- /dev/null +++ b/public/posts/2007.07.03-a-textmate-tip-for-emacs-users.md @@ -0,0 +1,18 @@ +Title: A TextMate tip for Emacs users +Date: July 3, 2007 +Timestamp: 1183481100 +Author: sjs +Tags: emacs, keyboard shortcuts, textmate +---- + +*Update: The only place I've seen this mentioned is in a comment on the MacroMates blog.* + +My Linux box is down due to a hardware failure; a cheap SATA controller to be specific. Perhaps that will be a story for another day. As a result I've been working on my MacBook and back in TextMate. Old habits. And I haven't gotten comfortable in any of the OS X Emacsen yet. + +This gave me an opportunity to accidentally discover some shortcuts in TextMate. A result of the Emacs shortcuts that my fingers are already wired to, here are some TextMate keyboard shortcuts that may or may not be documented (I need to RTFM some day). + + * As in most Cocoa text areas, C-f, C-b, C-n, C-p, C-a, C-e, and C-t work as expected (and others I'm sure). + * C-k: behaves as a vanilla Emacs, killing till a newline or killing a bare newline. I use the word killing specifically because you can yank it back with... + * C-y: yanks back the last thing on the kill ring (paste history). You still have to use C-S-v to yank previous items. + +I think TextMate may have helped ease me into Emacs without me even knowing. I had my suspicions that Allan was an Emacs fan and now I'm certain of it. I keep finding things in one that the other has, which makes switching between them easy. Well done Allan. diff --git a/public/posts/2007.07.05-rushcheck-quickcheck-for-ruby.md b/public/posts/2007.07.05-rushcheck-quickcheck-for-ruby.md new file mode 100644 index 0000000..b4530fa --- /dev/null +++ b/public/posts/2007.07.05-rushcheck-quickcheck-for-ruby.md @@ -0,0 +1,8 @@ +Title: RushCheck: QuickCheck for Ruby +Date: July 5, 2007 +Timestamp: 1183665000 +Author: sjs +Tags: quickcheck, ruby, rushcheck +---- + +I cannot wait to try out RushCheck. It is QuickCheck for Ruby. I don't have experience with QuickCheck or anything but it's clear to see how this helps you make certain your code is robust. diff --git a/public/posts/2007.07.06-see-your-regular-expressions-in-emacs.md b/public/posts/2007.07.06-see-your-regular-expressions-in-emacs.md new file mode 100644 index 0000000..2d3aeb6 --- /dev/null +++ b/public/posts/2007.07.06-see-your-regular-expressions-in-emacs.md @@ -0,0 +1,12 @@ +Title: See your regular expressions in Emacs +Date: July 6, 2007 +Timestamp: 1183740300 +Author: sjs +Tags: emacs, regex +---- + +First, if you are an Emacs newbie then be sure to read (at least) the introduction of Being Productive with Emacs. For some reason the PDF and HTML versions are slightly similar. + +Anyway, it mentions re-builder which is an awesome little gem if you use regular expressions at all1. What this baby does is open a small window at the bottom of your screen in which you can type a regex. It is parsed as you type it and matches are highlighted in the other window. Genius. + +[1] If you don't use them I encourage you to "learn them"http://regex.info/. Don't pay any attention to Jamie Zawinsky and his lack of appreciation for a fantastic tool. diff --git a/public/posts/2007.07.12-people.md b/public/posts/2007.07.12-people.md new file mode 100644 index 0000000..a857dd6 --- /dev/null +++ b/public/posts/2007.07.12-people.md @@ -0,0 +1,12 @@ +Title: people +Date: July 12, 2007 +Timestamp: 1184243280 +Author: sjs +Tags: life, people +---- + +Sometimes this is difficult to remember for someone who (likes to think that he) thinks somewhat logically. + +> When dealing with people, let us remember that we are not dealing with creatures of logic. We are dealing with creatures of emotion, creatures bristling with prejudices and motivated by pride and vanity. + +—Dale Carnegie, *How to Win Friends and Influence People* diff --git a/public/posts/2007.08.02-elschemo-boolean-logic-and-branching.md b/public/posts/2007.08.02-elschemo-boolean-logic-and-branching.md new file mode 100644 index 0000000..91de819 --- /dev/null +++ b/public/posts/2007.08.02-elschemo-boolean-logic-and-branching.md @@ -0,0 +1,199 @@ +Title: ElSchemo: Boolean logic and branching +Date: August 2, 2007 +Timestamp: 1186073940 +Author: sjs +Tags: elschemo, haskell, scheme +---- + +I've been developing a Scheme +interpreter in Haskell called +ElSchemo. +It started from Jonathan's excellent Haskell +tutorial +which I followed in order to learn both Haskell and Scheme. Basically +that means the code here is for me to get some feedback as much +as to show others how to do this kind of stuff. This may not be too +interesting if you haven't at least browsed the tutorial. + + +I'm going to cover 3 new special forms: and, or, and cond. I +promised to cover the let family of special forms this time around +but methinks this is long enough as it is. My sincere apologies if +you've been waiting for those. + +## Short-circuiting Boolean logic ## + +Two functions from the tutorial which may irk you immediately are +and and or, defined in Scheme in the given standard library. If +your code is free of side-effects then it may not bother you so +much. It bothered me. The problem with the implementation in +stdlib.scm is that all the arguments are evaluated before control +enters the function. Besides being inefficient by doing unnecessary work, +if any of the arguments have side-effects you can make use of short-circuiting +by using and to sequence actions, bailing out if any fail (by returning nil), +and using or to define a set of alternative actions which will bail out when the first in the list succeeds (by returning anything but nil). Had we macros then we could implement them as +macros. We don't, so we'll write them as special forms in Haskell. + +Unlike the special forms defined in the tutorial I'm going to +implement these as separate functions for clarity, rather than lump +them all in eval. However, they will be invoked directly from +eval so their type is easy; it's the same as eval's. + +Code first, ask questions later. Haskell is a pretty clear and +concise language. My explanations may be redundant because of this. + +### lispAnd ### + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +
    lispAnd :: Env -> [LispVal] -> IOThrowsError LispVal
    +lispAnd env [] = return $ Bool True
    +lispAnd env [pred] = eval env pred
    +lispAnd env (pred:rest) = do
    +    result <- eval env pred
    +    case result of
    +      Bool False -> return result
    +      _ -> lispAnd env rest
    + + +Starting with the trivial case, and returns #t with zero +arguments. + +With one argument, a single predicate, simply evaluate and +return that argument. + +Given a list of predicates, evaluate the first and inspect its value. +If the argument evaluated to #f then our work is done and we return +#f, otherwise we keep plugging along by making a recursive call with +the first argument stripped off. Eventually we will reach our base +case with only one predicate. + +It's possible to eliminate the case of one predicate. I think that +just complicates things but it's a viable solution. + +### lispOr ### + +Predictably this is quite similar to lispAnd. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +
    lispOr :: Env -> [LispVal] -> IOThrowsError LispVal
    +lispOr env [] = return $ Bool False
    +lispOr env [pred] = eval env pred
    +lispOr env (pred:rest) = do
    +    result <- eval env pred
    +    case result of
    +        Bool False -> lispOr env rest
    +        _ -> return result
    + + +With no arguments lispOr returns #f, and with one argument it +evaluates and returns the result. + +With 2 or more arguments the first is evaluated, but this time if the +result is #f then we continue looking for a truthy value. If the +result is anything else at all then it's returned and we are done. + +## A new branching construct ## + +First let me define a convenience function that I have added to +ElSchemo. It maps a list of expressions to their values by evaluating +each one in the given environment. + + + + + +
    1
    +2
    +
    evalExprs :: Env -> [LispVal] -> IOThrowsError [LispVal]
    +evalExprs env exprs = mapM (eval env) exprs
    + + +### lispCond ### + +Again, lispCond has the same type as eval. + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +
    lispCond :: Env -> [LispVal] -> IOThrowsError LispVal
    +lispCond env (List (pred:conseq) : rest) = do
    +    result <- eval env pred
    +    case result of
    +        Bool False -> if null rest then return result else lispCond env rest
    +        _ -> liftM last $ evalExprs env conseq
    + + +Unlike Lisp – which uses a predicate of T (true) – Scheme uses a +predicate of else to trigger the default branch. When the pattern +matching on Atom "else" succeeds, we evaluate the default +expressions and return the value of the last one. This is one +possible base case. Atom "else" could be defined to evaluate to +#t, but we don't want else to be evaluated as #t anywhere except +in a cond so I have chosen this solution. + +If the first predicate is not else then we evaluate it and check the +resulting value. If we get #f then we look at the rest of the +statement, if it's empty then we return #f, otherwise we recurse on +the rest of the parameters. If the predicate evaluates to a truthy +value – that is, anything but #f – then we evaluate the consequent +expressions and return the value of the last one. + +## Plumbing ## + +Now all that's left is to hook up the new functions in eval. + + + + + +
    1
    +2
    +3
    +
    eval env (List (Atom "and" : params)) = lispAnd env params
    +eval env (List (Atom "or" : params)) = lispOr env params
    +eval env (List (Atom "cond" : params)) = lispCond env params
    + + +You could, of course, throw the entire definitions in eval itself but eval is big +enough for me as it is. YMMV. + +## Done! ## + +So, that's a wrap. It only took 20 lines of code for the 3 new +special forms, and it could easily be done with less code. Next time +I will show you how to implement the various let functions. Really! + +*Do you like me describing ElSchemo piece by piece as I have been? I +plan on posting the Haskell code and my stdlib.scm in their entirety +sometime, and I could do that before or after I finish writing about +the features I've developed beyond the tutorial. Just let me know in +the comments.* diff --git a/public/posts/2007.08.09-cheat-from-emacs.md b/public/posts/2007.08.09-cheat-from-emacs.md new file mode 100644 index 0000000..31c8718 --- /dev/null +++ b/public/posts/2007.08.09-cheat-from-emacs.md @@ -0,0 +1,38 @@ +Title: Cheat from Emacs +Date: August 9, 2007 +Timestamp: 1186710960 +Author: sjs +Tags: Emacs +---- + +*Update: I had inadvertently used string-join, a function provided by something in my ~/.emacs.d. The script has been updated to work with a vanilla Emacs (23, but should work with 22 as well).* + +*Update #2 [2007.08.10]: Editing cheats and diffs have been implemented.* + +*Update #3 [2007.08.21]: I added completion to cheat.el. The file linked on this page is still the latest version.* + +We all know and love cheat. Now you can cheat without leaving Emacs (and without using a shell in Emacs). + +Just save cheat.el in ~/.emacs.d and then (require 'cheat) in your ~/.emacs. I also bind C-z C-c to cheat, you may want to do something similar. + + +You can't do everything you can do with cheat on the command line yet, and for most of the commands the cheat command itself is used. *Now you can do everything the command line client does from within Emacs, though you may need to revert to using cheat-command (described below).* + +Here's the rundown: + +*Any time you enter a cheat name there are both completion and a cheat-specific history available. Unless you are adding a new cheat. In that case you should use a new, unique name (duh).* + + * cheat – Lookup a cheat sheet interactively (cheat <name>) + * cheat-sheets – List all cheat sheets (cheat sheets) + * cheat-recent – List recently added cheat sheets (cheat recent) + * cheat-versions – List versions of a cheat sheet interactively (cheat <name> --versions) + * cheat-clear-cache – Clear all cached sheets. + * cheat-add-current-buffer – Add a new cheat using the specified name and the contents of the current buffer as the body. (cheat <name> --add) + * cheat-edit – Retrieve a fresh copy of the named cheat and display the body in a buffer for editing. + * cheat-save-current-buffer – Save the current cheat buffer, which should be named *cheat-<name>*. + * cheat-diff – Show the diff between the current version and the given version of the named cheat. If the version given is of the form m:n then show the diff between versions m and n. (cheat <name> --diff <version>) + * cheat-command – Pass any arguments you want to cheat interactively. + +*(Added)* I may add support for --diff and --edit in the future. + +Please do send me your patches so everyone can benefit from them. diff --git a/public/posts/2007.08.09-snap-crunchle-pop.md b/public/posts/2007.08.09-snap-crunchle-pop.md new file mode 100644 index 0000000..2265286 --- /dev/null +++ b/public/posts/2007.08.09-snap-crunchle-pop.md @@ -0,0 +1,12 @@ +Title: Snap, crunchle, pop +Date: August 9, 2007 +Timestamp: 1186654620 +Author: sjs +Tags: humans, injury, life +---- + +I think that every now and then we need to be reminded of the frail nature of our human bodies. Yesterday morning as I walked to my kitchen I was turning right by pivoting on my right foot when my 24 years of walking experience suddenly failed me. I clearly did something wrong, as I heard a crunching pop or two in my right ankle and went down. Luckily it's just a sprain but my foot is fairly bruised and still sore today. I'm trying to follow the RICE method for recuperating but one can only lay down for so long before having to eat, work, use the bathroom, etc. Thank goodness I don't work on my feet or I'd be out of commission. If it still hurts next week I'm going to see a doctor but till then I'm trying not to leave my house. The idea of hopping and hobbling to a bus to go to a doctor does not thrill me in the slightest. + +Oh, if you find yourself in a bind an upside down hockey stick is a decent makeshift crutch. You'll need 2 hands to operate the thing though. + +At the opposite end of the spectrum there are times when we seem to be amazingly resilient creatures. Check out a documentary called *"101 Things Removed from the Human Head"* if you can find it anywhere. One of those things was a boat anchor, I kid you not. diff --git a/public/posts/2007.08.11-opera-is-pretty-slick.md b/public/posts/2007.08.11-opera-is-pretty-slick.md new file mode 100644 index 0000000..1dcba1d --- /dev/null +++ b/public/posts/2007.08.11-opera-is-pretty-slick.md @@ -0,0 +1,16 @@ +Title: Opera is pretty slick +Date: August 11, 2007 +Timestamp: 1186834260 +Author: sjs +Tags: browsers, firefox, opera +---- + +Though I usually prefer free software, I don't have any problems using proprietary stuff if I think it's good. I had Firefox open for a couple of days and noticed that it was using 700M of memory. That's not a problem at all since I have 4G but it's also a lot of RAM to be in use for just one window with one tab open. The fact that Firefox gets sluggish after some time and needs to be restarted tells me that this isn't expected behaviour and is likely not due to caching for quick back/forward or whatever they claim is taking up the leaked memory. + +Konqueror is ok but I'm not a huge fan of it, partly due to its kitchen-sink browser/file manager hybrid design. IMO the KDE folks should break out the file manager part, but I digress. I can't really put my finger on anything specific I dislike about Konqueror, it's just not for me. To my dismay it seems to be the snappiest browser on Linux. + +The only other decent browser I know of (for Linux) is Opera so I found some quick instructions on the Ubuntu forums and shoehorned the x86 build of it into my amd64 installation. Everything went well, Flash works and all that stuff. Opera is not nearly as snappy as I like but it is still fairly pleasant to use, once you find a skin that fits into your desktop. For the record Firefox isn't snappy enough either. Apart from AdBlock I don't miss many extensions for every day browsing. + +I'm not sure if I'm going to stick with it yet but I've been using it for 2 days and haven't really missed Firefox at all. Of course as soon as I do any development I need Firefox for Firebug and the Web Developer extension and such. I've yet to investigate development tools on Opera. I'm comfortable developing in Firefox already so why switch? + +Man am I glad we're not in a Netscape/IE world anymore! If I open up my MacBook I can choose from at least 2 other browsers for every day browsing (Camino, Safari). diff --git a/public/posts/2007.08.19-catch-compiler-errors-at-runtime.md b/public/posts/2007.08.19-catch-compiler-errors-at-runtime.md new file mode 100644 index 0000000..a616732 --- /dev/null +++ b/public/posts/2007.08.19-catch-compiler-errors-at-runtime.md @@ -0,0 +1,16 @@ +Title: Catch compiler errors at runtime +Date: August 19, 2007 +Timestamp: 1187561820 +Author: sjs +Tags: ruby +---- + +While coding just now I had a small epiphany about Ruby. Though Ruby is highly dynamic and compiled at runtime, that doesn't preclude one catching some mistakes at compile time. I'm not talking about mere syntax errors or anything either. The only proviso to catching mistakes at compile time is that you must have a decent chunk of code executed during compilation. One benefit of Ruby's blurring of compile time and runtime is that you can run real code at compile time. This is largely how metaprogramming tricks are pulled off elegantly and with ease in projects such as Rails. + +Sure you won't get all the benefits of a strictly and/or statically typed compiler, but you can get some of them. If you have a library that makes substantial use of executing code at compile time then the mere act of loading your library causes your code to run, thus it compiles. If you require your lib and get true back then you know the code that bootstraps the runtime code is at least partially correct. + +Compile time is runtime. Runtime is compile time. Just because you have to run the code to compile it doesn't mean you can't catch a good chunk of compiler errors before you send out your code. Tests will always be there for the rest of your mistakes, but if you can pull work into compile time then Ruby's compiler can augment your regular testing practices. + +I admit that this is of limited use most of the time, but let it not be said that you can't catch any errors with your compiler just because you have to run your code to compile it. With Ruby the more meta you get the more the compiler rewards you. + +*[Of course this is true of languages such as Common Lisp too, which make available the full programming language at compile time. I just happened to be using Ruby when I realized this.]* diff --git a/public/posts/2007.08.21-cheat-productively-in-emacs.md b/public/posts/2007.08.21-cheat-productively-in-emacs.md new file mode 100644 index 0000000..4f03724 --- /dev/null +++ b/public/posts/2007.08.21-cheat-productively-in-emacs.md @@ -0,0 +1,28 @@ +Title: Cheat productively in Emacs +Date: August 21, 2007 +Timestamp: 1187720400 +Author: sjs +Tags: Emacs +---- + +By now you may have heard about cheat, the command line cheat sheet collection that's completely open to editing, wiki style. A couple of weeks ago I posted cheat.el which allows one to cheat from within Emacs. There's an update. However, before I get to cheat.el there's a small detour. + +Cheat is not just about Ruby! A few examples of cheats available are: + + * bash and zsh + * $EDITOR (if you happen to like e, TextMate, vi, emacs, RadRails, ...) + * GNU screen + * Version control (darcs, svn, git) + * Firebug + * Markdown and Textile + * Oracle and MySQL + * Regular expressions + * and of course Ruby, Rails, Capistrano, etc. + +As of today, Aug-21 2007, the count is at 166 cheat sheets so there's probably something there that you'll want to look up from the command line or Emacs sometime. That's enough stroking cheat's ego, but there seems to be a notion that cheat is only for Ruby stuff and that's really not the case. + +So what's new in this version of cheat.el? Completion! The only thing that bothered me about cheating in Emacs was the lack of completion. It now has completion, thus it is now perfect. :) In all likeliness this won't be the last release, but I can't really foresee adding anything else to it in the near future. Enjoy! + +Download it now: cheat.el + +For any newcomers, just drop this into ~/.emacs.d, ~/.elisp, or any directory in your load-path and then (require 'cheat). For more info check the original article for a rundown on the cheat commands. diff --git a/public/posts/2007.08.26-captivating-little-creatures.md b/public/posts/2007.08.26-captivating-little-creatures.md new file mode 100644 index 0000000..ff823f4 --- /dev/null +++ b/public/posts/2007.08.26-captivating-little-creatures.md @@ -0,0 +1,8 @@ +Title: Captivating little creatures +Date: August 26, 2007 +Timestamp: 1188131700 +Author: sjs +Tags: games, lemmings +---- + +Someone posted this JavaScript implementation of an old gem on Reddit, Lemmings! There goes my Sunday! :) diff --git a/public/posts/2007.08.30-5-ways-to-avoid-looking-like-a-jerk-on-the-internet.md b/public/posts/2007.08.30-5-ways-to-avoid-looking-like-a-jerk-on-the-internet.md new file mode 100644 index 0000000..b0d5f97 --- /dev/null +++ b/public/posts/2007.08.30-5-ways-to-avoid-looking-like-a-jerk-on-the-internet.md @@ -0,0 +1,34 @@ +Title: 5 ways to avoid looking like a jerk on the Internet +Date: August 30, 2007 +Timestamp: 1188487500 +Author: sjs +Tags: life, netiquette +---- + +Let me begin by stating that these are tips I have gathered by posting in many public forums on the Internet and I have learned most of these rules by making the mistakes myself. I'm not trying to point fingers at anyone or act all holier-than-thou. It's a cold, emotionless medium text is. It can be difficult to accurately convey one's feelings when typing a quick reply somewhere. John Gabriel's theory certainly plays a part as well, but I'll try and assume that you are generally a nice person. I also assume that we are talking about a text medium (IRC, forums, Slashdot/Reddit/Digg). None of that fancy voice or video conferencing stuff! + +Also, this is not a guide on how to really be an arrogant prick, but just not look like one when you engage in conversations on the Internet. It's also not a guide on not being a jerk. Should you lack basic manners you will have to learn them elsewhere. + +### Rule #1: Forget the medium ### + +One thing that is quite difficult to do is look past the medium and remember that these are all real people conversing with each other. Don't type anything that you wouldn't say to their face in real life. This is, of course, not exclusive to the Internet. + +### Rule #2: Remember the medium! ### + +While obeying Rule #1 it's important to remember that in a text medium there is no emotion or tone to our words. If you think that smilies / emoticons are lame and for 12 year olds, well you're right. However, there's no reason for an adult to refrain from using them as well. They can be important quick clues to how your message should be interpreted. You can always rephrase what you write so that there's little ambiguity to your words, but if you're typing something quickly on Digg, Reddit or some forum then you probably aren't spell checking and proof reading each and every post. + +### Rule #3: Avoid know-it-all responses ### + +Starting a reply with "But ...", "Well ...", "No ...", or "Your mother's a ..." often sounds confrontational. There's obviously no harm in using these in the right context, but many times I have found that removing these from the front of a sentence can drastically alter the tone and make it clear that I am trying to converse rather than argue. + +### Rule #4: Address the correct party ### + +If you're not speaking directly to the reader avoid using "you" when you mean "one". This is a particularly hard one to get in the habit of doing, for me at least. I am just not used to speaking so formally but in writing it really does make a world of difference. People are defensive creatures by nature and we don't like being singled out or accused. Hell, half of the time we don't even like honest, kind advice. + +### Rule #5: Accept the fact that people know more than you ### + +Geeks often come across as know-it-alls. While most geeks probably do think they're rather clever (guilty as charged) they probably also know that they don't know everything. When one knows nothing of a topic it's easy to admit that others are right and they are wrong (often because they won't have an opinion on the subject yet). The trouble starts once they learn something about the matter, once they have formed opinions and ideas about it. + +I'm not saying that we should all stop discussing things we're not experts on, just that we should try harder to keep open minds about things and realize that others may have some insight we do not. If in doubt, partake in civil discourse and try not to dismiss others without even asking them to back up their claims or ideas. + +Cue the comments pointing out how many of these rules I broke in this very post... :) diff --git a/public/posts/2007.09.25-learning-lisp-read-pcl.md b/public/posts/2007.09.25-learning-lisp-read-pcl.md new file mode 100644 index 0000000..49d83f0 --- /dev/null +++ b/public/posts/2007.09.25-learning-lisp-read-pcl.md @@ -0,0 +1,8 @@ +Title: Learning Lisp? Read PCL +Date: September 25, 2007 +Timestamp: 1190714340 +Author: sjs +Tags: lisp +---- + +Yes, it's a book. But it's so well written you should breeze through it as if it were a Lisp tutorial! diff --git a/public/posts/2007.09.26-python-and-ruby-brain-dump.md b/public/posts/2007.09.26-python-and-ruby-brain-dump.md new file mode 100644 index 0000000..17bf1d7 --- /dev/null +++ b/public/posts/2007.09.26-python-and-ruby-brain-dump.md @@ -0,0 +1,22 @@ +Title: Python and Ruby brain dump +Date: September 26, 2007 +Timestamp: 1190802840 +Author: sjs +Tags: python, ruby +---- + +It turns out that Python is the language of choice on the OLPC, both for implementing applications and exposing to the users. There is a view source key available. I think Python is a great choice. + +I've been using Ruby almost exclusively for over a year but the last week I've been doing a personal project in Python using Storm (which is pretty nice btw) and urwid. I'm remembering why I liked Python when I first learned it a few years ago. It may not be as elegant as Ruby, conceptually, but it sure is fun to code in. It really is executable pseudo-code for the most part. + +I'm tripping up by typing obj.setattr^W^Wsetattr(obj and def self.foo^W^Wfoo(self but other than that I haven't had trouble switching back into Python. I enjoy omitting end statements. I enjoy Python's lack of curly braces, apart from literal dicts. I hate the fact that in Emacs, in python-mode, indent-region only seems to piss me off (or indent-* really, anything except TAB). I really like list comprehensions. + +The two languages are so similar that at a glance you may think there are only shallow differences between the languages. People are always busy arguing about the boring things that every language can do (web frameworks anyone?) while ignoring the interesting differences between the languages and their corresponding ecosystems. + +Python has more libraries available as it's the more popular language. The nature of software written in the languages is different though as the languages themselves are quite different. + +Ruby has some Perl-ish features that make it a good sysadmin scripting language, hence we see nice tools such as Capistrano and god written in Ruby and used by projects written in other languages. + +Python is faster than Ruby so it is open to classes of software that would be cumbersome in Ruby. Source control, for example. You can write a slow SCM in Python though, as Bazaar demonstrates. You could probably write a passable one in Ruby as well. If it didn't quite perform well enough right now it should fare better in a year's time. + +I still think that my overall joy is greater when using Ruby, but if Ruby isn't the right tool for the job I'll probably look to Python next (unless some feature of the problem indicates something else would be more appropriate). The reason I chose Python for my current project is because of libs like urwid and I needed an excuse to try out Storm and brush up on my Python. ;-) diff --git a/public/posts/2007.10.29-gtkpod-in-gutsy-got-you-groaning.md b/public/posts/2007.10.29-gtkpod-in-gutsy-got-you-groaning.md new file mode 100644 index 0000000..64efa4e --- /dev/null +++ b/public/posts/2007.10.29-gtkpod-in-gutsy-got-you-groaning.md @@ -0,0 +1,50 @@ +Title: Gtkpod in Gutsy Got You Groaning? +Date: October 29, 2007 +Timestamp: 1193692440 +Author: sjs +Tags: broken, gtkpod, linux, ubuntu +---- + +I recently upgraded the Ubuntu installation on my workstation from Feisty Fawn to Gutsy Gibbon and for the most part I am happy with the changes. One thing I don't care much for is the fact that gtkpod-aac is a sham. Ubuntu provides the gtkpod-aac package for one to transfer aac files, and thus mp4 files with aac audio tracks, to their iPod. The version in the Gutsy repos is broken. This shows a weakness in Ubuntu, and though it's rather small it is one that will piss off a lot of people who expect things to just work. The kind of people who would buy an iPod. The kind of people who use Linux. The kind of Linux users that use Ubuntu. The kicker is that it doesn't look like they will ship a working version of gtkpod-aac for Gutsy at all. I know it's only 6 months but that seems like an eternity when you have the same old crap to watch on your iPod for that long. + +All is not lost. A kind soul left a helpful comment on the bug report explaining how he got it to work. It's a pretty simple fix. Just google for libmpeg4ip and find a Debian repo that has the following packages for your architecture: + + * libmpeg4ip-0 + * libmpeg4ip-dev + * libmp4v2-0 + * libmp4v2-dev + +Download those 4 .deb files and install them. You can ignore any advise to use an older version in the official repo. Once you have those installed, download and build the latest version of gtkpod from their Subversion repo. + +Now that you know what to do I'll give you what you probably wanted at the beginning. As long as you have wget, subversion, and use a Bourne-like shell this should work for you. + +↓ gtkpod-aac-fix.sh + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +
    mkdir /tmp/gtkpod-fix
    +cd /tmp/gtkpod-fix
    +wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmp4v2-0_1.5.0.1-0.3_amd64.deb
    +wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmp4v2-dev_1.5.0.1-0.3_amd64.deb
    +wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmpeg4ip-0_1.5.0.1-0.3_amd64.deb
    +wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmpeg4ip-dev_1.5.0.1-0.3_amd64.deb
    +for f in *.deb; do sudo gdebi -n "$f"; done
    +svn co https://gtkpod.svn.sourceforge.net/svnroot/gtkpod/gtkpod/trunk gtkpod
    +cd gtkpod
    +./autogen.sh --with-mp4v2 && make && sudo make install
    +cd
    +rm -rf /tmp/gtkpod-fix
    diff --git a/public/posts/2008.01.07-random-pet-peeve-of-the-day.md b/public/posts/2008.01.07-random-pet-peeve-of-the-day.md new file mode 100644 index 0000000..5741055 --- /dev/null +++ b/public/posts/2008.01.07-random-pet-peeve-of-the-day.md @@ -0,0 +1,10 @@ +Title: Random pet peeve of the day +Date: January 7, 2008 +Timestamp: 1199727720 +Author: sjs +Tags: usability, web +---- + +So long since my last post, and all I'm going to do is complain. ;-) Seriously though, if you have a website and the content on said site is dated then please – for the love of our almighty saviour, the Flying Spaghetti Monster – put the date at the top of the page. Don't make me scroll down to the end of the article just to see how relevant it is or just to give me some context. Not to mention that I always end up doing a "Where is the end? Oh crap, I passed it and now I'm in the comments, blargh!" + +I'm looking at Lifehacker since they're the most recent offender I've come across, but they are definitely not the only ones guilty of this. diff --git a/public/posts/2008.02.19-thoughts-on-arc.md b/public/posts/2008.02.19-thoughts-on-arc.md new file mode 100644 index 0000000..7fcaf44 --- /dev/null +++ b/public/posts/2008.02.19-thoughts-on-arc.md @@ -0,0 +1,42 @@ +Title: Thoughts on Arc +Date: February 19, 2008 +Timestamp: 1203420360 +Author: sjs +Tags: lisp arc +---- + +*NB: This is just a braindump. There's nothing profound or particularly insightful in this post.* + +You may have heard that Paul Graham recently released his pet dialect of Lisp: Arc. It's a relatively small language consisting of just 4500 lines of code. In just under 1200 lines of PLT Scheme the core of Arc is defined. The rest of the language is written in Arc itself. The heart of that is a file arc.arc, weighing in at 1500 lines. The remaining 1000-1300 lines are spread between libraries, mainly for writing web apps: html.arc, srv.arc, app.arc, and a few others. + +I'm not going to go into great detail, but Arc is a fun language. You can read all the code in one or two sittings and start hacking on it in no time. The code is simple where simple gets the job done and if you can follow SICP then you should understand it with relative ease (assuming you're somewhat familiar with Lisp). + +### Parsing, Markdown ### + +I'm writing a simple parser combinators library (loosely modeled on Parsec) in order to write a nice Markdown implementation. Overkill? Indeed. Parsec is a wonderful library and it is written beautifully. If I end up with something 1/2 as powerful and 1/10th as beautiful I'll be pleased. This was all in order to beef up the version of Markdown bundled with Arc so I could write a basic wiki. I've been beaten to the punch, twice! Perhaps I'll retrofit Markdown onto jgc's wiki once I get something decent finished. + +### Brevity and Innovation ### + +The brevity of Arc is both a blessing and a curse. On the one hand it makes for a very hacking-friendly language. It's easy/fun to try things in the REPL and write throwaway code for learning purposes. Paul's wanton removal of extraneous parentheses is a great boon. On the flip side Arc code can be a little cryptic at a first glance. While reading code there's a small period of time where you have to figure out what the short names are and what they do, but because the language is so small it's utterly trivial to grep or read the source and find out exactly how everything fits together and get the context you need. Once you're familiar with the domain then the terse names not only make sense, but they make the interesting parts of the code stand out more. I want to emphasize the pleasure of using Arc to learn. I think that Paul is on to something with the general brevity and simple nature of Arc. + +Some interesting ways that Paul has reduced code is by introducing new intra-symbol operators. Besides the usual backquote/quasiquote and comma/unquote translations, several other special characters are translated when they appear within/around symbols. + +There is the colon/compose operator that reduces code such as: (sym (string "pre-" something "-suffix")) to (sym:string "pre-" something "-suffix"). It can help with car/cdr chains without defining monstrosities such as cadadr, though whether (cadadr ...) is better than (cadr:cadr ...) is better than (car (cdr (car (cdr ...)))) is up to you. + +My favourite is the tilde to mean logical negation: no in Arc, not in most other languages. It doesn't shorten code much but it helps with parens. (if (no (empty str)) ...) becomes (if (~empty str) ...). Not much to be said about it, but it reads very nicely in code. + +Some newer ones are the dot and exclamation point to aide in the composition of functions requiring arguments. I won't go into detail as their use is trivial. If you're interested read Paul's explanation of them. + +### Web programming ### + +Paul has touted Arc as a good web programming language, most notably in his Arc Challenge that caused a minor stir in a few blogs and on Reddit. I'm writing a small web app for myself in Arc. I may host it somewhere public when it's useable. It's a somewhat pastie-like app specifically for storing/sharing solutions to problems over at Project Euler, which I recently started tackling. "What's wrong with saving the code on your hard disk without a web app?", you ask? It doesn't give me an excuse to try Arc as a web language. ;-) + +So far I find that Arc is quite a nice web language. With the handy HTML tag library you can generate 90s-style, quirks-mode-compliant tag soup in a blink. I haven't had trouble producing HTML 4.01 (strict) that validates. There's no need for a template language or partials (à la Rails), you just compose tags-as-sexps using Arc itself. This turns out to be quite elegant, even if somewhat reminiscent of my first forays into web programming with PHP. I don't feel as if I'm writing a web app so much as I'm writing an app that happens to present its UI in HTML. (I'm reminded a little of web.py, which I enjoy as the antithesis of Rails.) I suppose it takes some discipline to separate your logic & design when everything's mixed in the same file, but there's nothing stopping you from separating the logic and views into their own files if you really prefer to do it that way. + +There's no distinction between GET and POST params. This surprised me, but then I thought about it and it's not a big deal for most apps, imo. + +The app I'm writing is standard CRUD stuff so I haven't done anything cool using continuations yet. I plan to use call/cc for backtracking in my parser, but I'm still a ways from implementing that kind of functionality! + +### Non-conclusion ### + +I feel as though I should have a conclusion, but I don't. I've only been using Arc for a short time. It feels nice. I think Paul is doing a good job on the design by keeping it small, compact, and simple. Seeing as it's still in its infancy it's just a toy for me, but a toy with some decent potential. And hopefully an impact on other Lisps. Common Lisp may have industrial implementations and a 1500 page spec, but Arc is more fun and hackable. More so than Scheme, too. I think Arc has out-Schemed Scheme. diff --git a/public/posts/2008.03.03-project-euler-code-repo-in-arc.md b/public/posts/2008.03.03-project-euler-code-repo-in-arc.md new file mode 100644 index 0000000..4ff5b46 --- /dev/null +++ b/public/posts/2008.03.03-project-euler-code-repo-in-arc.md @@ -0,0 +1,15 @@ +Title: Project Euler code repo in Arc +Date: March 3, 2008 +Timestamp: 1204561440 +Author: sjs +Tags: arc, project euler +---- + +Release early and often. This is a code repo web app for solutions to Project Euler problems. You can only see your own solutions so it's not that exciting yet (but it scratches my itch... once it highlights syntax). You can try it out or download the source. You'll need an up-to-date copy of Anarki to untar the source in. Just run arc.sh then enter this at the REPL: + + +
    arc> (load "euler.arc")
    +arc> (esv)
    +
    + +That will setup the web server on port 3141. If you want a different port then run (esv 25) (just to mess with 'em). diff --git a/public/posts/2009.11.21-using-emacs-to-develop-mojo-apps-for-webos.html b/public/posts/2009.11.21-using-emacs-to-develop-mojo-apps-for-webos.html new file mode 100644 index 0000000..212a9ed --- /dev/null +++ b/public/posts/2009.11.21-using-emacs-to-develop-mojo-apps-for-webos.html @@ -0,0 +1,103 @@ +Title: Using Emacs to Develop Mojo Apps for WebOS +Date: November 21, 2009 +Timestamp: 1258790400 +Author: sjs +Tags: emacs, mojo, webos, lisp, javascript +---- + +

    + The latest technology I've been learning is Palm's SDK for webOS, + Mojo. My first impression is that it's a great platform and + Palm could do a great job of 2.0 if they cut down on some of the + verbosity of gluing together the UI. I have learned to like + JavaScript over the years as I learned that despite its + warts there + are good parts too. If you squint just right you can + see that it's scheme with Algol syntax. HTML and CSS are what + they are, but with WebKit running the show and only a single engine + to target it's not that bad. I've gone from Eclipse to Emacs + for the coding itself and highly recommend Emacs for Mojo + development. There is nothing that I miss from the Eclipse or + Komodo Edit thanks to the fact that Mojo uses open languages and + standards. +

    + + +

    + As far as actual development goes the Mojo documentation steers you + towards a combination of Eclipse, Palm's Mojo plugin for Eclipse, + and the Aptana Studio plugin. My editor of choice is Emacs but + I decided to give it a spin just to get started quickly, how bad + could it be? I'm not going to get into details but I will say that I + don't think I'll ever use Eclipse for anything; it's far too + sluggish and provides no compelling features for the languages + that I use. I tried Komodo Edit and it was significantly + better but still not for me. Emacs is great for editing HTML, + JavaScript, and CSS so all I really missed from the IDEs were the + shortcuts to package, install, and launch apps in the + emulator. I headed over to + the Emacs Wiki and + downloaded Jonathan + Arkell's Mojo + support for Emacs which provided a great base to get + started with. There are wrappers around (all?) of the Palm SDK + commands but it needed a bit of work to make it just do what I + wanted with as little input and thought as possible. +

    + +

    + A couple of of Lisp hacking sessions later and I'm happy enough with + mojo.el to bump the version to v0.9. I've checked off what I + feel are the most important checkpoints on + the webOS + Internals comparison of editors and the framework is in + place to make implementing most of the remaining commands very + trivial. I might take a bit of time today to flesh things out + just to check more points off so people feel more confident that + it's a fully featured environment, because it certainly is. +

    + + +

    + It now requires json.el in order to parse appinfo.json. json.el + might be included with Emacs if you have a very recent version, + otherwise you can google for it or get it from + my config + file repo on github where you can also find my latest + version of mojo.el. You still just (require 'mojo) in your + .emacs file. +

    + +

    + The wrappers around Palm SDK commands now search upwards for the + Mojo project root directory (from the default-directory for + current-buffer) and parse appinfo.json to give you sane defaults for + mojo-package, mojo-install, mojo-launch, mojo-delete, and + mojo-inspect. You can list installed apps and when entering app + ids there is completion and history, as you have come to expect in + Emacs. The most useful command for development is + mojo-package-install-and-inspect which does exactly what it says: + packages, installs, and launches the application for + inspection. No interaction is required as long as you are + editing a buffer inside your Mojo project. +

    + + +

    + If you read the install instructions in mojo.el and decide to setup + some keybindings then you will have single-task commands for + packaging, installing, launching, or all three steps at once. +

    + +

    + Please give me some feedback if you try this out. I've + developed it on Mac OS X and Jonathan on Windows so please try it on + Linux and send me a patch or even better a pull request on github if + it needs some work. There is room for improvement. The next feature + on my radar before I would consider it worthy of a v1.0 tag is + intelligent switching to corresponding buffers, + e.g. mojo-switch-to-view, mojo-switch-to-assistant, things like + that. Basically things I miss from the Rails package for Emacs. +

    + +

    Happy hacking!

    diff --git a/public/posts/2010.01.17-working-with-c-style-structs-in-ruby.html b/public/posts/2010.01.17-working-with-c-style-structs-in-ruby.html new file mode 100644 index 0000000..a9bb0a2 --- /dev/null +++ b/public/posts/2010.01.17-working-with-c-style-structs-in-ruby.html @@ -0,0 +1,74 @@ +Title: Working with C-style structs in Ruby +Date: January 17, 2010 +Timestamp: 1263715200 +Author: sjs +Tags: ruby, cstruct, compiler +---- + +

    This is the beginning of a series on generating Mach-O object files in +Ruby. We start small by introducing some Ruby tools that are useful when +working with binary data. Subsequent articles will cover a subset of the +Mach-O file format, then generating Mach object files suitable for linking +with ld or gcc to produce working executables. A basic knowledge of Ruby and C +are assumed. You can likely wing it on the Ruby side of things if you know any +similar languages.

    + +

    First we need to read and write structured binary files with Ruby. Array#pack and +String#unpack +get the job done at a low level, but every time I use them I have to look up +the documentation. It would also be nice to encapsulate serializing and +deserializing into classes describing the various binary data structures. The +built-in Struct +class sounds promising but did not meet my needs, nor was it easily +extended to meet them.

    + +

    Meet CStruct, +a class that you can use to describe a binary structure, somewhat similar to +how you would do it in C. Subclassing CStruct results in a class whose +instances can be serialized, and unserialized, with little effort. You can +subclass descendants of CStruct to extend them with additional members. +CStruct does not implement much more than is necessary for the compiler. For +example there is no support for floating point. If you want to use this for +more general purpose tasks be warned that it may require some work. Anything +supported by Array#pack is fairly easy to add though.

    + +

    First a quick example and then we'll get into the CStruct class itself. In +C you may write the following to have one struct "inherit" from another:

    + +

    + +

    With CStruct in Ruby that translates to:

    + +

    + +

    CStructs act like Ruby's built-in Struct to a certain extent. They are +instantiated the same way, by passing values to #new in the same order they +are defined in the class. You can find out the size (in bytes) of a CStruct +instance using the #bytesize method, or of any member using #sizeof(name).

    + +

    The most important method (for us) is #serialize, which returns a binary +string representing the contents of the CStruct.

    + +

    (I know that CStruct.new_from_bin should be called CStruct.unserialize, you +can see where my focus was when I wrote it.)

    + +

    CStruct#serialize automatically creates a "pack pattern", which is an array +of strings used to pack each member in turn. The pack pattern is mapped to the +result of calling Array#pack on each corresponding member, and then the +resulting strings are joined together. Serializing strings complicates matters +so we cannot build up a pack pattern string and then serialize it in one go, +but conceptually it's quite similar.

    + +

    Unserializing is the same process in reverse, and was mainly added for +completeness and testing purposes.

    + +

    That's about all you need to know to use CStruct. The code needs some work +but I decided to just go with what I have already so I can get on with the +more interesting and fun tasks.

    + +

    Next in this series: Basics +of the Mach-O file format

    diff --git a/public/posts/2010.01.18-basics-of-the-mach-o-file-format.html b/public/posts/2010.01.18-basics-of-the-mach-o-file-format.html new file mode 100644 index 0000000..52739d0 --- /dev/null +++ b/public/posts/2010.01.18-basics-of-the-mach-o-file-format.html @@ -0,0 +1,165 @@ +Title: Basics of the Mach-O file format +Date: January 18, 2010 +Timestamp: 1263801600 +Author: sjs +Tags: mach-o, os x, compiler +---- + +

    This post is part of a series on generating basic x86 Mach-O files +with Ruby. The + +first post introduced CStruct, a Ruby class used to serialize +simple struct-like objects.

    + +

    Please note that the best way to learn about Mach-O properly is to +read Apple's + +documentation on Mach-O, which is pretty good combined with the +comments in /usr/include/mach-o/*.h. These posts will only cover +the basics necessary to generate a simple object file for linking with +ld or gcc, and are not meant to be comprehensive.

    + +

    Mach-O File Format Overview

    + +

    A Mach-O file consists of 2 main pieces: the header and +the data. The header is basically a map of the file describing +what it contains and the position of everything contained in it. The +data comes directly after the header and consists of a number of +binary blobs of data, one after the other.

    + +

    The header contains 3 types of records: the Mach header, +segments, and sections. Each binary blob is described +by a named section in the header. Sections are grouped into one or +more named segments. The Mach header is just one part of the header +and should not be confused with the entire header. It contains +information about the file as a whole, and specifies the number of +segments as well.

    + +

    Take a quick look at Figure 1 in + +Apple's Mach-O overview, which illustrates this quite nicely.

    + +

    A very basic Mach object file consists of a header followed by single +blob of machine code. That blob could be described by a single +section named __text, inside a single nameless segment. Here's a +diagram showing the layout of such a file:

    + +
    +
    +            ,---------------------------,
    +  Header    |  Mach header              |
    +            |    Segment 1              |
    +            |      Section 1 (__text)   | --,
    +            |---------------------------|   | 
    +  Data      |           blob            | <-'
    +            '---------------------------'      
    +
    + + +

    The Mach Header

    + +

    The Mach header contains the architecture (cpu type), the type of +file (object in our case), and the number of segments. There is more +to it but that's about all we care about. To see exactly what's in a +Mach header fire up a shell and type otool -h /bin/zsh (on a +Mac).

    + +

    Using + +CStruct we define the Mach header like so:

    + + + + +

    Segments

    + +

    Segments, or segment commands, specify where in memory the +segment should be loaded by the OS, and the number of bytes to +allocate for that segment. They also specify which bytes inside the +file are part of that segment, and how many sections it contains.

    + +

    One benefit to generating an object file rather than an executable is +that we let the linker worry about some details. One of those details +is where in memory segments will ultimately end up.

    + +

    Names are optional and can be arbitrary, but the convention is to +name segments with uppercase letters preceded by two underscores, +e.g. __DATA or __TEXT

    + +

    The code exposes some more details about segment commands, but should +be easy enough to follow.

    + + + + +

    Sections

    + +

    All sections within a segment are described one after the other +directly after each segment command. Sections define their name, +address in memory, size, offset of section data within the file, and +segment name. The segment name might seem redundant but in the next +post we'll see why this is useful information to have in the section +header.

    + +

    Sections can optionally specify a map to addresses within their +binary blob, called a relocation table. This is used by the +linker. Since we're letting the linker work out where to place +everything in memory the addresses inside our machine code will need +to be updated.

    + +

    By convention segments are named with lowercase letters preceded by +two underscores, e.g. __bss or __text

    + +

    Finally, the Ruby code describing section structs:

    + + + + +

    macho.rb

    + +

    As much of the Mach-O format as we need is defined in + +asm/macho.rb. The Mach header, Segment commands, sections, +relocation tables, and symbol table structs are all there, with a few +constants as well.

    + +

    I'll cover symbol tables and relocation tables in my next post.

    + + +

    Looking at real Mach-O files

    + +

    To see the segments and sections of an object file, run +otool -l /usr/lib/crt1.o. -l is for load commands. +If you want to see why we stick to generating object files instead of +executables run otool -l /bin/zsh. They are complicated +beasts.

    + +

    If you want to see the actual data for a section otool provides a +couple of ways to do this. The first is to use +otool -d <segment> <section> for an arbitrary +section. To see the contents of a well-known section, such as __text +in the __TEXT segment, use otool -t /usr/bin/true. You can +also disassemble the __text section with +otool -tv /usr/bin/true.

    + +

    You'll get to know otool quite well if you work with Mach-O.

    + + +

    Take a break

    + +

    That was probably a lot to digest, and to make real sense of it you +might need to read some of the + +official documentation.

    + +

    We're close to being able to describe a minimal Mach object file +that can be linked, and the resulting binary executed. By the end of +the next post we'll be there.

    + +

    (You can almost do that with what we know now. If you +create a Mach file with a Mach header (ncmds=1), a single unnamed +segment (nsects=1), and then a section named __text with a segment +name of __TEXT, and some x86 machine code as the section data, you +would almost have a useful Mach object file.)

    + +

    Till next time, happy hacking!

    diff --git a/public/posts/2010.01.20-a-preview-of-mach-o-file-generation.html b/public/posts/2010.01.20-a-preview-of-mach-o-file-generation.html new file mode 100644 index 0000000..8837db5 --- /dev/null +++ b/public/posts/2010.01.20-a-preview-of-mach-o-file-generation.html @@ -0,0 +1,26 @@ +Title: A preview of Mach-O file generation +Date: January 20, 2010 +Timestamp: 1263974400 +Author: sjs +Tags: ruby, mach-o, os x, compiler +---- + +

    This month I got back into an x86 compiler I started last May. It lives on github.

    + +

    The code is a bit of a mess but it mostly works. It generates Mach object +files that are linked with gcc to produce executable binaries.

    + +

    The Big Refactoring of January 2010 has come to an end and the tests pass +again, even if printing is broken it prints something, and more +importantly compiles test/test_huge.code into something that works.

    + +

    After print is fixed I can clean up the code before implementing anything +new. I wasn't sure if I'd get back into this or not and am pretty excited +about it. I'm learning a lot from this project.

    + +

    If you are following the Mach-O posts you might want to look at +asm/machofile.rb, a library for creating Mach-O files. Using it is quite +straightforward, an example is in asm/binary.rb, in the #output method.

    + +

    Definitely time for bed now!

    diff --git a/public/posts/2010.11.04-37signals-chalk-dissected.html b/public/posts/2010.11.04-37signals-chalk-dissected.html new file mode 100644 index 0000000..735d2d0 --- /dev/null +++ b/public/posts/2010.11.04-37signals-chalk-dissected.html @@ -0,0 +1,224 @@ +Title: 37signals' Chalk Dissected +Date: November 4, 2010 +Timestamp: 1288854000 +Author: sjs +Tags: 37signals, chalk, ipad, javascript, web, html, css, zepto.js +---- + +

    Update 2010-11-05: I dove into the JavaScript a little and explained most of it. Sam Stephenson tweeted that Chalk is written in CoffeeScript and compiled on the fly when served using Brochure. That's hot! (for those unaware Sam Stephenson works at 37signals, and is also the man behind Prototype.)

    + +

    37signals recently released a blackboard web app for iPad called Chalk.

    + +

    It includes Thomas Fuchs new mobile JS framework Zepto, a few images, iOS SpringBoard icon, and of course HTML, CSS, and JavaScript. It weighs in at about 244k including 216k of images. HTML, CSS, and JavaScript are not minified (except Zepto), but they are gzipped. Because the image-to-text ratio is high gzip can only shave off 12k. There is absolutely nothing there that isn't required though. The code and resources are very tight, readable, and beautiful.

    + +

    The manifest is a nice summary of the contents, and allows browsers to cache the app for offline use. Combine this with mobile Safari's "Add to Home Screen" button and you have yourself a free chalkboard app that works offline.

    + +
    CACHE MANIFEST
    +
    +/
    +/zepto.min.js
    +/chalk.js
    +/images/background.jpg
    +/images/chalk.png
    +/images/chalk-sprites.png
    +/images/chalk-tile-erase.jpg
    +/images/chalk-tile-red.png
    +/images/chalk-tile-white.png
    +/stylesheets/chalk.css
    +
    + +

    Not much there, just 10 requests to fetch the whole thing. 11 including the manifest. In we go.

    + +

     

    +

    HTML

    + +

    2k, 61 lines. 10 of which are Google Analytics JavaScript. Let's glance at some of it.

    + + + +

    Standard html5 doctype, and a manifest for application caching.

    + +

    The rest of the HTML is mainly structural. There is not a single text node in the entire tree (excluding whitespace). The chalkboard is a canvas element and an image element used to render the canvas contents as an image for sharing. The other elements are just sprites and buttons. There are div elements for the light switch and shade (a dimmer on each side), share button, instructions on sharing, close button, ledge, chalk, eraser and corresponding indicators. Phew, that was a mouthful. (oblig: "that's what she said!")

    + +

    The interesting thing about the HTML is that without any JavaScript or CSS the document would be a completely blank white page (except for a strange looking share button w/ no title). Talk about progressive enhancement. Here's a look at the HTML:

    + + + +

    Onward.

    + +

     

    +

    Zepto

    + +

    Zepto is a tiny, modern JS framework for mobile WebKit browsers such as those found on iPhone and Android handsets. I'm not going to cover it here but I'll mention that it's similar in feel to jQuery. In fact it tries to mimic jQuery very closely to make migrations from Zepto to jQuery easy, and vice versa. The reason it weighs in at just under 6k (2k gzipped) is that it doesn't overreach or have to support legacy crap like IE6. It was started by Thomas Fuchs so you know it's good.

    + +

     

    +

    Display (CSS & Images)

    + +

    6.6k, 385 lines. This is basically half of the text portion, excluding Zepto. There are 6 images including one called chalk-sprites.png. Interesting. Let's look at the background first though.

    + +

     

    +

    Background

    + +

     

    +
    +
    +background.jpg 1024x946px
    + +

    The background is the blackboard itself, and is almost square at 1024x946. The cork border and light switch are there too. This is set as the background-image of the html element and is positioned at a negative x or y in order to centre it properly. CSS media queries are used to detect the screen's orientation. This way the same image is used for both orientations, clever.

    + + + +

     

    +

    Chalkboard

    + +

    Just a canvas element positioned over the chalkboard using media queries. There's also an image element called "output" used to render an image for sharing.

    + + + +

     

    +

    Sprites

    + +

     

    +
    +
    +chalk-sprites.png
    + +

    Sprites are used for all the other elements: ledge, chalk, eraser, tool indicator, share button, instructions, and close button (to leave the sharing mode). Positioned using CSS, standard stuff. There is white text alongside those green arrows. If you want to see it we'll have to change the background to black.

    + +

     

    +

    Light Switch & Shade

    + +

    When you touch the light switch on the left side of the chalkboard - only visible in landscape orientation - the cork border dims and the ledge and share button disappear, leaving the chalkboard under the spotlight all classy like. The shade consists of two "dimmer" div elements inside a shade div, which is hidden by default.

    + +

    The dimmers background color is black at 67% opacity. The shade element fades in using -webkit-transition: on its visibility property while the dimmers use CSS3 transitions on their background. The dimmers are positioned using media queries as well, one on each side of the board. Interestingly their parent shade has a height and width of 0. Rather than each having a unique id they just have the class "dim" and the :nth-child pseudo-class selector is used to position them independently.

    + + + +

    If you took a look at the HTML before you'll have noticed there's no shade class defined on the body element. Looks like they're using JavaScript to add the shade class to body, triggering the transitions to the visible shades and setting the dimmers backgrounds to black at the same time, causing the fading effect. The shade fades in while the ledge and share button fade out.

    + +

    The light switch itself is displayed only in landscape orientation, again using a media query.

    + +

     

    +

    Tools

    + +

    There are 2 layers to the tools on the ledge. There are the images of the tools and their indicators, but also an anchor element for each tool that acts as targets to select them. When tools are select the indicators fade in and out using CSS3 transitions on opacity by adding and removing the class "active" on the tool.

    + + + +

    There are pattern images for each colour of chalk, and one for the the eraser. The eraser "pattern" is the entire blackboard so erasing it doesn't look ugly. I love that kind of attention to detail.

    + +

     

    +

    Sharing

    + +

    The shade effect that happens when you hit the share button is similar to the shade effect used for the light switch. It's a bit more complex as the sharing instructions are positioned differently in portrait and landscape orientations, but there's nothing really new in there (that I can see).

    + +

    The rest of the CSS is largely presentational stuff like removing margins and padding, and positioning using lots of media queries. You can see it all at chalk.37signals.com/stylesheets/chalk.css.

    + +

     

    +

    JavaScript (and CoffeeScript)

    + +

    5.5k in about 170 lines. That's just half the size of the CSS.

    + +

    Sam Stephenson shared the original CoffeeScript source with us. It's about 150 lines, and is a bit easier to read as CS is far cleaner than JS.

    + +

    The bulk of the magic is done w/ hardware accelerated CSS3 rather than slow JS animation using setInterval and setTimeout to change properties. That sort of thing isn't novel anymore anyway. The fact that JS is really only used for drawing and toggling CSS classes is pretty awesome!

    + +

    The entire contents of the JS reside inside the DOMContentLoaded event handler attached to window.

    + +

     

    +

    Initialization

    + +

     

    + + +

    First we get a handle on all the elements and the canvas' 2d drawing context. I almost want to say views and controls as it really feels just like hooking up a controller and view in a desktop GUI app. Sometimes the line between dynamic web page and web app are blurred, not so here. Chalk is 100% app.

    + +

    The canvas' dimensions and pen are initialized in lines 13 - 19, and then the chalkboard background is drawn onto the canvas using the drawImage() method.

    + +

    The canvas offsets are cached for calculations, and are updated when the window fires the "orientationChange" event. Next up tools (a.k.a. pens) are created and initialized.

    + +

     

    +

    Tools

    + +

     

    + + +

    createPattern(name, callback) loads one of the pattern images, chalk-tile-*, and then creates a pattern in the drawing context and passes it to the given callback.

    + +

    setStroke(pattern, width) effectively sets the pen used for drawing, described as a pattern & stroke width. The patterns are initialized and the white pen is passed to setStroke since it's the default tool.

    + +

    The last part defines the 3 tools, note that the active tool "white_chalk" is at the end. Also note that the tool names are the ids of the target elements in the ledge. activateTool(tool) accepts a tool name. The tool to activate is moved to the end of the tools array on lines 31-32, activeTool is set to the given tool as well on line 32. The reason for moving the active tool to the end of the array is revealed in the for loop on line 34, the order of the tools array determines their z-index ordering (highest number is in front). Then the 'active' CSS class is added to the active tool to show the indicator, and then the pen is set by assigning a pen to the context's strokeStyle property.

    + +

    Finally the white_chalk tool is activated and the click event for the tool targets is setup.

    + +

     

    +

    Drawing

    + +

     

    + + +

    Drawing is done by listening for touch events on the canvas element. An array of points to draw is initialized to a 1-element array containing null. Null values make the draw function break up the line being drawn by skipping the next point in the array. x and y coords are initialized in touchstart, points are appended to the points array in touchmove, and the touchend handler appends two points and null to the points array to end the line. I'm not sure why [x, y] is used as the points in the touchend handler rather than coords from the event. Please leave a comment if you know why!

    + +

    The draw function is called for each point in the points array at 30ms intervals. A line is started by calling context.beginPath(), each point is drawn, and then the line is ended with context.stroke(). The 2nd condition of the while loop ensures that we don't draw for too long, as bad things would happen if the function were executed a 2nd time while it was already running.

    + +

    Sam Stephenson was kind enough to clarify these points. See his comment below the post for clarification on using [x, y] in the touchend handler and the 10ms limit when drawing points.

    + +

     

    +

    Light Switch & Shade

    + +

     

    + + +

    When the light switch is touched (or clicked) the shade class on the body element is toggled. Nothing to it.

    + +

     

    +

    Sharing

    + +

     

    + + +

    The share window is opened after a 10ms delay, just enough time for any drawing to be completed before rendering the image. The image is created by assigning the result of canvas' toDataURL() method to the output image element's src attribute.

    + +

    When the share window is closed the output image element gets its src set to the sprites image. I'm not sure why that was done. As Sam mentions in his comment below, this is done to reclaim the memory used by the rendered image.

    + +

    The rest of the code there just sets up event handlers and toggles CSS classes.

    + +

     

    +

    That's it!

    + +

    That about covers it. Don't have an iPad? Play around with it anyway, but be warned that you can't draw anything. You can select chalk and the eraser and hit the light switch. I instinctively tried touching my MacBook's display but alas it doesn't magically respond to touches, lame.

    + +

    Have fun drawing. Thanks to 37signals for a beautiful (and useful) example of a few modern web technologies.

    + + + diff --git a/public/posts/2011.11.27-lights.md b/public/posts/2011.11.27-lights.md new file mode 100644 index 0000000..4d4db3c --- /dev/null +++ b/public/posts/2011.11.27-lights.md @@ -0,0 +1,6 @@ +Title: Lights +Date: November 27, 2011 +Timestamp: 1322446260 +Link: http://lights.elliegoulding.com/ +---- +An interactive WebGL visualization. Where's the LSD when you need it? diff --git a/public/posts/2011.11.27-recovering-old-posts.md b/public/posts/2011.11.27-recovering-old-posts.md new file mode 100644 index 0000000..cbf736e --- /dev/null +++ b/public/posts/2011.11.27-recovering-old-posts.md @@ -0,0 +1,9 @@ +Title: Recovering Old Blog Posts +Date: November 27, 2011 +Timestamp: 1322385300 +Author: sjs +Tags: recover, old, blog, posts +---- + +I'm in the process of recovering some old blog posts from the [Wayback Machine](http://web.archive.org). +Some of them might be culled, because nobody cares about my old blog posts except for me. diff --git a/public/posts/2011.12.10-static-url-shortener-using-htaccess.md b/public/posts/2011.12.10-static-url-shortener-using-htaccess.md new file mode 100644 index 0000000..4abb2c0 --- /dev/null +++ b/public/posts/2011.12.10-static-url-shortener-using-htaccess.md @@ -0,0 +1,23 @@ +Title: A Static URL Shortener Using .htaccess +Date: December 10, 2011 +Timestamp: 1323584949 +Author: sjs +Tags: s42.ca, url, shortener, samhuri.net, url shortener +---- + +This blog is statically generated. A few Ruby and Node.js scripts along with a Makefile and some duct tape hold it all together. All of [samhuri.net is on Github][GH] if you want to take a look. Most of it is quite minimal, sometimes to a fault. Little improvements are made here and there and the most recent one is neat [.htaccess][htaccess-wiki] hack. I want to automatically announce new posts on Twitter so short URLs are in order. + +I try to strike a reasonable balance between writing everything for this site myself and using libraries. A quick look at a few short URL projects was enough to see they weren't what I was looking for. They were all database backed servers. Comments on this blog are served up dynamically but everything else is static and I try to avoid dynamic behaviour when possible. Comments are moving to a more static system sometime. Anyway I registered the domain [s42.ca][s42] and nabbed [an algorithm for creating the short codes from Jonathan Snook][snook] before diving into TextMate to implement my idea. + +The result is about two dozen additional lines of Ruby in my static generator, and a command added to a Makefile. The Ruby code generates a short URL for each of my blog posts and then creates a [RewriteRule][RewriteRule] directive to redirect that short codes to each corresponding blog post. Then the directives are dumped into a .htaccess file which is [scp][scp]'d to s42.ca when I run `make publish_blog`. + + + +I think this is a pretty neat hack and have not seen this technique anywhere else so I thought I'd share it. Maybe someone else will find it interesting or useful for their blog. How far it scales won't be a concern until I have thousands of posts. That sounds like a good problem for future Sami to solve should it arise. + +[GH]: https://github.com/samsonjs/samhuri.net +[htaccess-wiki]: http://en.wikipedia.org/wiki/Htaccess +[s42]: http://s42.ca +[snook]: http://snook.ca/archives/php/url-shortener +[RewriteRule]: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule +[scp]: http://en.wikipedia.org/wiki/Secure_copy diff --git a/public/posts/2011.12.11-pure-css3-images-hmm-maybe-later.html b/public/posts/2011.12.11-pure-css3-images-hmm-maybe-later.html new file mode 100644 index 0000000..0a44432 --- /dev/null +++ b/public/posts/2011.12.11-pure-css3-images-hmm-maybe-later.html @@ -0,0 +1,8 @@ +Title: Pure CSS3 images? Hmm, maybe later +Date: December 11, 2011 +Timestamp: 1323635103 +Link: http://calendar.perfplanet.com/2011/pure-css3-images-hmm-maybe-later/ +---- +Great analysis of the performance of CSS based images. Not directly +mentioned, but very apparent, is that the task of making CSS images itself +is prohibitively difficult. diff --git a/public/posts/2011.12.15-i-see-http.html b/public/posts/2011.12.15-i-see-http.html new file mode 100644 index 0000000..078ce57 --- /dev/null +++ b/public/posts/2011.12.15-i-see-http.html @@ -0,0 +1,7 @@ +Title: I see HTTP +Date: December 15, 2011 +Timestamp: 1323964035 +Link: http://calendar.perfplanet.com/2011/i-see-http/ +---- +Icy is a public domain iOS app that lets you see everything a web page +loads in great detail. This looks useful. diff --git a/public/posts/2011.12.19-my-kind-of-feature-checklist.html b/public/posts/2011.12.19-my-kind-of-feature-checklist.html new file mode 100644 index 0000000..fde80d2 --- /dev/null +++ b/public/posts/2011.12.19-my-kind-of-feature-checklist.html @@ -0,0 +1,14 @@ +Title: My kind of feature checklist +Date: December 19, 2011 +Timestamp: 1324354805 +Link: http://www.marco.org/2011/12/19/amazon-kindle-vs-ipad +Comments: off +---- +Marco's feature checklist in favour of the iPad illustrates how easy it is +to rig these things. Combined with Amazon's checklist favouring the Kindle +Fire this would be mildly useful, half as long as a modest review, and with +more or less the same conclusions. + +Seriously though some of the items on Marco's list are pretty important to +most people but would never make anyone's feature checklist. Goes to show +that most feature checklists are bullshit. diff --git a/public/posts/2011.12.22-new-release-of-firefox-for-android-optimized-for-tablets.html b/public/posts/2011.12.22-new-release-of-firefox-for-android-optimized-for-tablets.html new file mode 100644 index 0000000..1d879f9 --- /dev/null +++ b/public/posts/2011.12.22-new-release-of-firefox-for-android-optimized-for-tablets.html @@ -0,0 +1,16 @@ +Title: New Release of Firefox for Android, Optimized for Tablets +Date: December 22, 2011 +Timestamp: 1324868051 +Link: http://daringfireball.net/linked/2011/12/22/firefox-android +Comments: off +---- + +> On the other hand, watch this video. Even in Mozilla's own demo - which presumably puts Firefox for Android in its best light - doesn't the whole thing look a bit herky-jerky, in terms of touch responsiveness and scrolling smoothness? + +Surely they could do better on iOS though. I have faith in the Firefox +team to provide a good experience because they have done so in the +past. Modern versions of Firefox are excellent. + +[New Release of Firefox for Android, Optimized for +Tablets](http://blog.mozilla.com/blog/2011/12/20/new-firefox-for-android-ex= +perience-optimized-for-tablets/) diff --git a/public/posts/2011.12.25-the-broken-pixel-theory.html b/public/posts/2011.12.25-the-broken-pixel-theory.html new file mode 100644 index 0000000..0031bc6 --- /dev/null +++ b/public/posts/2011.12.25-the-broken-pixel-theory.html @@ -0,0 +1,10 @@ +Title: The Broken Pixel Theory +Date: December 25, 2011 +Timestamp: 1324868060 +Link: http://jtaby.com/2011/12/25/the-broken-pixel-theory.html +Comments: off +---- + +> For example, a clean desk tends to stay clean until a piece of paper stays on it for a couple of days. Similarly, I=92m much less likely to care about a 2-3 pixel UI bug when the whole UI is a mess. + +Great insight from Majd Taby. diff --git a/public/posts/2012.01.04-yak-shaving.md b/public/posts/2012.01.04-yak-shaving.md new file mode 100644 index 0000000..30c0846 --- /dev/null +++ b/public/posts/2012.01.04-yak-shaving.md @@ -0,0 +1,8 @@ +Title: Yak shaving +Date: January 4, 2012 +Timestamp: 1325712240 +Link: http://blog.hasmanythrough.com/2012/1/4/yak-shaving +Comments: off +---- + +The best plain-english explanation of yak shaving I have seen. diff --git a/public/posts/2012.01.09-the-40-standup-desk.md b/public/posts/2012.01.09-the-40-standup-desk.md new file mode 100644 index 0000000..6124a7d --- /dev/null +++ b/public/posts/2012.01.09-the-40-standup-desk.md @@ -0,0 +1,10 @@ +Title: The $40 Standup Desk +Date: January 9, 2012 +Timestamp: 1326097000 +Link: http://opensoul.org/blog/archives/2012/01/09/the-40-standup-desk/ +Comments: off +---- + +> Ultimately, I decided I might as well just do something cheap for now. So I built my own. I had thinking about doing it for a while when my coworker Steve Smith built his desk. After seeing his, I was convinced this was what I wanted to do. It turns out, the cheap option is pretty awesome. + +This looks great. Might have to consider it when or if I get a desk. diff --git a/public/posts/2012.01.17-recovering-from-a-computer-science-education.md b/public/posts/2012.01.17-recovering-from-a-computer-science-education.md new file mode 100644 index 0000000..5b183c5 --- /dev/null +++ b/public/posts/2012.01.17-recovering-from-a-computer-science-education.md @@ -0,0 +1,8 @@ +Title: Recovering From a Computer Science Education +Date: January 17, 2012 +Timestamp: 1326787200 +Link: http://prog21.dadgum.com/123.html +Comments: off +---- + +Something to keep in mind. diff --git a/public/posts/2012.01.17-sopa-lives-and-mpaa-calls-protests-an-abuse-of-power.md b/public/posts/2012.01.17-sopa-lives-and-mpaa-calls-protests-an-abuse-of-power.md new file mode 100644 index 0000000..0c67192 --- /dev/null +++ b/public/posts/2012.01.17-sopa-lives-and-mpaa-calls-protests-an-abuse-of-power.md @@ -0,0 +1,37 @@ +Title: SOPA lives - and MPAA calls protests an "abuse of power" +Date: January 17, 2012 +Timestamp: 1326797200 +Link: http://arstechnica.com/tech-policy/news/2012/01/sopa-livesand-mpaa-calls-protests-an-abuse-of-power.ars +Comments: off +---- + +> rather than coming to the table to find solutions to a problem that all +now seem to agree is very real and damaging. + +No. All most certainly do *not* agree. + +> It is also an abuse of power given the freedoms these companies enjoy in +the marketplace today. It's a dangerous and troubling development when the +platforms that serve as gateways to information intentionally skew the +facts to incite their users in order to further their corporate interests. + +This must be a joke. It's a joke, right? Please tell me this joker is +joking. The hypocrisy is too much. + +> stop the hyperbole and PR stunts and engage in meaningful efforts to +combat piracy. + +There is absolutely nothing reasonable that anyone can do to "combat +piracy". Digital copies are cheap. Adapt or die. + +The VCR did not kill media industries. Nor the cassette, CD, DVD. Why +should anyone believe that computers and the Internet are going to kill +music and movies? + +If the MPAA displayed even a shred of sanity maybe they would be taken +seriously in their efforts to curb piracy. The biggest problem I can see is +that studies have given us evidence that they are not hurt by it at all. +Their tactic of choice seems to be to loudly decry "Nuh-uh! Piracy +*does* hurt us!" and then strong arming everyone worldwide while suing anyone and +everyone. If times are so tough maybe they should cut some of their budgets +for lawyers and lobbyists. diff --git a/public/posts/2012.01.19-fujitsu-has-lost-their-mind.md b/public/posts/2012.01.19-fujitsu-has-lost-their-mind.md new file mode 100644 index 0000000..6819ac5 --- /dev/null +++ b/public/posts/2012.01.19-fujitsu-has-lost-their-mind.md @@ -0,0 +1,10 @@ +Title: Fujitsu has lost their mind +Date: January 19, 2012 +Timestamp: 1327032333 +Link: http://tablet-news.com/2012/01/17/fujitsu-lifebook-2013-concept-incorporates-a-tablet-for-a-keyboard-phone-and-digital-camera/ +Comments: off +---- + +Does this even warrant any comments on why it's already a massive failure? +The many, many drawbacks seem so apparent I cannot believe this escaped +from their drawing board. diff --git a/public/posts/2013.03.06-zelda-tones-for-ios.html b/public/posts/2013.03.06-zelda-tones-for-ios.html new file mode 100644 index 0000000..0380440 --- /dev/null +++ b/public/posts/2013.03.06-zelda-tones-for-ios.html @@ -0,0 +1,59 @@ +Title: Zelda Tones for iOS +Date: March 6, 2013 +Timestamp: 1362624673 +Author: sjs +Tags: zelda, nintendo, pacman, ringtones, tones, ios +---- + +

    Zelda

    + +

    + Matt Gemmell recently shared some + sweet Super Nintendo wallpapers for iPhone 5. + Although I don't have an iPhone 5 I was happy to snap them up and crop them for my 4S. +

    + +

    + If you like that sort of thing then you might want these tones that I whipped up. The first pack is a few Zelda + ringtones along with a few more SMS tones. Most of them are from + A Link to the Past. +

    + +

    Get the Zelda tones

    + +
      +
    • Theme
    • +
    • Overworld overture
    • +
    • Song of Storms
    • +
    • Secret
    • +
    • Item
    • +
    • Achievement
    • +
    + + +

    Pacman

    + +

    The second pack is two Pacman tones.

    +

    Get the Pacman tones

    + +
      +
    • Pacman starts
    • +
    • Pacman dies
    • +
    + + +

    O Fortuna

    + +

    + Okay okay, one last one. + O Fortuna from + Carmina Burana, + composed by Carl Orff, + performed by the London Philharmonic Orchestra. +

    + +
    • O Fortuna
    + +

    Get the O Fortuna ringtone

    + +

    Enjoy!

    diff --git a/public/posts/2013.09.27-linky.md b/public/posts/2013.09.27-linky.md new file mode 100644 index 0000000..e776b30 --- /dev/null +++ b/public/posts/2013.09.27-linky.md @@ -0,0 +1,81 @@ +Title: Linky +Date: September 27, 2013 +Timestamp: 1380343742 +Author: sjs +Tags: linky, north watcher, ruby, gmail, links, notifications +---- + +## Send links from mobile devices to your computers. + +The last few months I've been annoyed by my workflow for sending links from my touch devices to my computers. For example if I come across a cool Mac app or an open source project I want to check out, or anything along those lines. Until now I have been mailing links to my work or home addresses, or saving links in Instapaper. The problem with both of those is the same: I have to remember to check something when I arrive at the correct machine. It sounds trivial but I have been annoyed by it nonetheless. + +This weekend I finally decided to scratch that itch and ended up writing much less code than I imagined to accomplish it in a perfectly acceptable way. The components are: + + - [Gmail](https://mail.google.com) + - [IFTTT (If This Then That)](http://ifttt.com) + - [DropBox](https://dropbox.com) + - [NorthWatcher](https://github.com/samsonjs/NorthWatcher) + - [a (short) Ruby program](https://github.com/samsonjs/bin/blob/master/linky-notify) + - [terminal-notifier](https://github.com/alloy/terminal-notifier) (which displays [native notifications in OS X](http://support.apple.com/kb/HT5362)) + +Yup, that is a lot of moving parts. It is rather elegant in a [Unixy way](http://www.catb.org/~esr/writings/taoup/) though. + +*I experimented with Gmail → IFTTT → [Boxcar](http://boxcar.io) → [Growl](http://growl.info/), but Boxcar's Mac app is really rough and didn't seem to pick up new messages at all, let alone quickly, so I fell back to a solution with more parts.* + + +### Gmail + +[Gmail](https://mail.google.com) allows you to append extra info to your email address in the username, which you can use for filtering and labeling. I send links to sami.samhuri+linky@gmail.com and then filter those messages out of my inbox, as well as applying the label *linky*. Using email as the entry point means that basically every app I use already supports sending links in this way. + + +### IFTTT + +[IFTTT (If This Then That)](http://ifttt.com) can wire up services, so that events that happen in one place can trigger an action elsewhere, passing along some info about the event along with it. In this case when a new email arrives in my Gmail account with the label *linky* then I create a text file in Dropbox that contains two lines: the title, followed by the link itself. + +For example, the following lines would be created in a file at `~/Dropbox/Linky/Ruxton/.txt` for my machine named [Ruxton](http://en.wikipedia.org/wiki/Ruxton_Island). + + Callbacks as our Generations' Go To Statement + http://tirania.org/blog/archive/2013/Aug-15.html + +The filename field is defined as: + + {FromAddress}-{ReceivedAt} + +And the content is: + + {Subject}
    + {BodyPlain}
    + +That means that when you email links, the subject should contain the title and the body should contain the link on the first line. It's ok if there's stuff after the body (like your signature), they will be ignored later. + +I create one recipe in IFTTT for each machine that I want links to appear on. You could get fancy and have different Gmail labels for individual machines, or aliases, groups, etc. I've kept it simple and just have every link I send go to both my home & work computers. + + +### Dropbox + +Dropbox is fantastic. My files are [never not everywhere](http://5by5.tv/b2w/37). IFTTT creates the file in Dropbox, and then Dropbox makes sure it hits all of my machines. Did I mention that Dropbox is awesome? It's awesome. + + +### NorthWatcher + +This is a quick and dirty thing I whipped up a couple of years ago, and now it's come in handy again. It's a program that watches directories for added and removed files, and then launches a program that can then react to the change. In this case, on each machine I want notifications on, I have it watch the Dropbox folder where IFTTT creates the text files. e.g. `~/Dropbox/Linky/Ruxton` + +It has a text configuration file kind of like [cron](http://en.wikipedia.org/wiki/Cron). Here's mine from Ruxton: + + + Dropbox/Linky/Ruxton ruby /Users/sjs/bin/linky-notify + +That tells NorthWatcher to run `ruby /Users/sjs/bin/linky-notify` when files are added to the directory `~/Dropbox/Linky/Ruxton`. + +*[NorthWatcher is on GitHub](https://github.com/samsonjs/NorthWatcher) and [npm](https://npmjs.org). Install [node](http://nodejs.org) and then run `npm install -g northwatcher`. After creating the config file at `~/.northwatcher` you can run it automatically using [this launchd config file](https://gist.github.com/samsonjs/6657795). Drop that in `~/Library/LaunchAgents/net.samhuri.northwatcher.plist`. Don't forget to update the working directory path, and run `launchctl load ~/Library/LaunchAgents/net.samhuri.northwatcher.plist` to load it up (afterwards it will load on boot).* + + +### A Ruby program, and terminal-notifier + +Finally, we have the last two components of the system. A [short Ruby program (`/Users/sjs/bin/linky-notify`)](https://github.com/samsonjs/bin/blob/master/linky-notify) that reads in all the files NorthWatcher reports as added, and uses `terminal-notifier` to show a native OS X notification for each link. After displaying the notification it moves the text file into a subfolder named `Archive`, so I have a record of all the links I have sent myself. + +You can get `terminal-notifier` with [homebrew](http://brew.sh) in a few seconds: `brew install terminal-notifier`. After you have used `terminal-notifier` you will be able to go into *Notifications* in *System Preferences* and change it from *Banners* to *Alerts*. *Banners* are transient, while *Alerts* are persistent and have action buttons: `Show` and `Close`. + + +## Cool story, bro + +It may not be exciting, but as someone who typically suffers from [NIH syndrome](http://en.wikipedia.org/wiki/Not_invented_here) and writes too much from scratch, I found it pretty rewarding to cobble something seemingly complicated together with a bunch of existing components. It didn't take very long and only involved about 10 lines of code. It's not exactly what I wanted but it's surprisingly close. Success! diff --git a/public/posts/2014.02.03-ember-structure.md b/public/posts/2014.02.03-ember-structure.md new file mode 100644 index 0000000..65511a3 --- /dev/null +++ b/public/posts/2014.02.03-ember-structure.md @@ -0,0 +1,11 @@ +Title: Structure of an Ember app +Date: February 3, 2014 +Timestamp: 1391479549 +Author: sjs +Tags: ember.js +---- + +I made a diagram of an Ember app. There's [a discussion about it](http://discuss.emberjs.com/t/diagram-of-an-ember-apps-structure/4060) on the +[Ember Discussion Forum](http://discuss.emberjs.com/). Here is the source file, created with OmniGraffle: [Ember structure.graffle](https://www.dropbox.com/s/onnmn1oq096hv5f/Ember%20structure.graffle) + +![Structure of an Ember app](/f/ember-structure.png) diff --git a/public/posts/_data.json b/public/posts/_data.json new file mode 100644 index 0000000..36389b9 --- /dev/null +++ b/public/posts/_data.json @@ -0,0 +1,1296 @@ +{ + "2006.02.08-first-post": { + "title": "First Post!", + "date": "February 8, 2006", + "timestamp": 1139368860, + "tags": [ + "life" + ], + "author": "sjs", + "url": "/posts/2006.02.08-first-post" + }, + "2006.02.08-touch-screen-on-steroids": { + "title": "Touch Screen on Steroids", + "date": "February 8, 2006", + "timestamp": 1139407560, + "tags": [ + "technology", + "touch" + ], + "author": "sjs", + "url": "/posts/2006.02.08-touch-screen-on-steroids" + }, + "2006.02.15-urban-extreme-gymnastics": { + "title": "Urban Extreme Gymnastics?", + "date": "February 15, 2006", + "timestamp": 1140028860, + "tags": [ + "amusement" + ], + "author": "sjs", + "url": "/posts/2006.02.15-urban-extreme-gymnastics" + }, + "2006.02.18-girlfriend-x": { + "title": "Girlfriend X", + "date": "February 18, 2006", + "timestamp": 1140292200, + "tags": [ + "crazy", + "funny" + ], + "author": "sjs", + "url": "/posts/2006.02.18-girlfriend-x" + }, + "2006.02.18-jump-to-viewcontroller-in-textmate": { + "title": "Jump to view/controller in TextMate", + "date": "February 18, 2006", + "timestamp": 1140303060, + "tags": [ + "hacking", + "rails", + "textmate", + "rails", + "textmate" + ], + "author": "sjs", + "url": "/posts/2006.02.18-jump-to-viewcontroller-in-textmate" + }, + "2006.02.18-some-textmate-snippets-for-rails-migrations": { + "title": "Some TextMate snippets for Rails Migrations", + "date": "February 18, 2006", + "timestamp": 1140331680, + "tags": [ + "textmate", + "rails", + "hacking", + "rails", + "snippets", + "textmate" + ], + "author": "sjs", + "url": "/posts/2006.02.18-some-textmate-snippets-for-rails-migrations" + }, + "2006.02.20-obligatory-post-about-ruby-on-rails": { + "title": "Obligatory Post about Ruby on Rails", + "date": "February 20, 2006", + "timestamp": 1140424260, + "tags": [ + "rails", + "coding", + "hacking", + "migration", + "rails", + "testing" + ], + "author": "sjs", + "url": "/posts/2006.02.20-obligatory-post-about-ruby-on-rails", + "styles": [ + "typocode" + ] + }, + "2006.02.20-textmate-snippets-for-rails-assertions": { + "title": "TextMate Snippets for Rails Assertions", + "date": "February 20, 2006", + "timestamp": 1140508320, + "tags": [ + "textmate", + "rails", + "coding", + "rails", + "snippets", + "testing", + "textmate" + ], + "author": "sjs", + "url": "/posts/2006.02.20-textmate-snippets-for-rails-assertions" + }, + "2006.02.21-textmate-move-selection-to-self-down": { + "title": "TextMate: Move selection to self.down", + "date": "February 21, 2006", + "timestamp": 1140510360, + "tags": [ + "textmate", + "rails", + "hacking", + "hack", + "macro", + "rails", + "textmate" + ], + "author": "sjs", + "url": "/posts/2006.02.21-textmate-move-selection-to-self-down" + }, + "2006.02.21-textmate-insert-text-into-self-down": { + "title": "TextMate: Insert text into self.down", + "date": "February 21, 2006", + "timestamp": 1140562500, + "tags": [ + "textmate", + "rails", + "hacking", + "commands", + "macro", + "rails", + "snippets", + "textmate" + ], + "author": "sjs", + "url": "/posts/2006.02.21-textmate-insert-text-into-self-down", + "styles": [ + "typocode" + ] + }, + "2006.02.22-intelligent-migration-snippets-0.1-for-textmate": { + "title": "Intelligent Migration Snippets 0.1 for TextMate", + "date": "February 22, 2006", + "timestamp": 1140607680, + "tags": [ + "mac os x", + "textmate", + "rails", + "hacking", + "migrations", + "snippets" + ], + "author": "sjs", + "url": "/posts/2006.02.22-intelligent-migration-snippets-0.1-for-textmate" + }, + "2006.02.23-sjs-rails-bundle-0.2-for-textmate": { + "title": "SJ's Rails Bundle 0.2 for TextMate", + "date": "February 23, 2006", + "timestamp": 1140743880, + "tags": [ + "textmate", + "rails", + "coding", + "bundle", + "macros", + "rails", + "snippets", + "textmate" + ], + "author": "sjs", + "url": "/posts/2006.02.23-sjs-rails-bundle-0.2-for-textmate", + "styles": [ + "typocode" + ] + }, + "2006.03.03-generate-selfdown-in-your-rails-migrations": { + "title": "Generate self.down in your Rails migrations", + "date": "March 3, 2006", + "timestamp": 1141450680, + "tags": [ + "rails", + "textmate", + "migrations", + "rails", + "textmate" + ], + "author": "sjs", + "url": "/posts/2006.03.03-generate-selfdown-in-your-rails-migrations" + }, + "2006.03.03-spore": { + "title": "Spore", + "date": "March 3, 2006", + "timestamp": 1141450980, + "tags": [ + "amusement", + "technology", + "cool", + "fun", + "games" + ], + "author": "sjs", + "url": "/posts/2006.03.03-spore" + }, + "2006.03.03-i-dont-mind-fairplay-either": { + "title": "I don't mind FairPlay either", + "date": "March 3, 2006", + "timestamp": 1141451760, + "tags": [ + "apple", + "mac os x", + "life", + "drm", + "fairplay", + "ipod", + "itunes" + ], + "author": "sjs", + "url": "/posts/2006.03.03-i-dont-mind-fairplay-either" + }, + "2006.04.04-zsh-terminal-goodness-on-os-x": { + "title": "zsh terminal goodness on OS X", + "date": "April 4, 2006", + "timestamp": 1144187820, + "tags": [ + "mac os x", + "apple", + "osx", + "terminal", + "zsh" + ], + "author": "sjs", + "url": "/posts/2006.04.04-zsh-terminal-goodness-on-os-x" + }, + "2006.05.07-os-x-and-fitts-law": { + "title": "OS X and Fitt's law", + "date": "May 7, 2006", + "timestamp": 1147059780, + "tags": [ + "mac os x", + "apple", + "mac", + "os", + "usability", + "x" + ], + "author": "sjs", + "url": "/posts/2006.05.07-os-x-and-fitts-law" + }, + "2006.05.07-wikipediafs-on-linux-in-python": { + "title": "WikipediaFS on Linux, in Python", + "date": "May 7, 2006", + "timestamp": 1147060140, + "tags": [ + "hacking", + "python", + "linux", + "fuse", + "linux", + "mediawiki", + "python", + "wikipediafs" + ], + "author": "sjs", + "url": "/posts/2006.05.07-wikipediafs-on-linux-in-python" + }, + "2006.06.05-ich-bin-auslnder-und-spreche-nicht-gut-deutsch": { + "title": "Ich bin Ausländer und spreche nicht gut Deutsch", + "date": "June 5, 2006", + "timestamp": 1149527460, + "tags": [ + "life", + "munich", + "seekport", + "work" + ], + "author": "sjs", + "url": "/posts/2006.06.05-ich-bin-auslnder-und-spreche-nicht-gut-deutsch" + }, + "2006.06.09-never-buy-a-german-keyboard": { + "title": "Never buy a German keyboard!", + "date": "June 9, 2006", + "timestamp": 1149841020, + "tags": [ + "apple", + "apple", + "german", + "keyboard" + ], + "author": "sjs", + "url": "/posts/2006.06.09-never-buy-a-german-keyboard" + }, + "2006.06.10-theres-nothing-regular-about-regular-expressions": { + "title": "There's nothing regular about regular expressions", + "date": "June 10, 2006", + "timestamp": 1149928080, + "tags": [ + "technology", + "book", + "regex" + ], + "author": "sjs", + "url": "/posts/2006.06.10-theres-nothing-regular-about-regular-expressions" + }, + "2006.06.11-apple-pays-attention-to-detail": { + "title": "Apple pays attention to detail", + "date": "June 11, 2006", + "timestamp": 1150014600, + "tags": [ + "technology", + "mac os x", + "apple" + ], + "author": "sjs", + "url": "/posts/2006.06.11-apple-pays-attention-to-detail" + }, + "2006.07.06-working-with-the-zend-framework": { + "title": "Working with the Zend Framework", + "date": "July 6, 2006", + "timestamp": 1152196560, + "tags": [ + "coding", + "technology", + "php", + "framework", + "php", + "seekport", + "zend" + ], + "author": "sjs", + "url": "/posts/2006.07.06-working-with-the-zend-framework" + }, + "2006.07.13-ubuntu-linux-for-linux-users-please": { + "title": "Ubuntu: Linux for Linux users please", + "date": "July 13, 2006", + "timestamp": 1152804840, + "tags": [ + "linux", + "linux", + "ubuntu" + ], + "author": "sjs", + "url": "/posts/2006.07.13-ubuntu-linux-for-linux-users-please" + }, + "2006.07.17-ruby-and-rails-have-spoiled-me-rotten": { + "title": "Ruby and Rails have spoiled me rotten", + "date": "July 17, 2006", + "timestamp": 1153140000, + "tags": [ + "rails", + "ruby", + "php", + "coding", + "framework", + "php", + "rails", + "ruby", + "zend" + ], + "author": "sjs", + "url": "/posts/2006.07.17-ruby-and-rails-have-spoiled-me-rotten" + }, + "2006.07.19-late-static-binding": { + "title": "Late static binding", + "date": "July 19, 2006", + "timestamp": 1153329780, + "tags": [ + "php", + "coding", + "coding", + "php" + ], + "author": "sjs", + "url": "/posts/2006.07.19-late-static-binding" + }, + "2006.07.21-class-method-instance-method-it-doesnt-matter-to-php": { + "title": "Class method? Instance method? It doesn't matter to PHP", + "date": "July 21, 2006", + "timestamp": 1153493760, + "tags": [ + "php", + "coding" + ], + "author": "sjs", + "url": "/posts/2006.07.21-class-method-instance-method-it-doesnt-matter-to-php" + }, + "2006.08.22-where-are-my-headphones": { + "title": "Where are my headphones?", + "date": "August 22, 2006", + "timestamp": 1156257060, + "tags": [ + "life", + "seekport" + ], + "author": "sjs", + "url": "/posts/2006.08.22-where-are-my-headphones" + }, + "2006.09.16-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo": { + "title": "Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo", + "date": "September 16, 2006", + "timestamp": 1158469860, + "tags": [ + "amusement", + "buffalo" + ], + "author": "sjs", + "url": "/posts/2006.09.16-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo" + }, + "2006.09.22-some-features-you-might-have-missed-in-itunes-7": { + "title": "Some features you might have missed in iTunes 7", + "date": "September 22, 2006", + "timestamp": 1158969540, + "tags": [ + "apple", + "apple", + "itunes" + ], + "author": "sjs", + "url": "/posts/2006.09.22-some-features-you-might-have-missed-in-itunes-7" + }, + "2006.12.17-coping-with-windows-xp-activiation-on-a-mac": { + "title": "Coping with Windows XP activiation on a Mac", + "date": "December 17, 2006", + "timestamp": 1166427000, + "tags": [ + "parallels", + "windows", + "apple", + "mac os x", + "bootcamp" + ], + "author": "sjs", + "url": "/posts/2006.12.17-coping-with-windows-xp-activiation-on-a-mac" + }, + "2007.03.06-full-screen-cover-flow": { + "title": "Full-screen Cover Flow", + "date": "March 6, 2007", + "timestamp": 1173217860, + "tags": [ + "apple", + "coverflow", + "itunes" + ], + "author": "sjs", + "url": "/posts/2007.03.06-full-screen-cover-flow" + }, + "2007.03.08-digg-v4-reply-to-replies-greasemonkey-script": { + "title": "Digg v4: Reply to replies (Greasemonkey script)", + "date": "March 8, 2007", + "timestamp": 1173424740, + "tags": [ + "coding", + "digg", + "firefox", + "userscript" + ], + "author": "sjs", + "url": "/posts/2007.03.08-digg-v4-reply-to-replies-greasemonkey-script" + }, + "2007.03.25-diggscuss-0.9": { + "title": "Diggscuss 0.9", + "date": "March 25, 2007", + "timestamp": 1174834980, + "tags": [ + "coding", + "digg", + "firefox", + "userscript" + ], + "author": "sjs", + "url": "/posts/2007.03.25-diggscuss-0.9" + }, + "2007.04.04-a-triple-booting-schizophrenic-macbook": { + "title": "A triple-booting, schizophrenic MacBook", + "date": "April 4, 2007", + "timestamp": 1175754600, + "tags": [ + "linux", + "mac os x", + "windows" + ], + "author": "sjs", + "url": "/posts/2007.04.04-a-triple-booting-schizophrenic-macbook" + }, + "2007.04.11-activerecord-base.find_or_create-and-find_or_initialize": { + "title": "ActiveRecord::Base.find_or_create and find_or_initialize", + "date": "April 11, 2007", + "timestamp": 1176287040, + "tags": [ + "activerecord", + "coding", + "rails", + "ruby" + ], + "author": "sjs", + "url": "/posts/2007.04.11-activerecord-base.find_or_create-and-find_or_initialize" + }, + "2007.04.16-getting-to-know-vista": { + "title": "Getting to know Vista", + "date": "April 16, 2007", + "timestamp": 1176746940, + "tags": [ + "windows" + ], + "author": "sjs", + "url": "/posts/2007.04.16-getting-to-know-vista" + }, + "2007.04.26-quickly-inserting-millions-of-rows-with-mysql-innodb": { + "title": "Quickly inserting millions of rows with MySQL/InnoDB", + "date": "April 26, 2007", + "timestamp": 1177596360, + "tags": [ + "linux", + "mysql" + ], + "author": "sjs", + "url": "/posts/2007.04.26-quickly-inserting-millions-of-rows-with-mysql-innodb" + }, + "2007.04.30-funny-how-code-can-be-beautiful": { + "title": "Funny how code can be beautiful", + "date": "April 30, 2007", + "timestamp": 1177942020, + "tags": [ + "haskell" + ], + "author": "sjs", + "url": "/posts/2007.04.30-funny-how-code-can-be-beautiful" + }, + "2007.05.01-typo-and-i-are-friends-again": { + "title": "Typo and I are friends again", + "date": "May 1, 2007", + "timestamp": 1178081497, + "tags": [ + "typo" + ], + "author": "sjs", + "url": "/posts/2007.05.01-typo-and-i-are-friends-again" + }, + "2007.05.03-a-scheme-parser-in-haskell-part-1": { + "title": "A Scheme parser in Haskell: Part 1", + "date": "May 3, 2007", + "timestamp": 1178178470, + "tags": [ + "coding", + "haskell" + ], + "author": "sjs", + "url": "/posts/2007.05.03-a-scheme-parser-in-haskell-part-1" + }, + "2007.05.05-gotta-love-the-ferry-ride": { + "title": "Gotta Love the Ferry Ride", + "date": "May 5, 2007", + "timestamp": 1178364300, + "tags": [ + "life", + "photo", + "bc", + "victoria" + ], + "author": "sjs", + "url": "/posts/2007.05.05-gotta-love-the-ferry-ride" + }, + "2007.05.05-a-new-way-to-look-at-networking": { + "title": "A New Way to Look at Networking", + "date": "May 5, 2007", + "timestamp": 1178406600, + "tags": [ + "technology", + "networking" + ], + "author": "sjs", + "url": "/posts/2007.05.05-a-new-way-to-look-at-networking" + }, + "2007.05.09-dtrace-ruby-goodness-for-sun": { + "title": "dtrace + Ruby = Goodness for Sun", + "date": "May 9, 2007", + "timestamp": 1178725500, + "tags": [ + "ruby", + "dtrace", + "sun" + ], + "author": "sjs", + "url": "/posts/2007.05.09-dtrace-ruby-goodness-for-sun" + }, + "2007.05.09-i-cant-wait-to-see-what-matt-stone-trey-parker-do-with-this": { + "title": "I Can't Wait to See What Trey Parker & Matt Stone Do With This", + "date": "May 9, 2007", + "timestamp": 1178746440, + "tags": [ + "crazy" + ], + "author": "sjs", + "url": "/posts/2007.05.09-i-cant-wait-to-see-what-matt-stone-trey-parker-do-with-this" + }, + "2007.05.10-rails-plugins-link-dump": { + "title": "Rails Plugins (link dump)", + "date": "May 10, 2007", + "timestamp": 1178756520, + "tags": [ + "rails" + ], + "author": "sjs", + "url": "/posts/2007.05.10-rails-plugins-link-dump" + }, + "2007.05.10-enumerable-pluck-and-string-to_proc-for-ruby": { + "title": "Enumurable#pluck and String#to_proc for Ruby", + "date": "May 10, 2007", + "timestamp": 1178838840, + "tags": [ + "ruby", + "extensions" + ], + "author": "sjs", + "url": "/posts/2007.05.10-enumerable-pluck-and-string-to_proc-for-ruby" + }, + "2007.05.15-dumping-objects-to-the-browser-in-rails": { + "title": "Dumping Objects to the Browser in Rails", + "date": "May 15, 2007", + "timestamp": 1179261480, + "tags": [ + "rails" + ], + "author": "sjs", + "url": "/posts/2007.05.15-dumping-objects-to-the-browser-in-rails" + }, + "2007.05.16-cheating-at-life-in-general": { + "title": "Cheating at Life in General", + "date": "May 16, 2007", + "timestamp": 1179308760, + "tags": [ + "cheat", + "vim", + "emacs", + "textmate" + ], + "author": "sjs", + "url": "/posts/2007.05.16-cheating-at-life-in-general" + }, + "2007.05.18-iphone-humour": { + "title": "iPhone Humour", + "date": "May 18, 2007", + "timestamp": 1179513240, + "tags": [ + "apple", + "funny", + "iphone" + ], + "author": "sjs", + "url": "/posts/2007.05.18-iphone-humour" + }, + "2007.05.22-inspirado": { + "title": "Inspirado", + "date": "May 22, 2007", + "timestamp": 1179865380, + "tags": [ + "rails", + "inspirado" + ], + "author": "sjs", + "url": "/posts/2007.05.22-inspirado" + }, + "2007.05.26-finnish-court-rules-css-ineffective-at-protecting-dvds": { + "title": "Finnish court rules CSS ineffective at protecting DVDs", + "date": "May 26, 2007", + "timestamp": 1180175040, + "tags": [ + "drm" + ], + "author": "sjs", + "url": "/posts/2007.05.26-finnish-court-rules-css-ineffective-at-protecting-dvds" + }, + "2007.06.08-301-moved-permanently": { + "title": "301 moved permanently", + "date": "June 8, 2007", + "timestamp": 1181350800, + "tags": [ + "life" + ], + "author": "sjs", + "url": "/posts/2007.06.08-301-moved-permanently" + }, + "2007.06.08-so-long-typo-and-thanks-for-all-the-timeouts": { + "title": "so long typo (and thanks for all the timeouts)", + "date": "June 8, 2007", + "timestamp": 1181350860, + "tags": [ + "mephisto", + "typo" + ], + "author": "sjs", + "url": "/posts/2007.06.08-so-long-typo-and-thanks-for-all-the-timeouts" + }, + "2007.06.14-more-scheming-with-haskell": { + "title": "More Scheming with Haskell", + "date": "June 14, 2007", + "timestamp": 1181783340, + "tags": [ + "coding", + "haskell", + "scheme" + ], + "author": "sjs", + "url": "/posts/2007.06.14-more-scheming-with-haskell" + }, + "2007.06.14-testspec-on-rails-declared-awesome-just-one-catch": { + "title": "test/spec on rails declared awesome, just one catch", + "date": "June 14, 2007", + "timestamp": 1181830860, + "tags": [ + "bdd", + "rails", + "test/spec" + ], + "author": "sjs", + "url": "/posts/2007.06.14-testspec-on-rails-declared-awesome-just-one-catch" + }, + "2007.06.15-begging-the-question": { + "title": "Begging the question", + "date": "June 15, 2007", + "timestamp": 1181933340, + "tags": [ + "english", + "life", + "pedantry" + ], + "author": "sjs", + "url": "/posts/2007.06.15-begging-the-question" + }, + "2007.06.18-back-on-gentoo-trying-new-things": { + "title": "Back on Gentoo, trying new things", + "date": "June 18, 2007", + "timestamp": 1182215100, + "tags": [ + "emacs", + "gentoo", + "linux", + "vim" + ], + "author": "sjs", + "url": "/posts/2007.06.18-back-on-gentoo-trying-new-things" + }, + "2007.06.20-reinventing-the-wheel": { + "title": "Reinventing the wheel", + "date": "June 20, 2007", + "timestamp": 1182356820, + "tags": [ + "emacs", + "snippets" + ], + "author": "sjs", + "url": "/posts/2007.06.20-reinventing-the-wheel" + }, + "2007.06.22-embrace-the-database": { + "title": "Embrace the database", + "date": "June 22, 2007", + "timestamp": 1182507240, + "tags": [ + "activerecord", + "rails", + "ruby" + ], + "author": "sjs", + "url": "/posts/2007.06.22-embrace-the-database" + }, + "2007.06.23-emacs-for-textmate-junkies": { + "title": "Emacs for TextMate junkies", + "date": "June 23, 2007", + "timestamp": 1182565020, + "tags": [ + "emacs", + "textmate" + ], + "author": "sjs", + "url": "/posts/2007.06.23-emacs-for-textmate-junkies" + }, + "2007.06.24-floating-point-in-elschemo": { + "title": "Floating point in ElSchemo", + "date": "June 24, 2007", + "timestamp": 1182711180, + "tags": [ + "elschemo", + "haskell", + "scheme" + ], + "author": "sjs", + "url": "/posts/2007.06.24-floating-point-in-elschemo" + }, + "2007.06.25-propaganda-makes-me-sick": { + "title": "Propaganda makes me sick", + "date": "June 25, 2007", + "timestamp": 1182768900, + "tags": [ + "propaganda" + ], + "author": "sjs", + "url": "/posts/2007.06.25-propaganda-makes-me-sick" + }, + "2007.06.26-rtfm": { + "title": "RTFM!", + "date": "June 26, 2007", + "timestamp": 1182806340, + "tags": [ + "emacs", + "rtfm" + ], + "author": "sjs", + "url": "/posts/2007.06.26-rtfm" + }, + "2007.06.25-emacs-tagify-region-or-insert-tag": { + "title": "Emacs: tagify-region-or-insert-tag", + "date": "June 25, 2007", + "timestamp": 1182809580, + "tags": [ + "emacs", + "tagify" + ], + "author": "sjs", + "url": "/posts/2007.06.25-emacs-tagify-region-or-insert-tag" + }, + "2007.06.28-recent-ruby-and-rails-regales": { + "title": "Recent Ruby and Rails Regales", + "date": "June 28, 2007", + "timestamp": 1183058580, + "tags": [ + "rails", + "rails on rules", + "regular expressions", + "ruby", + "sake", + "secure associations", + "regex" + ], + "author": "sjs", + "url": "/posts/2007.06.28-recent-ruby-and-rails-regales" + }, + "2007.06.30-controlling-volume-via-the-keyboard-on-linux": { + "title": "Controlling volume via the keyboard on Linux", + "date": "June 30, 2007", + "timestamp": 1183245180, + "tags": [ + "alsa", + "linux", + "ruby", + "volume" + ], + "author": "sjs", + "url": "/posts/2007.06.30-controlling-volume-via-the-keyboard-on-linux" + }, + "2007.07.03-a-textmate-tip-for-emacs-users": { + "title": "A TextMate tip for Emacs users", + "date": "July 3, 2007", + "timestamp": 1183481100, + "tags": [ + "emacs", + "keyboard shortcuts", + "textmate" + ], + "author": "sjs", + "url": "/posts/2007.07.03-a-textmate-tip-for-emacs-users" + }, + "2007.07.05-rushcheck-quickcheck-for-ruby": { + "title": "RushCheck: QuickCheck for Ruby", + "date": "July 5, 2007", + "timestamp": 1183665000, + "tags": [ + "quickcheck", + "ruby", + "rushcheck" + ], + "author": "sjs", + "url": "/posts/2007.07.05-rushcheck-quickcheck-for-ruby" + }, + "2007.07.06-see-your-regular-expressions-in-emacs": { + "title": "See your regular expressions in Emacs", + "date": "July 6, 2007", + "timestamp": 1183740300, + "tags": [ + "emacs", + "regex" + ], + "author": "sjs", + "url": "/posts/2007.07.06-see-your-regular-expressions-in-emacs" + }, + "2007.07.12-people": { + "title": "people", + "date": "July 12, 2007", + "timestamp": 1184243280, + "tags": [ + "life", + "people" + ], + "author": "sjs", + "url": "/posts/2007.07.12-people" + }, + "2007.08.02-elschemo-boolean-logic-and-branching": { + "title": "ElSchemo: Boolean logic and branching", + "date": "August 2, 2007", + "timestamp": 1186073940, + "tags": [ + "elschemo", + "haskell", + "scheme" + ], + "author": "sjs", + "url": "/posts/2007.08.02-elschemo-boolean-logic-and-branching" + }, + "2007.08.09-snap-crunchle-pop": { + "title": "Snap, crunchle, pop", + "date": "August 9, 2007", + "timestamp": 1186654620, + "tags": [ + "humans", + "injury", + "life" + ], + "author": "sjs", + "url": "/posts/2007.08.09-snap-crunchle-pop" + }, + "2007.08.09-cheat-from-emacs": { + "title": "Cheat from Emacs", + "date": "August 9, 2007", + "timestamp": 1186710960, + "tags": [ + "Emacs" + ], + "author": "sjs", + "url": "/posts/2007.08.09-cheat-from-emacs" + }, + "2007.08.11-opera-is-pretty-slick": { + "title": "Opera is pretty slick", + "date": "August 11, 2007", + "timestamp": 1186834260, + "tags": [ + "browsers", + "firefox", + "opera" + ], + "author": "sjs", + "url": "/posts/2007.08.11-opera-is-pretty-slick" + }, + "2007.08.19-catch-compiler-errors-at-runtime": { + "title": "Catch compiler errors at runtime", + "date": "August 19, 2007", + "timestamp": 1187561820, + "tags": [ + "ruby" + ], + "author": "sjs", + "url": "/posts/2007.08.19-catch-compiler-errors-at-runtime" + }, + "2007.08.21-cheat-productively-in-emacs": { + "title": "Cheat productively in Emacs", + "date": "August 21, 2007", + "timestamp": 1187720400, + "tags": [ + "Emacs" + ], + "author": "sjs", + "url": "/posts/2007.08.21-cheat-productively-in-emacs" + }, + "2007.08.26-captivating-little-creatures": { + "title": "Captivating little creatures", + "date": "August 26, 2007", + "timestamp": 1188131700, + "tags": [ + "games", + "lemmings" + ], + "author": "sjs", + "url": "/posts/2007.08.26-captivating-little-creatures" + }, + "2007.08.30-5-ways-to-avoid-looking-like-a-jerk-on-the-internet": { + "title": "5 ways to avoid looking like a jerk on the Internet", + "date": "August 30, 2007", + "timestamp": 1188487500, + "tags": [ + "life", + "netiquette" + ], + "author": "sjs", + "url": "/posts/2007.08.30-5-ways-to-avoid-looking-like-a-jerk-on-the-internet" + }, + "2007.09.25-learning-lisp-read-pcl": { + "title": "Learning Lisp? Read PCL", + "date": "September 25, 2007", + "timestamp": 1190714340, + "tags": [ + "lisp" + ], + "author": "sjs", + "url": "/posts/2007.09.25-learning-lisp-read-pcl" + }, + "2007.09.26-python-and-ruby-brain-dump": { + "title": "Python and Ruby brain dump", + "date": "September 26, 2007", + "timestamp": 1190802840, + "tags": [ + "python", + "ruby" + ], + "author": "sjs", + "url": "/posts/2007.09.26-python-and-ruby-brain-dump" + }, + "2007.10.29-gtkpod-in-gutsy-got-you-groaning": { + "title": "Gtkpod in Gutsy Got You Groaning?", + "date": "October 29, 2007", + "timestamp": 1193692440, + "tags": [ + "broken", + "gtkpod", + "linux", + "ubuntu" + ], + "author": "sjs", + "url": "/posts/2007.10.29-gtkpod-in-gutsy-got-you-groaning" + }, + "2008.01.07-random-pet-peeve-of-the-day": { + "title": "Random pet peeve of the day", + "date": "January 7, 2008", + "timestamp": 1199727720, + "tags": [ + "usability", + "web" + ], + "author": "sjs", + "url": "/posts/2008.01.07-random-pet-peeve-of-the-day" + }, + "2008.02.19-thoughts-on-arc": { + "title": "Thoughts on Arc", + "date": "February 19, 2008", + "timestamp": 1203420360, + "tags": [ + "lisp arc" + ], + "author": "sjs", + "url": "/posts/2008.02.19-thoughts-on-arc" + }, + "2008.03.03-project-euler-code-repo-in-arc": { + "title": "Project Euler code repo in Arc", + "date": "March 3, 2008", + "timestamp": 1204561440, + "tags": [ + "arc", + "project euler" + ], + "author": "sjs", + "url": "/posts/2008.03.03-project-euler-code-repo-in-arc" + }, + "2009.11.21-using-emacs-to-develop-mojo-apps-for-webos": { + "title": "Using Emacs to Develop Mojo Apps for WebOS", + "date": "November 21, 2009", + "timestamp": 1258790400, + "tags": [ + "emacs", + "mojo", + "webos", + "lisp", + "javascript" + ], + "author": "sjs", + "url": "/posts/2009.11.21-using-emacs-to-develop-mojo-apps-for-webos" + }, + "2010.01.17-working-with-c-style-structs-in-ruby": { + "title": "Working with C-style structs in Ruby", + "date": "January 17, 2010", + "timestamp": 1263715200, + "tags": [ + "ruby", + "cstruct", + "compiler" + ], + "author": "sjs", + "url": "/posts/2010.01.17-working-with-c-style-structs-in-ruby" + }, + "2010.01.18-basics-of-the-mach-o-file-format": { + "title": "Basics of the Mach-O file format", + "date": "January 18, 2010", + "timestamp": 1263801600, + "tags": [ + "mach-o", + "os x", + "compiler" + ], + "author": "sjs", + "url": "/posts/2010.01.18-basics-of-the-mach-o-file-format" + }, + "2010.01.20-a-preview-of-mach-o-file-generation": { + "title": "A preview of Mach-O file generation", + "date": "January 20, 2010", + "timestamp": 1263974400, + "tags": [ + "ruby", + "mach-o", + "os x", + "compiler" + ], + "author": "sjs", + "url": "/posts/2010.01.20-a-preview-of-mach-o-file-generation" + }, + "2010.11.04-37signals-chalk-dissected": { + "title": "37signals' Chalk Dissected", + "date": "November 4, 2010", + "timestamp": 1288854000, + "tags": [ + "37signals", + "chalk", + "ipad", + "javascript", + "web", + "html", + "css", + "zepto.js" + ], + "author": "sjs", + "url": "/posts/2010.11.04-37signals-chalk-dissected" + }, + "2011.11.27-recovering-old-posts": { + "title": "Recovering Old Blog Posts", + "date": "November 27, 2011", + "timestamp": 1322385300, + "tags": [ + "recover", + "old", + "blog", + "posts" + ], + "author": "sjs", + "url": "/posts/2011.11.27-recovering-old-posts" + }, + "2011.11.27-lights": { + "title": "Lights →", + "date": "November 27, 2011", + "timestamp": 1322446260, + "tags": [ + + ], + "url": "/posts/2011.11.27-lights", + "link": "http://lights.elliegoulding.com/" + }, + "2011.12.10-static-url-shortener-using-htaccess": { + "title": "A Static URL Shortener Using .htaccess", + "date": "December 10, 2011", + "timestamp": 1323584949, + "tags": [ + "s42.ca", + "url", + "shortener", + "samhuri.net", + "url shortener" + ], + "author": "sjs", + "url": "/posts/2011.12.10-static-url-shortener-using-htaccess" + }, + "2011.12.11-pure-css3-images-hmm-maybe-later": { + "title": "Pure CSS3 images? Hmm, maybe later →", + "date": "December 11, 2011", + "timestamp": 1323635103, + "tags": [ + + ], + "url": "/posts/2011.12.11-pure-css3-images-hmm-maybe-later", + "link": "http://calendar.perfplanet.com/2011/pure-css3-images-hmm-maybe-later/" + }, + "2011.12.15-i-see-http": { + "title": "I see HTTP →", + "date": "December 15, 2011", + "timestamp": 1323964035, + "tags": [ + + ], + "url": "/posts/2011.12.15-i-see-http", + "link": "http://calendar.perfplanet.com/2011/i-see-http/" + }, + "2011.12.19-my-kind-of-feature-checklist": { + "title": "My kind of feature checklist →", + "date": "December 19, 2011", + "timestamp": 1324354805, + "tags": [ + + ], + "url": "/posts/2011.12.19-my-kind-of-feature-checklist", + "link": "http://www.marco.org/2011/12/19/amazon-kindle-vs-ipad" + }, + "2011.12.22-new-release-of-firefox-for-android-optimized-for-tablets": { + "title": "New Release of Firefox for Android, Optimized for Tablets →", + "date": "December 22, 2011", + "timestamp": 1324868051, + "tags": [ + + ], + "url": "/posts/2011.12.22-new-release-of-firefox-for-android-optimized-for-tablets", + "link": "http://daringfireball.net/linked/2011/12/22/firefox-android" + }, + "2011.12.25-the-broken-pixel-theory": { + "title": "The Broken Pixel Theory →", + "date": "December 25, 2011", + "timestamp": 1324868060, + "tags": [ + + ], + "url": "/posts/2011.12.25-the-broken-pixel-theory", + "link": "http://jtaby.com/2011/12/25/the-broken-pixel-theory.html" + }, + "2012.01.04-yak-shaving": { + "title": "Yak shaving →", + "date": "January 4, 2012", + "timestamp": 1325712240, + "tags": [ + + ], + "url": "/posts/2012.01.04-yak-shaving", + "link": "http://blog.hasmanythrough.com/2012/1/4/yak-shaving" + }, + "2012.01.09-the-40-standup-desk": { + "title": "The $40 Standup Desk →", + "date": "January 9, 2012", + "timestamp": 1326097000, + "tags": [ + + ], + "url": "/posts/2012.01.09-the-40-standup-desk", + "link": "http://opensoul.org/blog/archives/2012/01/09/the-40-standup-desk/" + }, + "2012.01.17-recovering-from-a-computer-science-education": { + "title": "Recovering From a Computer Science Education →", + "date": "January 17, 2012", + "timestamp": 1326787200, + "tags": [ + + ], + "url": "/posts/2012.01.17-recovering-from-a-computer-science-education", + "link": "http://prog21.dadgum.com/123.html" + }, + "2012.01.17-sopa-lives-and-mpaa-calls-protests-an-abuse-of-power": { + "title": "SOPA lives - and MPAA calls protests an \"abuse of power\" →", + "date": "January 17, 2012", + "timestamp": 1326797200, + "tags": [ + + ], + "url": "/posts/2012.01.17-sopa-lives-and-mpaa-calls-protests-an-abuse-of-power", + "link": "http://arstechnica.com/tech-policy/news/2012/01/sopa-livesand-mpaa-calls-protests-an-abuse-of-power.ars" + }, + "2012.01.19-fujitsu-has-lost-their-mind": { + "title": "Fujitsu has lost their mind →", + "date": "January 19, 2012", + "timestamp": 1327032333, + "tags": [ + + ], + "url": "/posts/2012.01.19-fujitsu-has-lost-their-mind", + "link": "http://tablet-news.com/2012/01/17/fujitsu-lifebook-2013-concept-incorporates-a-tablet-for-a-keyboard-phone-and-digital-camera/" + }, + "2013.03.06-zelda-tones-for-ios": { + "title": "Zelda Tones for iOS", + "date": "March 6, 2013", + "timestamp": 1362624673, + "tags": [ + "zelda", + "nintendo", + "pacman", + "ringtones", + "tones", + "ios" + ], + "author": "sjs", + "url": "/posts/2013.03.06-zelda-tones-for-ios" + }, + "2013.09.27-linky": { + "title": "Linky", + "date": "September 27, 2013", + "timestamp": 1380343742, + "tags": [ + "linky", + "north watcher", + "ruby", + "gmail", + "links", + "notifications" + ], + "author": "sjs", + "url": "/posts/2013.09.27-linky" + }, + "2014.02.03-ember-structure": { + "title": "Structure of an Ember app", + "date": "February 3, 2014", + "timestamp": 1391479549, + "tags": [ + "ember.js" + ], + "author": "sjs", + "url": "/posts/2014.02.03-ember-structure" + } +} diff --git a/public/posts/drafts/2011.06.03-the-case-for-native.md b/public/posts/drafts/2011.06.03-the-case-for-native.md new file mode 100644 index 0000000..84da393 --- /dev/null +++ b/public/posts/drafts/2011.06.03-the-case-for-native.md @@ -0,0 +1,83 @@ +Title: The Case For Native +Date: June 3, 2011 +Author: sjs +Tags: titanium, native, mobile, apps, platforms, android, ios +---- + +For the past month I've been using [Appcelerator Titanium](http://www.appcelerator.com/products/) on a two man team. We made a simple iPhone app with a tab bar with embedded nav controllers, just 10 screens or so total. We started porting it to the iPad and Android so have some experience there. It's been a pretty frustrating exercise most days. I had a lot of little complaints but didn't take the time to step back and look at the bigger picture. I love JavaScript and in theory Titanium is awesome and a huge win. I wanted it to be a win but in reality it just hasn't been. + +Here are 9 reasons why native is better in the short and long run. + +### Reliability + +Inserting rows or updating a table view won't make it freeze or crash unless you make a mistake. Titanium is very new, very ambitious, and pretty flaky. A control as vital as the table view should be rock solid at this point. No excuses. + +### Tools + +They're better. For these reasons: + + - Code completing IDEs with integrated documentation, helps with learning. + + *I hate the editors in IDEs - give me TextMate or Emacs please - but few will disagree that Xcode is the best environment for writing Cocoa apps or that IntelliJ IDEA or Eclipse is the best environment for writing Android apps.* + + - Debuggers. Yup, they're useful. + + - Xcode / Interface Builder for iOS, Faster prototyping by using a GUI to build your GUIs. + + *[One more level, we can go deeper.... BRRRAAAAAAUUUUUM](http://youtu.be/d2yD4yDsiP4)* + + - Android has XML layout which is somewhat better than code. Not as a big a win but still a win. Declarative is better than imperative. + +### Faster Development + +Edit-compile-test cycle is incredibly slow when you have to compile 250 - 500 files for Titanium every time you want to test something. If you have a relatively simple and small app it still [takes minutes to compile](http://xkcd.com/303/) it. It's slow, tedious, and unnecessary. + +### Happiness + +Don't underestimate the importance of happiness. Better and more reliable tools plus faster development makes me happier. Waiting minutes to test a change is draining and does not make me happy. Trusting my tools because they are well tested and stable makes me happy. Writing code that should work but doesn't makes me unhappy. Debugging some framework instead of working on my actual tasks makes me unhappy. + +### Documentation + +I rarely need to look at Android source or Cocoa headers. I've had to look at Titanium's source more often. Some of the `Kroll*` classes are hairy. Values are converted to and from `NSDictionary` to JS objects and back again, to and fro between JS and ObjC. Which brings me to... + +### Titanium is a Poor JavaScript Environment + +Many of the ObjC proxy objects, `KrollObject`s, that are exposed as the JS API do not behave like regular JS objects, they are like those the weird host objects you find in a browser environment. If you treat some of these like normal JS objects things go awry or assignments silently have no effect. There's no excuse for that today, we have learned and know better and browsers are changing that stuff as fast as they can. And there's no documentation on these things. You have to find out the hard way or by reading the source. + +Don't get me started on the C-style "*BAM THERE'S YOUR TEXT*" include. Or how behaviour can differ if you pass a variable instead of an object literal to some functions. + +### Libraries + +More. Better. Widely tested. Nuff said. + +### Knowledge + +More help, knowledge, tutorials, and people on IRC, forums, and mailing lists. Titanium wants you to buy support because that's how they make money, so free support is a ghetto. Google and Apple want you to need as little support as possible so the docs are far better to begin with, but when they fall short the sheer number of devs makes free support better as well in places such as StackOverflow. + +### Results and Performance + +Native apps win every time hands down. That's part of the allure of Titanium over, say, PhoneGap. You can't beat native look, feel, and speed. Titanium will never get you the speed, partially because they've not exposed the table view's native methods as bindings in JS so you can't control things at a low level to make it perform well. Or in some cases even work. + +Just look at these iOS apps: + + - [Instapaper](http://itunes.apple.com/us/app/instapaper/id288545208?mt=8%3FpartnerId%3D30) + - [Twitter / Tweetie](http://itunes.apple.com/us/app/twitter/id333903271?mt=8) + - [Gowalla](http://itunes.apple.com/ca/app/gowalla/id304510106?mt=8) + - [Instagram](http://itunes.apple.com/ca/app/instagram/id389801252?mt=8) and [Hipstamatic](http://hipstamaticapp.com/) + +Android ... I don't use many, sadly few are very good: + + - [DoubleTwist](http://www.doubletwist.com/apps/android/doubletwist-player/com.doubleTwist.androidPlayer/) + - [NewsRob](http://www.androlib.com/android.application.com-newsrob-wmq.aspx) + +### Losses + +Negligible. + +Mobile libraries are often just HTTP interfaces to some API with a server doing the heavy lifting. You can't effectively reuse very much UI and mobile apps consist mostly of UI. + +To be effective with Titanium you have to read the source anyway, so either way you need to know how to read ObjC and Java, if not write it. + +### Exceptions + +They exist, sometimes Titanium or PhoneGap is the right solution. I'm a pragmatic guy and believe in using the right tool for the job. If that's Titanium I'll advocate it. In most cases I don't think it is. diff --git a/public/posts/drafts/mach-o-symbol-and-relocation-tables.html b/public/posts/drafts/mach-o-symbol-and-relocation-tables.html new file mode 100644 index 0000000..a34fd4f --- /dev/null +++ b/public/posts/drafts/mach-o-symbol-and-relocation-tables.html @@ -0,0 +1,38 @@ +

    + This post is the last of a triplet on generating basic x86 Mach-O files + with Ruby. The + + first post introduced CStruct, a Ruby class used to serialize + simple struct-like objects, while the + second describes + the + structure of a simple Mach-O file. +

    + + +

    Symbol Tables

    + +

    + + +

    N-List structures

    + +

    + + +

    Load Command

    + +

    + + +

    Relocation Tables

    + +

    + + +

    Putting it all together

    + +As promised I'll show you how to create a very basic Mach-O binary +that you can execute on a machine running OS X (well, any x86 machine +running Darwin but at least 99% of the time that is OS X). + diff --git a/public/projects/_data.json b/public/projects/_data.json new file mode 100644 index 0000000..e75b0a4 --- /dev/null +++ b/public/projects/_data.json @@ -0,0 +1,58 @@ +{ + "strftime": { + "title": "strftime", + "description": "strftime for JavaScript" + }, + "bin": { + "title": "bin", + "description": "~/bin" + }, + "compiler": { + "title": "compiler", + "description": "an x86 compiler written in ruby" + }, + "config": { + "title": "config", + "description": "important dot files (zsh, emacs, vim, screen)" + }, + "format": { + "title": "format", + "description": "printf for JavaScript" + }, + "gitter": { + "title": "gitter", + "description": "a GitHub client for Node (v3 API)" + }, + "samhuri.net": { + "title": "samhuri.net", + "description": "this site" + }, + "ThePusher": { + "title": "ThePusher", + "description": "Github post receive hook router" + }, + "lake": { + "title": "lake", + "description": "A simple implementation of Scheme in C" + }, + "mojo.el": { + "title": "mojo.el", + "description": "turn emacs into a sweet mojo editor" + }, + "NorthWatcher": { + "title": "NorthWatcher", + "description": "cron for filesystem changes" + }, + "batteries": { + "title": "batteries", + "description": "a general purpose node library" + }, + "repl-edit": { + "title": "repl-edit", + "description": "edit Node repl commands with your text editor" + }, + "cheat.el": { + "title": "cheat.el", + "description": "cheat from emacs" + } +} diff --git a/public/projects/_project.ejs b/public/projects/_project.ejs new file mode 100644 index 0000000..e6163f4 --- /dev/null +++ b/public/projects/_project.ejs @@ -0,0 +1,44 @@ + + + Fork me on GitHub +

    <%= title %>

    +

    <%= description %>

    + + + + + + +
    + watchers + + + forks + +
    +
    +
    +

    branches

    + +
    +
    +

    languages

    + +
    +
    +

    contributors

    + +
    +
    +
    + + + + + + diff --git a/public/projects/index.ejs b/public/projects/index.ejs new file mode 100644 index 0000000..ec94079 --- /dev/null +++ b/public/projects/index.ejs @@ -0,0 +1,181 @@ + + + + + projects - samhuri.net + + + + + + + + + + + + +
    +

    samhuri.net

    +
    + + Fork me on GitHub + + + +

    + GitHub +

    + + + + + + + + + + + +
    + + projects + + + + followers + +
    + + gists + + + + following + +
    + + +

    + JS RegExp .lastIndex +

    + + + + + + diff --git a/public/projects/strftime.ejs b/public/projects/strftime.ejs new file mode 100644 index 0000000..68d64e5 --- /dev/null +++ b/public/projects/strftime.ejs @@ -0,0 +1 @@ +<%- partial('_project') %> diff --git a/public/s42/.gitkeep b/public/s42/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/public/sjs.rss b/public/sjs.rss new file mode 100644 index 0000000..11f5182 --- /dev/null +++ b/public/sjs.rss @@ -0,0 +1,265 @@ +samhuri.networds mean thingshttp://samhuri.netMon, 03 Feb 2014 18:05:49 -0800Structure of an Ember app<div id="article"> + <p class="time">February 3, 2014</p> + <p>I made a diagram of an Ember app. There&rsquo;s <a href="http://discuss.emberjs.com/t/diagram-of-an-ember-apps-structure/4060">a discussion about it</a> on the +<a href="http://discuss.emberjs.com/">Ember Discussion Forum</a>. Here is the source file, created with OmniGraffle: <a href="https://www.dropbox.com/s/onnmn1oq096hv5f/Ember%20structure.graffle">Ember structure.graffle</a></p> + +<p><img src="/f/ember-structure.png" alt="Structure of an Ember app" /></p> + +</div> +Mon, 03 Feb 2014 18:05:49 -0800sjshttp://samhuri.net/posts/2014.02.03-ember-structurehttp://samhuri.net/posts/2014.02.03-ember-structureLinky<div id="article"> + <p class="time">September 27, 2013</p> + <h2>Send links from mobile devices to your computers.</h2> + +<p>The last few months I&rsquo;ve been annoyed by my workflow for sending links from my touch devices to my computers. For example if I come across a cool Mac app or an open source project I want to check out, or anything along those lines. Until now I have been mailing links to my work or home addresses, or saving links in Instapaper. The problem with both of those is the same: I have to remember to check something when I arrive at the correct machine. It sounds trivial but I have been annoyed by it nonetheless.</p> + +<p>This weekend I finally decided to scratch that itch and ended up writing much less code than I imagined to accomplish it in a perfectly acceptable way. The components are:</p> + +<ul> +<li><a href="https://mail.google.com">Gmail</a></li> +<li><a href="http://ifttt.com">IFTTT (If This Then That)</a></li> +<li><a href="https://dropbox.com">DropBox</a></li> +<li><a href="https://github.com/samsonjs/NorthWatcher">NorthWatcher</a></li> +<li><a href="https://github.com/samsonjs/bin/blob/master/linky-notify">a (short) Ruby program</a></li> +<li><a href="https://github.com/alloy/terminal-notifier">terminal-notifier</a> (which displays <a href="http://support.apple.com/kb/HT5362">native notifications in OS X</a>)</li> +</ul> + + +<p>Yup, that is a lot of moving parts. It is rather elegant in a <a href="http://www.catb.org/~esr/writings/taoup/">Unixy way</a> though.</p> + +<p><em>I experimented with Gmail &rarr; IFTTT &rarr; <a href="http://boxcar.io">Boxcar</a> &rarr; <a href="http://growl.info/">Growl</a>, but Boxcar&rsquo;s Mac app is really rough and didn&rsquo;t seem to pick up new messages at all, let alone quickly, so I fell back to a solution with more parts.</em></p> + +<h3>Gmail</h3> + +<p><a href="https://mail.google.com">Gmail</a> allows you to append extra info to your email address in the username, which you can use for filtering and labeling. I send links to sami.samhuri+linky@gmail.com and then filter those messages out of my inbox, as well as applying the label <em>linky</em>. Using email as the entry point means that basically every app I use already supports sending links in this way.</p> + +<h3>IFTTT</h3> + +<p><a href="http://ifttt.com">IFTTT (If This Then That)</a> can wire up services, so that events that happen in one place can trigger an action elsewhere, passing along some info about the event along with it. In this case when a new email arrives in my Gmail account with the label <em>linky</em> then I create a text file in Dropbox that contains two lines: the title, followed by the link itself.</p> + +<p>For example, the following lines would be created in a file at <code>~/Dropbox/Linky/Ruxton/&lt;generated filename&gt;.txt</code> for my machine named <a href="http://en.wikipedia.org/wiki/Ruxton_Island">Ruxton</a>.</p> + +<pre><code>Callbacks as our Generations' Go To Statement +http://tirania.org/blog/archive/2013/Aug-15.html +</code></pre> + +<p>The filename field is defined as:</p> + +<pre><code>{FromAddress}-{ReceivedAt} +</code></pre> + +<p>And the content is:</p> + +<pre><code>{Subject}&lt;br&gt; +{BodyPlain}&lt;br&gt; +</code></pre> + +<p>That means that when you email links, the subject should contain the title and the body should contain the link on the first line. It&rsquo;s ok if there&rsquo;s stuff after the body (like your signature), they will be ignored later.</p> + +<p>I create one recipe in IFTTT for each machine that I want links to appear on. You could get fancy and have different Gmail labels for individual machines, or aliases, groups, etc. I&rsquo;ve kept it simple and just have every link I send go to both my home &amp; work computers.</p> + +<h3>Dropbox</h3> + +<p>Dropbox is fantastic. My files are <a href="http://5by5.tv/b2w/37">never not everywhere</a>. IFTTT creates the file in Dropbox, and then Dropbox makes sure it hits all of my machines. Did I mention that Dropbox is awesome? It&rsquo;s awesome.</p> + +<h3>NorthWatcher</h3> + +<p>This is a quick and dirty thing I whipped up a couple of years ago, and now it&rsquo;s come in handy again. It&rsquo;s a program that watches directories for added and removed files, and then launches a program that can then react to the change. In this case, on each machine I want notifications on, I have it watch the Dropbox folder where IFTTT creates the text files. e.g. <code>~/Dropbox/Linky/Ruxton</code></p> + +<p>It has a text configuration file kind of like <a href="http://en.wikipedia.org/wiki/Cron">cron</a>. Here&rsquo;s mine from Ruxton:</p> + +<pre><code>+ Dropbox/Linky/Ruxton ruby /Users/sjs/bin/linky-notify +</code></pre> + +<p>That tells NorthWatcher to run <code>ruby /Users/sjs/bin/linky-notify</code> when files are added to the directory <code>~/Dropbox/Linky/Ruxton</code>.</p> + +<p><em><a href="https://github.com/samsonjs/NorthWatcher">NorthWatcher is on GitHub</a> and <a href="https://npmjs.org">npm</a>. Install <a href="http://nodejs.org">node</a> and then run <code>npm install -g northwatcher</code>. After creating the config file at <code>~/.northwatcher</code> you can run it automatically using <a href="https://gist.github.com/samsonjs/6657795">this launchd config file</a>. Drop that in <code>~/Library/LaunchAgents/net.samhuri.northwatcher.plist</code>. Don&rsquo;t forget to update the working directory path, and run <code>launchctl load ~/Library/LaunchAgents/net.samhuri.northwatcher.plist</code> to load it up (afterwards it will load on boot).</em></p> + +<h3>A Ruby program, and terminal-notifier</h3> + +<p>Finally, we have the last two components of the system. A <a href="https://github.com/samsonjs/bin/blob/master/linky-notify">short Ruby program (<code>/Users/sjs/bin/linky-notify</code>)</a> that reads in all the files NorthWatcher reports as added, and uses <code>terminal-notifier</code> to show a native OS X notification for each link. After displaying the notification it moves the text file into a subfolder named <code>Archive</code>, so I have a record of all the links I have sent myself.</p> + +<p>You can get <code>terminal-notifier</code> with <a href="http://brew.sh">homebrew</a> in a few seconds: <code>brew install terminal-notifier</code>. After you have used <code>terminal-notifier</code> you will be able to go into <em>Notifications</em> in <em>System Preferences</em> and change it from <em>Banners</em> to <em>Alerts</em>. <em>Banners</em> are transient, while <em>Alerts</em> are persistent and have action buttons: <code>Show</code> and <code>Close</code>.</p> + +<h2>Cool story, bro</h2> + +<p>It may not be exciting, but as someone who typically suffers from <a href="http://en.wikipedia.org/wiki/Not_invented_here">NIH syndrome</a> and writes too much from scratch, I found it pretty rewarding to cobble something seemingly complicated together with a bunch of existing components. It didn&rsquo;t take very long and only involved about 10 lines of code. It&rsquo;s not exactly what I wanted but it&rsquo;s surprisingly close. Success!</p> + +</div> +Fri, 27 Sep 2013 21:49:02 -0700sjshttp://samhuri.net/posts/2013.09.27-linkyhttp://samhuri.net/posts/2013.09.27-linkyZelda Tones for iOS<div id="article"> + <p class="time">March 6, 2013</p> + <h2>Zelda</h2> + + + + +<p> + <a href="http://mattgemmell.com">Matt Gemmell</a> recently shared some + <a href="http://mattgemmell.com/2013/03/05/iphone-5-super-nintendo-wallpapers/">sweet Super Nintendo wallpapers for iPhone 5</a>. + Although I don't have an iPhone 5 I was happy to snap them up and crop them for my 4S. +</p> + + + + +<p> + If you like that sort of thing then you might want these tones that I whipped up. The first pack is a few Zelda + ringtones along with a few more SMS tones. Most of them are from + <a href="http://en.wikipedia.org/wiki/The_Legend_of_Zelda:_A_Link_to_the_Past">A Link to the Past</a>. +</p> + + + + +<p align="center"><a href="/f/zelda-tones.zip">Get the Zelda tones</a></p> + + + + +<ul> + <li><audio controls><source src="/f/zelda-tones/Zelda Theme.mp3" type="audio/mpeg"></audio> Theme</li> + <li><audio controls><source src="/f/zelda-tones/Zelda Overture.mp3" type="audio/mpeg"></audio> Overworld overture</li> + <li><audio controls><source src="/f/zelda-tones/Zelda Song of Storms.mp3" type="audio/mpeg"></audio> Song of Storms</li> + <li><audio controls><source src="/f/zelda-tones/Zelda Secret.mp3" type="audio/mpeg"></audio> Secret</li> + <li><audio controls><source src="/f/zelda-tones/Zelda Item.mp3" type="audio/mpeg"></audio> Item</li> + <li><audio controls><source src="/f/zelda-tones/Zelda Achievement.mp3" type="audio/mpeg"></audio> Achievement</li> +</ul> + + + + +<h2>Pacman</h2> + + + + +<p>The second pack is two Pacman tones.</p> + + +<p align="center"><a href="/f/pacman-tones.zip">Get the Pacman tones</a></p> + + + + +<ul> + <li><audio controls><source src="/f/pacman-tones/Pacman.mp3" type="audio/mpeg"></audio> Pacman starts</li> + <li><audio controls><source src="/f/pacman-tones/Pacman Dies.mp3" type="audio/mpeg"></audio> Pacman dies</li> +</ul> + + + + +<h2>O Fortuna</h2> + + + + +<p> + Okay okay, one last one. + <a href="http://en.wikipedia.org/wiki/O_Fortuna">O Fortuna</a> from + <a href="http://en.wikipedia.org/wiki/Carmina_Burana">Carmina Burana</a>, + composed by <a href="http://en.wikipedia.org/wiki/Carl_Orff">Carl Orff</a>, + performed by the <a href="http://www.lpo.co.uk">London Philharmonic Orchestra</a>. +</p> + + + + +<ul><li><audio controls><source src="/f/Carmina Burana - O Fortuna.mp3" type="audio/mpeg"></audio> O Fortuna</li></ul> + + + + +<p align="center"><a href="/f/Carmina Burana - O Fortuna.m4r">Get the O Fortuna ringtone</a></p> + + + + +<p>Enjoy!</p> + + +</div> +Wed, 06 Mar 2013 18:51:13 -0800sjshttp://samhuri.net/posts/2013.03.06-zelda-tones-for-ioshttp://samhuri.net/posts/2013.03.06-zelda-tones-for-iosFujitsu has lost their mind →<div id="article"> + <p class="time">January 19, 2012</p> + <p>Does this even warrant any comments on why it&rsquo;s already a massive failure? +The many, many drawbacks seem so apparent I cannot believe this escaped +from their drawing board.</p> + + <p><a class="permalink" href="http://samhuri.net/posts/2012.01.19-fujitsu-has-lost-their-mind">&infin;</a></p> +</div> +Thu, 19 Jan 2012 20:05:33 -0800http://tablet-news.com/2012/01/17/fujitsu-lifebook-2013-concept-incorporates-a-tablet-for-a-keyboard-phone-and-digital-camera/http://samhuri.net/posts/2012.01.19-fujitsu-has-lost-their-mindSOPA lives - and MPAA calls protests an "abuse of power" →<div id="article"> + <p class="time">January 17, 2012</p> + <blockquote><p>rather than coming to the table to find solutions to a problem that all +now seem to agree is very real and damaging.</p></blockquote> + +<p>No. All most certainly do <em>not</em> agree.</p> + +<blockquote><p>It is also an abuse of power given the freedoms these companies enjoy in +the marketplace today. It&rsquo;s a dangerous and troubling development when the +platforms that serve as gateways to information intentionally skew the +facts to incite their users in order to further their corporate interests.</p></blockquote> + +<p>This must be a joke. It&rsquo;s a joke, right? Please tell me this joker is +joking. The hypocrisy is too much.</p> + +<blockquote><p>stop the hyperbole and PR stunts and engage in meaningful efforts to +combat piracy.</p></blockquote> + +<p>There is absolutely nothing reasonable that anyone can do to &ldquo;combat +piracy&rdquo;. Digital copies are cheap. Adapt or die.</p> + +<p>The VCR did not kill media industries. Nor the cassette, CD, DVD. Why +should anyone believe that computers and the Internet are going to kill +music and movies?</p> + +<p>If the MPAA displayed even a shred of sanity maybe they would be taken +seriously in their efforts to curb piracy. The biggest problem I can see is +that studies have given us evidence that they are not hurt by it at all. +Their tactic of choice seems to be to loudly decry &ldquo;Nuh-uh! Piracy +<em>does</em> hurt us!&rdquo; and then strong arming everyone worldwide while suing anyone and +everyone. If times are so tough maybe they should cut some of their budgets +for lawyers and lobbyists.</p> + + <p><a class="permalink" href="http://samhuri.net/posts/2012.01.17-sopa-lives-and-mpaa-calls-protests-an-abuse-of-power">&infin;</a></p> +</div> +Tue, 17 Jan 2012 02:46:40 -0800http://arstechnica.com/tech-policy/news/2012/01/sopa-livesand-mpaa-calls-protests-an-abuse-of-power.arshttp://samhuri.net/posts/2012.01.17-sopa-lives-and-mpaa-calls-protests-an-abuse-of-powerRecovering From a Computer Science Education →<div id="article"> + <p class="time">January 17, 2012</p> + <p>Something to keep in mind.</p> + + <p><a class="permalink" href="http://samhuri.net/posts/2012.01.17-recovering-from-a-computer-science-education">&infin;</a></p> +</div> +Tue, 17 Jan 2012 00:00:00 -0800http://prog21.dadgum.com/123.htmlhttp://samhuri.net/posts/2012.01.17-recovering-from-a-computer-science-educationThe $40 Standup Desk →<div id="article"> + <p class="time">January 9, 2012</p> + <blockquote><p>Ultimately, I decided I might as well just do something cheap for now. So I built my own. I had thinking about doing it for a while when my coworker Steve Smith built his desk. After seeing his, I was convinced this was what I wanted to do. It turns out, the cheap option is pretty awesome.</p></blockquote> + +<p>This looks great. Might have to consider it when or if I get a desk.</p> + + <p><a class="permalink" href="http://samhuri.net/posts/2012.01.09-the-40-standup-desk">&infin;</a></p> +</div> +Mon, 09 Jan 2012 00:16:40 -0800http://opensoul.org/blog/archives/2012/01/09/the-40-standup-desk/http://samhuri.net/posts/2012.01.09-the-40-standup-deskYak shaving →<div id="article"> + <p class="time">January 4, 2012</p> + <p>The best plain-english explanation of yak shaving I have seen.</p> + + <p><a class="permalink" href="http://samhuri.net/posts/2012.01.04-yak-shaving">&infin;</a></p> +</div> +Wed, 04 Jan 2012 13:24:00 -0800http://blog.hasmanythrough.com/2012/1/4/yak-shavinghttp://samhuri.net/posts/2012.01.04-yak-shavingThe Broken Pixel Theory →<div id="article"> + <p class="time">December 25, 2011</p> + <blockquote><p>For example, a clean desk tends to stay clean until a piece of paper stays on it for a couple of days. Similarly, I=92m much less likely to care about a 2-3 pixel UI bug when the whole UI is a mess.</p></blockquote> + +<p>Great insight from Majd Taby.</p> + + <p><a class="permalink" href="http://samhuri.net/posts/2011.12.25-the-broken-pixel-theory">&infin;</a></p> +</div> +Sun, 25 Dec 2011 18:54:20 -0800http://jtaby.com/2011/12/25/the-broken-pixel-theory.htmlhttp://samhuri.net/posts/2011.12.25-the-broken-pixel-theoryNew Release of Firefox for Android, Optimized for Tablets →<div id="article"> + <p class="time">December 22, 2011</p> + <blockquote><p>On the other hand, watch this video. Even in Mozilla&rsquo;s own demo &ndash; which presumably puts Firefox for Android in its best light &ndash; doesn&rsquo;t the whole thing look a bit herky-jerky, in terms of touch responsiveness and scrolling smoothness?</p></blockquote> + +<p>Surely they could do better on iOS though. I have faith in the Firefox +team to provide a good experience because they have done so in the +past. Modern versions of Firefox are excellent.</p> + +<p><a href="http://blog.mozilla.com/blog/2011/12/20/new-firefox-for-android-ex=%0Aperience-optimized-for-tablets/">New Release of Firefox for Android, Optimized for +Tablets</a></p> + + <p><a class="permalink" href="http://samhuri.net/posts/2011.12.22-new-release-of-firefox-for-android-optimized-for-tablets">&infin;</a></p> +</div> +Sun, 25 Dec 2011 18:54:11 -0800http://daringfireball.net/linked/2011/12/22/firefox-androidhttp://samhuri.net/posts/2011.12.22-new-release-of-firefox-for-android-optimized-for-tablets diff --git a/samhuri.net.tmproj b/samhuri.net.tmproj deleted file mode 100644 index 046e755..0000000 --- a/samhuri.net.tmproj +++ /dev/null @@ -1,578 +0,0 @@ - - - - - currentDocument - assets/css/mobile.css - documents - - - expanded - - name - samhuri.net - regexFileFilter - !(\.DS_Store|.*\.min\..*|.*\.tmproj)$ - regexFolderFilter - !.*/(\.[^/]*|public/blog|node_modules|CVS|_blog|public/proj|Chalk|json-diff|riak-js|f|node|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$ - sourceDirectory - - - - fileHierarchyDrawerWidth - 200 - metaData - - .gitignore - - caret - - column - 10 - line - 7 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - Gemfile - - caret - - column - 0 - line - 6 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - Makefile - - caret - - column - 0 - line - 33 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - TODO - - caret - - column - 22 - line - 19 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - assets/css/blog.css - - caret - - column - 0 - line - 132 - - firstVisibleColumn - 0 - firstVisibleLine - 108 - - assets/css/mobile.css - - caret - - column - 47 - line - 112 - - firstVisibleColumn - 0 - firstVisibleLine - 62 - - assets/css/proj-common.css - - caret - - column - 90 - line - 6 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - assets/css/proj.css - - caret - - column - 0 - line - 29 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - assets/css/style.css - - caret - - column - 6 - line - 40 - - columnSelection - - firstVisibleColumn - 0 - firstVisibleLine - 13 - selectFrom - - column - 0 - line - 40 - - selectTo - - column - 6 - line - 40 - - - assets/js/blog.js - - caret - - column - 0 - line - 94 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - assets/js/proj.js - - caret - - column - 0 - line - 111 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - assets/js/request.js - - caret - - column - 0 - line - 26 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - assets/js/strftime.js - - caret - - column - 49 - line - 4 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - bin/blog.rb - - caret - - column - 44 - line - 101 - - firstVisibleColumn - 0 - firstVisibleLine - 79 - - bin/combine.sh - - caret - - column - 73 - line - 6 - - columnSelection - - firstVisibleColumn - 0 - firstVisibleLine - 0 - selectFrom - - column - 15 - line - 6 - - selectTo - - column - 73 - line - 6 - - - bin/projects.js - - caret - - column - 42 - line - 49 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - discussd/discussd.js - - caret - - column - 0 - line - 279 - - firstVisibleColumn - 0 - firstVisibleLine - 240 - - discussd/package.json - - caret - - column - 0 - line - 15 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - package.json - - caret - - column - 8 - line - 11 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - projects.json - - caret - - column - 0 - line - 3 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - public/.htaccess - - caret - - column - 21 - line - 0 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - public/discussions.html - - caret - - column - 6 - line - 2 - - columnSelection - - firstVisibleColumn - 0 - firstVisibleLine - 0 - selectFrom - - column - 0 - line - 2 - - selectTo - - column - 6 - line - 2 - - - public/index.html - - caret - - column - 0 - line - 13 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - public/s42/.htaccess - - caret - - column - 0 - line - 93 - - firstVisibleColumn - 0 - firstVisibleLine - 31 - - templates/blog/archive.html - - caret - - column - 64 - line - 19 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - templates/blog/index.html - - caret - - column - 0 - line - 22 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - templates/blog/link.mustache - - caret - - column - 37 - line - 6 - - columnSelection - - firstVisibleColumn - 0 - firstVisibleLine - 0 - selectFrom - - column - 32 - line - 6 - - selectTo - - column - 37 - line - 6 - - - templates/blog/link.rss.html - - caret - - column - 9 - line - 3 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - templates/blog/post.html - - caret - - column - 0 - line - 32 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - templates/blog/post.mustache - - caret - - column - 31 - line - 2 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - templates/proj/index.html - - caret - - column - 0 - line - 137 - - firstVisibleColumn - 85 - firstVisibleLine - 80 - - templates/proj/project.html - - caret - - column - 47 - line - 61 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - - openDocuments - - bin/blog.rb - assets/css/blog.css - templates/blog/archive.html - assets/css/style.css - assets/css/mobile.css - Gemfile - .gitignore - assets/js/blog.js - public/discussions.html - discussd/discussd.js - discussd/package.json - package.json - bin/projects.js - assets/css/proj.css - assets/css/proj-common.css - projects.json - assets/js/request.js - templates/blog/post.html - public/.htaccess - assets/js/strftime.js - templates/blog/link.rss.html - templates/blog/link.mustache - templates/blog/post.mustache - templates/proj/index.html - assets/js/proj.js - public/index.html - templates/proj/project.html - TODO - templates/blog/index.html - Makefile - bin/combine.sh - - showFileHierarchyDrawer - - windowFrame - {{0, 4}, {960, 1174}} - - diff --git a/templates/blog/archive.html b/templates/blog/archive.html deleted file mode 100644 index ce8fc21..0000000 --- a/templates/blog/archive.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - archive - sjs's blog - - - - - - - - - - - - -
      - {{#posts}} -
    • {{date}} {{title}}
    • - {{/posts}} -
    - - - - diff --git a/templates/blog/index.html b/templates/blog/index.html deleted file mode 100644 index ec3d222..0000000 --- a/templates/blog/index.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - sjs's blog - - - {{#styles}} - - {{/styles}} - - - - - - - - - - {{{article}}} - {{#comments}} -

    (discussion requires JavaScript)

    - -
    -
    -
    -
    -
    - -

    -

    -

    -

    -

    -
    -
    - - {{/comments}} - - - - {{#comments}} - - - {{/comments}} - - diff --git a/templates/blog/post.html b/templates/blog/post.html deleted file mode 100644 index 3930732..0000000 --- a/templates/blog/post.html +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - {{title}} - sjs's blog - - - - - {{#styles}} - - {{/styles}} - - - - - - - - {{{article}}} - - {{#comments}} -

    (discussion requires JavaScript)

    - -
    -
    -
    -
    -
    - -

    -

    -

    -

    -

    -
    -
    - - {{/comments}} - - - - - - {{#comments}} - - - - {{/comments}} - - - diff --git a/templates/blog/post.mustache b/templates/blog/post.mustache deleted file mode 100644 index 5757920..0000000 --- a/templates/blog/post.mustache +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/templates/blog/link.rss.html b/templates/link.rss.html similarity index 100% rename from templates/blog/link.rss.html rename to templates/link.rss.html diff --git a/templates/blog/post.rss.html b/templates/post.rss.html similarity index 100% rename from templates/blog/post.rss.html rename to templates/post.rss.html diff --git a/templates/proj/index.html b/templates/proj/index.html deleted file mode 100644 index 44535f7..0000000 --- a/templates/proj/index.html +++ /dev/null @@ -1,172 +0,0 @@ - - - - - - projects - samhuri.net - - - - - - - - - - Fork me on GitHub - - -

    - GitHub -

    - - - - - - - - - - - -
    - - projects - - - - followers - -
    - - gists - - - - following - -
    - - -

    - JS RegExp .lastIndex -

    - - - - - diff --git a/templates/proj/project.html b/templates/proj/project.html deleted file mode 100644 index d1a3579..0000000 --- a/templates/proj/project.html +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - {{name}} - samhuri.net - - - - - - -Fork me on GitHub -

    {{name}}

    -

    {{description}}

    - - - - - - -
    - watchers - - - forks - -
    -
    -
    -

    branches

    - -
    -
    -

    languages

    - -
    -
    -

    contributors

    - -
    -
    -
    - - - - - - - - diff --git a/wayback/@done/2007.05.20-sjs - samhuri.net.html b/wayback/@done/2007.05.20-sjs - samhuri.net.html new file mode 100644 index 0000000..1a69283 --- /dev/null +++ b/wayback/@done/2007.05.20-sjs - samhuri.net.html @@ -0,0 +1,781 @@ + + + + sjs - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    +
    +

    iPhone humour

    +

    Posted by sjs +Fri, 18 May 2007 18:34:00 GMT

    +

    Love it or hate it - even though it's not even out yet - the iPhone has spawned at least 2 good jokes.

    + + + + + +
      +
    • A comment on slashdot: +
      +

      "I'm waiting for the iPhone-shuffle, no display, just a button to call a random person on your contacts list."

    • +

    + + + +

    Posted in ,  | Tags , ,  | no comments | no trackbacks

    +
    +
    +

    Cheating at life in general

    +

    Posted by sjs +Wed, 16 May 2007 16:46:00 GMT

    +

    NB: My definition of life is slightly skewed by my being somewhat of a geek

    + + +

    Luckily no one in the real world cares if you cheat. Most of life is open-book, but for the times when you just need to find something quick the answer, of course, is to cheat profusely.

    + + +

    I've only checked out a few of the cheat sheets but they are of high quality and their wiki-like nature means if they suck and you have time you can help out. I was very pleased to find that there are a number of zsh cheats already.

    + + +

    They certainly know the way to my heart! Ruby, Rails, TextMate*, vim*, zsh, screen. That'll do snake. That'll do.

    + + +

    * There are cheats for emacs, jEdit, and e too if TextMate and/or vim don't tickle your fancy

    + + +

    Tags  | no comments | no trackbacks

    +
    +
    +

    Dumping objects to the browser in Rails

    +

    Posted by sjs +Wed, 16 May 2007 03:38:00 GMT

    +

    Here's an easy way to solve a problem that may have nagged you as it did me. Simply using foo.inspect to dump out some object to the browser dumps one long string which is barely useful except for short strings and the like. The ideal output is already available using the PrettyPrint module so we just need to use it.

    + + +

    Unfortunately typing <pre><%= PP.pp(@something, '') %></pre> to quickly debug some possibly large object (or collection) can get old fast so we need a shortcut.

    + + +

    Taking the definition of Object#pp_s from the extensions project it's trivial to create a helper method to just dump out an object in a reasonable manner.

    + + +
    /app/helpers/application_helper.rb
    def dump(thing)
    +  s = StringIO.new
    +  PP.pp(thing, s)
    +  "<pre>#{s.string}</pre>"
    +end
    + +

    Alternatively you could do as the extensions folks do and actually define Object#pp_s so you can use it in your logs or anywhere else you may want to inspect an object. If you do this you probably want to change the dump helper method accordingly in case you decide to change pp_s in the future.

    + + +
    lib/local_support/core_ext/object.rb
    class Object
    +  def pp_s
    +    pps = StringIO.new
    +    PP.pp(self, pps)
    +    pps.string
    +  end
    +end
    + + +

    Posted in  | Tags  | no comments | no trackbacks

    +
    +
    +

    Good reading

    +

    Posted by sjs +Wed, 16 May 2007 00:55:00 GMT

    +

    This is the best tutorial I have read on developing RESTful web apps using Rails. If you're remotely interested or curious about REST on Rails I highly recommend that as one of your first reads.

    + + +

    I have been messing around with REST and managed to piece together a basic app without much trouble. That tutorial really cleared up some things I wasn't too sure about, especially with respect to routing resources.

    + + +

    Check out the restful_authentication plugin to see how a session becomes a resource.

    + + +

    For many cases I can definitely see the benefits of REST and for the exceptions you just use Rails in the traditional way.

    + + +

    Posted in  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    Enumerable#pluck and String#to_proc for Ruby

    +

    Posted by sjs +Fri, 11 May 2007 06:14:00 GMT

    +

    I wanted a method analogous to Prototype's pluck and invoke in Rails for building lists for options_for_select. Yes, I know about options_from_collection_for_select.

    + + +

    I wanted something more general that I can use anywhere - not just in Rails - so I wrote one. In a second I'll introduce Enumerable#pluck, but first we need some other methods to help implement it nicely.

    + + +

    First you need Symbol#to_proc, which shouldn't need an introduction. If you're using Rails you have this already.

    + + +
    Symbol#to_proc
    class Symbol
    +  # Turns a symbol into a proc.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| p.birthdate }
    +  #   people.map(&:birthdate)
    +  #
    +  def to_proc
    +    Proc.new {|thing, *args| thing.send(self, *args)}
    +  end
    +end
    +
    + +

    Next we define String#to_proc, which is nearly identical to the Array#to_proc method I previously wrote about.

    + + +
    String#to_proc
    class String
    +  # Turns a string into a proc.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| p.birthdate.year }
    +  #   people.map(&'birthdate.year')
    +  #
    +  def to_proc
    +    Proc.new do |*args|
    +      split('.').inject(args.shift) do |thing, msg|
    +        thing = thing.send(msg.to_sym, *args)
    +      end
    +    end
    +  end
    +end
    +
    + +

    Finally there's Enumerable#to_proc which returns a proc that passes its parameter through each of its members and collects their results. It's easier to explain by example.

    + + +
    Enumerable#to_proc
    module Enumerable
    +  # Effectively treats itself as a list of transformations, and returns a proc
    +  # which maps values to a list of the results of applying each transformation
    +  # in that list to the value.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| [p.birthdate, p.email] }
    +  #   people.map(&[:birthdate, :email])
    +  #
    +  def to_proc
    +    @procs ||= map(&:to_proc)
    +    Proc.new do |thing, *args|
    +      @procs.map do |proc|
    +        proc.call(thing, *args)
    +      end
    +    end
    +  end
    +end
    + +

    Here's the cool part, Enumerable#pluck for Ruby in all its glory.

    + + +
    Enumerable#pluck
    module Enumerable
    +  # Use this to pluck values from objects, especially useful for ActiveRecord models.
    +  # This is analogous to Prototype's Enumerable.pluck method but more powerful.
    +  #
    +  # You can pluck values simply, like so:
    +  #   >> people.pluck(:last_name)  #=> ['Samhuri', 'Jones', ...]
    +  #
    +  # But with Symbol#to_proc defined this is effectively the same as:
    +  #   >> people.map(&:last_name)   #=> ['Samhuri', 'Jones', ...]
    +  #
    +  # Where pluck's power becomes evident is when you want to do something like:
    +  #   >> people.pluck(:name, :address, :phone)
    +  #        #=> [['Johnny Canuck', '123 Maple Lane', '416-555-124'], ...]
    +  #
    +  # Instead of:
    +  #   >> people.map { |p| [p.name, p.address, p.phone] }
    +  #
    +  #   # map each person to: [person.country.code, person.id]
    +  #   >> people.pluck('country.code', :id)
    +  #        #=> [['US', 1], ['CA', 2], ...]
    +  #
    +  def pluck(*args)
    +    # Thanks to Symbol#to_proc, Enumerable#to_proc and String#to_proc this Just Works(tm)
    +    map(&args)
    +  end
    +end
    + +

    I wrote another version without using the various #to_proc methods so as to work with a standard Ruby while only patching 1 module.

    + + +
    module Enumerable
    +  # A version of pluck which doesn't require any to_proc methods.
    +  def pluck(*args)
    +    procs = args.map do |msgs|
    +      # always operate on lists of messages
    +      if String === msgs
    +        msgs = msgs.split('.').map {|a| a.to_sym} # allow 'country.code'
    +      elsif !(Enumerable === msgs)
    +        msgs = [msgs]
    +      end
    +      Proc.new do |orig|
    +        msgs.inject(orig) { |thing, msg| thing = thing.send(msg) }
    +      end
    +    end
    +
    +    if procs.size == 1
    +      map(&procs.first)
    +    else
    +      map do |thing|
    +        procs.map { |proc| proc.call(thing) }
    +      end
    +    end
    +  end
    +end
    + +

    It's just icing on the cake considering Ruby's convenient block syntax, but there it is. Do with it what you will. You can change or extend any of these to support drilling down into hashes quite easily too.

    + + +

    Update #1: Fixed a potential performance issue in Enumerable#to_proc by saving the results of to_proc in @procs.

    + + +

    Posted in ,  | Tags ,  | 2 comments | no trackbacks

    +
    +
    +

    Rails plugins (link dump)

    +

    Posted by sjs +Thu, 10 May 2007 07:22:00 GMT

    +

    Some Rails plugins I find useful:

    + + + + + +

    Posted in  | Tags  | no comments | no trackbacks

    +
    +
    +

    I can't wait to see what Matt Stone & Trey Parker do with this

    +

    Posted by sjs +Thu, 10 May 2007 04:34:00 GMT

    +

    I'd just like to say, bwa ha ha ha!

    + + +

    Summary: Paris Hilton drove with a suspended license and is facing 45 days in jail. Now she's reaching out to lord knows who on her MySpace page to petition The Governator to pardon her. I might cry if I weren't pissing myself laughing.

    + + +

    Paris Hilton is out of her mind, living in some fantasy world separate from Earth. Pathetic doesn't begin to describe this plea for help from her own stupidity. She knowingly and willingly disobeyed the law, got busted, and then proceeded to claim that

    + + +
    +

    "She provides hope for young people all over the U.S. and the world. She provides beauty and excitement to (most of) our otherwise mundane lives."

    +
    + + +

    I take this as a learning experience. For example, I learned that the US is no longer part of the world.

    + + +

    Flat out crazy, insane, not of sound mind. She is not any sort of hope, inspiration or role model for anyone.

    + + +

    Posted in  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    dtrace + ruby = goodness for Sun

    +

    Posted by sjs +Wed, 09 May 2007 22:45:00 GMT

    +

    Suddenly I feel the urge to try out Solaris for i386 again. Last time I gave it a shot was when it was first released, and all I ever got out of the CD was a white screen. It's been 2-3 years since then and it should be well-tested. I'll try to install it into a VM first using the ISO and potentially save myself a CD. (I don't even think I have blank CDs lying around anymore, only DVDs.)

    + + +

    The culprit.

    + + +

    Posted in  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    A new way to look at networking

    +

    Posted by sjs +Sun, 06 May 2007 06:10:00 GMT

    +

    Van Jacobson gave a Google Tech Talk on some of his ideas of how a modern, global network could work more effectively, and with more trust in the data which changes many hands on its journey to its final destination.

    + + + + +

    The man is very smart and his ideas are fascinating. He has the experience and knowledge to see the big picture and what can be done to solve some of the new problems we have. He starts with the beginning of the phone networks and then goes on to briefly explain the origins of the ARPAnet, which evolved into the modern Internet and TCP/IP and the many other protocols we use daily (often behind the scenes).

    + + +

    He explains the problems that were faced while using the phone networks for data, and how they were solved by realizing that a new problem had risen and needed a new, different solution. He then goes to explain how the Internet has changed significantly from the time it started off in research centres, schools, and government offices into what it is today (lots of identical bytes being redundantly pushed to many consumers, where broadcast would be more appropriate and efficient).

    + + +

    If you have some time I really suggest watching this talk. I would love to research some of the things he spoke about if I ever got the chance. I'm sure they'll be on my mind anyway and inevitably I'll end up playing around with layering crap onto IPV6 and what not. Deep down I love coding in C and I think developing a protocol would be pretty fun. I'd learn a lot in any case.

    + + +

    Posted in  | Tags  | no comments | no trackbacks

    +
    +
    +

    Gotta love the ferry ride

    +

    Posted by sjs +Sat, 05 May 2007 18:25:00 GMT

    +

    I lived in Victoria for over a year before I ever rode the ferry between Vancouver Island and Tsawwassen (ignoring the time I was in BC with my family about 16 years ago, that is). I always just flew in and out of Victoria directly. The ferry is awesome and the view is incredible, navigating through all those little islands. Last time I rode the ferry I snapped this shot. It's possibly the best picture I've taken on that trip.

    + + +

    Sunset

    + + +

    Posted in  | Tags  | no comments | no trackbacks

    +
    + + +

    Older posts: 1 2 3 ... 5

    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/2007.05.28-sjs - samhuri.net.html b/wayback/@done/2007.05.28-sjs - samhuri.net.html new file mode 100644 index 0000000..9f0a7f5 --- /dev/null +++ b/wayback/@done/2007.05.28-sjs - samhuri.net.html @@ -0,0 +1,793 @@ + + + + sjs - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    +
    +

    inspirado

    +

    Posted by sjs +Wed, 23 May 2007 03:23:00 GMT

    +

    spyderous is a Gentoo dev and I read his posts via the Gentoo planet (and again on the freedesktop.org planet).

    + + +

    He recently mentioned an idea to foster participation in Gentoo (or any other project) by aggregating personal project plans for people to browse. I thought it sounded cool so I started coding and came up with what I call inspirado.

    + + +

    It's fairly basic so far but it's only a week old. It is RESTful and you can get XML for most pages by appending .xml to the URL (or by using curl and setting the HTTP Accept header). Eventually Atom and/or RSS should be available as well.

    + + +

    Note that everything you see there is purely for testing purposes and any changes you make are most likely going to be blown away.

    + + +

    There are several features on my TODO list but I'd love to hear about any you might have. Write to sami.samhuri@gmail.com if you have suggestions or anything else to say.

    + + +

    (Inspirado is, of course, a Rails app.)

    + + +

    Posted in ,  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    iPhone humour

    +

    Posted by sjs +Fri, 18 May 2007 18:34:00 GMT

    +

    Love it or hate it - even though it's not even out yet - the iPhone has spawned at least 2 good jokes.

    + + + + + +
      +
    • A comment on slashdot: +
      +

      "I'm waiting for the iPhone-shuffle, no display, just a button to call a random person on your contacts list."

    • +

    + + + +

    Posted in ,  | Tags , ,  | no comments | no trackbacks

    +
    +
    +

    Cheating at life in general

    +

    Posted by sjs +Wed, 16 May 2007 16:46:00 GMT

    +

    NB: My definition of life is slightly skewed by my being somewhat of a geek

    + + +

    Luckily no one in the real world cares if you cheat. Most of life is open-book, but for the times when you just need to find something quick the answer, of course, is to cheat profusely.

    + + +

    I've only checked out a few of the cheat sheets but they are of high quality and their wiki-like nature means if they suck and you have time you can help out. I was very pleased to find that there are a number of zsh cheats already.

    + + +

    They certainly know the way to my heart! Ruby, Rails, TextMate*, vim*, zsh, screen. That'll do snake. That'll do.

    + + +

    * There are cheats for emacs, jEdit, and e too if TextMate and/or vim don't tickle your fancy

    + + +

    Tags  | no comments | no trackbacks

    +
    +
    +

    Dumping objects to the browser in Rails

    +

    Posted by sjs +Wed, 16 May 2007 03:38:00 GMT

    +

    Here's an easy way to solve a problem that may have nagged you as it did me. Simply using foo.inspect to dump out some object to the browser dumps one long string which is barely useful except for short strings and the like. The ideal output is already available using the PrettyPrint module so we just need to use it.

    + + +

    Unfortunately typing <pre><%= PP.pp(@something, '') %></pre> to quickly debug some possibly large object (or collection) can get old fast so we need a shortcut.

    + + +

    Taking the definition of Object#pp_s from the extensions project it's trivial to create a helper method to just dump out an object in a reasonable manner.

    + + +
    /app/helpers/application_helper.rb
    def dump(thing)
    +  s = StringIO.new
    +  PP.pp(thing, s)
    +  "<pre>#{s.string}</pre>"
    +end
    + +

    Alternatively you could do as the extensions folks do and actually define Object#pp_s so you can use it in your logs or anywhere else you may want to inspect an object. If you do this you probably want to change the dump helper method accordingly in case you decide to change pp_s in the future.

    + + +
    lib/local_support/core_ext/object.rb
    class Object
    +  def pp_s
    +    pps = StringIO.new
    +    PP.pp(self, pps)
    +    pps.string
    +  end
    +end
    + + +

    Posted in  | Tags  | no comments | no trackbacks

    +
    +
    +

    Good reading

    +

    Posted by sjs +Wed, 16 May 2007 00:55:00 GMT

    +

    This is the best tutorial I have read on developing RESTful web apps using Rails. If you're remotely interested or curious about REST on Rails I highly recommend that as one of your first reads.

    + + +

    I have been messing around with REST and managed to piece together a basic app without much trouble. That tutorial really cleared up some things I wasn't too sure about, especially with respect to routing resources.

    + + +

    Check out the restful_authentication plugin to see how a session becomes a resource.

    + + +

    For many cases I can definitely see the benefits of REST and for the exceptions you just use Rails in the traditional way.

    + + +

    Posted in  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    Enumerable#pluck and String#to_proc for Ruby

    +

    Posted by sjs +Fri, 11 May 2007 06:14:00 GMT

    +

    I wanted a method analogous to Prototype's pluck and invoke in Rails for building lists for options_for_select. Yes, I know about options_from_collection_for_select.

    + + +

    I wanted something more general that I can use anywhere - not just in Rails - so I wrote one. In a second I'll introduce Enumerable#pluck, but first we need some other methods to help implement it nicely.

    + + +

    First you need Symbol#to_proc, which shouldn't need an introduction. If you're using Rails you have this already.

    + + +
    Symbol#to_proc
    class Symbol
    +  # Turns a symbol into a proc.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| p.birthdate }
    +  #   people.map(&:birthdate)
    +  #
    +  def to_proc
    +    Proc.new {|thing, *args| thing.send(self, *args)}
    +  end
    +end
    +
    + +

    Next we define String#to_proc, which is nearly identical to the Array#to_proc method I previously wrote about.

    + + +
    String#to_proc
    class String
    +  # Turns a string into a proc.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| p.birthdate.year }
    +  #   people.map(&'birthdate.year')
    +  #
    +  def to_proc
    +    Proc.new do |*args|
    +      split('.').inject(args.shift) do |thing, msg|
    +        thing = thing.send(msg.to_sym, *args)
    +      end
    +    end
    +  end
    +end
    +
    + +

    Finally there's Enumerable#to_proc which returns a proc that passes its parameter through each of its members and collects their results. It's easier to explain by example.

    + + +
    Enumerable#to_proc
    module Enumerable
    +  # Effectively treats itself as a list of transformations, and returns a proc
    +  # which maps values to a list of the results of applying each transformation
    +  # in that list to the value.
    +  #
    +  # Example:
    +  #   # The same as people.map { |p| [p.birthdate, p.email] }
    +  #   people.map(&[:birthdate, :email])
    +  #
    +  def to_proc
    +    @procs ||= map(&:to_proc)
    +    Proc.new do |thing, *args|
    +      @procs.map do |proc|
    +        proc.call(thing, *args)
    +      end
    +    end
    +  end
    +end
    + +

    Here's the cool part, Enumerable#pluck for Ruby in all its glory.

    + + +
    Enumerable#pluck
    module Enumerable
    +  # Use this to pluck values from objects, especially useful for ActiveRecord models.
    +  # This is analogous to Prototype's Enumerable.pluck method but more powerful.
    +  #
    +  # You can pluck values simply, like so:
    +  #   >> people.pluck(:last_name)  #=> ['Samhuri', 'Jones', ...]
    +  #
    +  # But with Symbol#to_proc defined this is effectively the same as:
    +  #   >> people.map(&:last_name)   #=> ['Samhuri', 'Jones', ...]
    +  #
    +  # Where pluck's power becomes evident is when you want to do something like:
    +  #   >> people.pluck(:name, :address, :phone)
    +  #        #=> [['Johnny Canuck', '123 Maple Lane', '416-555-124'], ...]
    +  #
    +  # Instead of:
    +  #   >> people.map { |p| [p.name, p.address, p.phone] }
    +  #
    +  #   # map each person to: [person.country.code, person.id]
    +  #   >> people.pluck('country.code', :id)
    +  #        #=> [['US', 1], ['CA', 2], ...]
    +  #
    +  def pluck(*args)
    +    # Thanks to Symbol#to_proc, Enumerable#to_proc and String#to_proc this Just Works(tm)
    +    map(&args)
    +  end
    +end
    + +

    I wrote another version without using the various #to_proc methods so as to work with a standard Ruby while only patching 1 module.

    + + +
    module Enumerable
    +  # A version of pluck which doesn't require any to_proc methods.
    +  def pluck(*args)
    +    procs = args.map do |msgs|
    +      # always operate on lists of messages
    +      if String === msgs
    +        msgs = msgs.split('.').map {|a| a.to_sym} # allow 'country.code'
    +      elsif !(Enumerable === msgs)
    +        msgs = [msgs]
    +      end
    +      Proc.new do |orig|
    +        msgs.inject(orig) { |thing, msg| thing = thing.send(msg) }
    +      end
    +    end
    +
    +    if procs.size == 1
    +      map(&procs.first)
    +    else
    +      map do |thing|
    +        procs.map { |proc| proc.call(thing) }
    +      end
    +    end
    +  end
    +end
    + +

    It's just icing on the cake considering Ruby's convenient block syntax, but there it is. Do with it what you will. You can change or extend any of these to support drilling down into hashes quite easily too.

    + + +

    Update #1: Fixed a potential performance issue in Enumerable#to_proc by saving the results of to_proc in @procs.

    + + +

    Posted in ,  | Tags ,  | 2 comments | no trackbacks

    +
    +
    +

    Rails plugins (link dump)

    +

    Posted by sjs +Thu, 10 May 2007 07:22:00 GMT

    +

    Some Rails plugins I find useful:

    + + + + + +

    Posted in  | Tags  | no comments | no trackbacks

    +
    +
    +

    I can't wait to see what Matt Stone & Trey Parker do with this

    +

    Posted by sjs +Thu, 10 May 2007 04:34:00 GMT

    +

    I'd just like to say, bwa ha ha ha!

    + + +

    Summary: Paris Hilton drove with a suspended license and is facing 45 days in jail. Now she's reaching out to lord knows who on her MySpace page to petition The Governator to pardon her. I might cry if I weren't pissing myself laughing.

    + + +

    Paris Hilton is out of her mind, living in some fantasy world separate from Earth. Pathetic doesn't begin to describe this plea for help from her own stupidity. She knowingly and willingly disobeyed the law, got busted, and then proceeded to claim that

    + + +
    +

    "She provides hope for young people all over the U.S. and the world. She provides beauty and excitement to (most of) our otherwise mundane lives."

    +
    + + +

    I take this as a learning experience. For example, I learned that the US is no longer part of the world.

    + + +

    Flat out crazy, insane, not of sound mind. She is not any sort of hope, inspiration or role model for anyone.

    + + +

    Posted in  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    dtrace + ruby = goodness for Sun

    +

    Posted by sjs +Wed, 09 May 2007 22:45:00 GMT

    +

    Suddenly I feel the urge to try out Solaris for i386 again. Last time I gave it a shot was when it was first released, and all I ever got out of the CD was a white screen. It's been 2-3 years since then and it should be well-tested. I'll try to install it into a VM first using the ISO and potentially save myself a CD. (I don't even think I have blank CDs lying around anymore, only DVDs.)

    + + +

    The culprit.

    + + +

    Posted in  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    A new way to look at networking

    +

    Posted by sjs +Sun, 06 May 2007 06:10:00 GMT

    +

    Van Jacobson gave a Google Tech Talk on some of his ideas of how a modern, global network could work more effectively, and with more trust in the data which changes many hands on its journey to its final destination.

    + + + + +

    The man is very smart and his ideas are fascinating. He has the experience and knowledge to see the big picture and what can be done to solve some of the new problems we have. He starts with the beginning of the phone networks and then goes on to briefly explain the origins of the ARPAnet, which evolved into the modern Internet and TCP/IP and the many other protocols we use daily (often behind the scenes).

    + + +

    He explains the problems that were faced while using the phone networks for data, and how they were solved by realizing that a new problem had risen and needed a new, different solution. He then goes to explain how the Internet has changed significantly from the time it started off in research centres, schools, and government offices into what it is today (lots of identical bytes being redundantly pushed to many consumers, where broadcast would be more appropriate and efficient).

    + + +

    If you have some time I really suggest watching this talk. I would love to research some of the things he spoke about if I ever got the chance. I'm sure they'll be on my mind anyway and inevitably I'll end up playing around with layering crap onto IPV6 and what not. Deep down I love coding in C and I think developing a protocol would be pretty fun. I'd learn a lot in any case.

    + + +

    Posted in  | Tags  | no comments | no trackbacks

    +
    + + +

    Older posts: 1 2 3 ... 5

    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/2007.06.29-sjs - geeky ramblings.html b/wayback/@done/2007.06.29-sjs - geeky ramblings.html new file mode 100644 index 0000000..4cb2e62 --- /dev/null +++ b/wayback/@done/2007.06.29-sjs - geeky ramblings.html @@ -0,0 +1,1563 @@ + + + + sjs - geeky ramblings + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + +
    +

    + Recent Ruby and Rails Regales + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, June 28 +
    +
    +

    Some cool Ruby and [the former on] Rails things are springing up and I haven't written much about the two Rs lately, though I work with them daily.

    + + +

    Rails on Rules

    + + +

    My friend Jim Roepcke is researching and implementing a plugin/framework designed to work with Rails called Rails on Rules. His inspiration is the rule system from WebObjects' Direct to Web. He posted a good example for me, but this baby isn't just for template/view logic. If some of the Rails conventions were specified in a default set of rules which the developer could further customize then you basically have a nice way of doing things that you would otherwise code by hand. I think it would be a boon for the ActiveScaffold project. We're meeting up to talk about this soon and I'll have more to say after then, but it sounds pretty cool.

    + + +

    Sake Bomb!

    + + +

    I've noticed a trend among some recent posts about Rake: the authors keep talking about booze. Are we nothing but a bunch of booze hounds?! Well one can hope. There's some motivation to learn more about a tool, having more time to drink after work. This week Chris Wanstrath dropped a Sake Bomb on the Ruby community. Like piston, sake is something you can just pick up and use instantly. Interestingly the different pronunciations of rake and sake help me from confusing the two on the command line... so far.

    + + +

    Secure Associations (for Rails)

    + + +

    Jordan McKible released the secure_associations plugin. It lets you protect your models' *_id attributes from mass-assignment via belongs_to_protected and has_many_protected. It's a mild enhancement, but an enhancement nonetheless. This is useful to enough people that it should be in Rails proper.

    + + +

    Regular expressions and strings with embedded objects

    + + +

    taw taught me a new technique for simplifying regular expressions by transforming the text in a reversible manner. In one example he replaced literal strings in SQL - which are easily parsed via a regex - with what he calls embedded objects. They're just tokens to identify the temporarily removed strings, but the important thing is that they don't interfere with the regexes that operate on the other parts of the SQL, which would have been very difficult to get right with the strings inside it. If I made it sound complicated just read the post, he explains it well.

    + + +

    If you believe anything Steve Yegge says then that last regex trick may come in handy for Q&D parsing in any language, be it Ruby, NBL, or whataver.

    + +
    + +
    + +
    +

    + Emacs: tagify-region-or-insert-tag + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    After axing half of wrap-region.el I renamed it to tagify.el and improved it ever so slightly. It's leaner, and does more!

    + + +

    tagify-region-or-insert-tag does the same thing as wrap-region-with-tag except if there is no region it now inserts the opening and closing tags and sets point in between them. I have this bound to C-z t, as I use C-z as my personal command prefix.

    + + +

    < is bound to tagify-region-or-insert-self which really doesn't warrant an explanation.

    + +
    + +
    + +
    +

    + RTFM! + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    I should read the Emacs manual sometime, especially since I have it in dead-tree form. Check out skeleton pairs in the Emacs manual, or better yet C-h f skeleton-pair-insert-maybe. skeleton-pair has already been massaged to do what you most likely want if you set the correct options. Cool. I like Emacs more every day.

    + + +

    This renders wrap-region useless, which is great! I like a trim .emacs and .emacs.d.

    + +
    + +
    + +
    +

    + Propaganda makes me sick + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    Things like this in modern times are surprising. Can't people spot this phony crap for what it is?

    + + +

    First they put away the dealers, keep our kids safe and off the streets
    +Then they put away the prostitutes, keep married men cloistered at home
    +Then they shooed away the bums, and they beat and bashed the queers
    +Turned away asylum-seekers, fed us suspicions and fears
    +We didn't raise our voice, we didn't make a fuss
    +It´s funny there was no one left to notice, when they came for us
    +
    +Looks like witches are in season, you better fly your flag and be aware
    +Of anyone who might fit the description, diversity is now our biggest fear
    +Now with our conversations tapped, and our differences exposed
    +How ya supposed to love your neighbour, with our minds and curtains +closed?
    +We used to worry ‘bout big brother
    +Now we got a big father and an even bigger mother

    +
    +And still you believe, this aristocracy gives a fuck about you
    +They put the mock in democracy, and you swallowed every hook
    +The sad truth is, you'd rather follow the school into the net
    +‘Cause swimming alone at sea, is not the kind of freedom that you +actually want
    +So go back to your crib, and suck on a tit
    +Bask in the warmth of your diaper, you're sitting in shit
    +And piss, while sucking on a giant pacifier
    +A country of adult infants, a legion of mental midgets
    +A country of adult infants, a country of adult infants
    +All regaining their unconsciousness
    +
    +—from the song Regaining Unconsciousness, by NOFX

    + +
    + +
    + +
    +

    + Floating point in ElSchemo + + 0 + +

    +
    + Posted by sjs +
    +on Sunday, June 24 +
    +
    +

    NB: My Scheme interpreter is based on Jonathan Tang's Write Yourself a Scheme in 48 hours Haskell tutorial. Not all of this makes sense outside that context, and the context of my previous posts on the subject.

    + + +

    My scheme interpreter has been christened ElSchemo, since it was sorely in need of a better name than "my Scheme interpreter". It's also seen far too much of my time and sports jazzy new features. I'll probably post the full code up here sooner or later, including my stdlib.scm and misp slightly modified to run with ElSchemo's limited vocabulary (namely the lack of define-syntax).

    + + +

    But that will be for another day, because today I want to talk about implementing floating point numbers, from parsing to operating on them.

    + + + +
    + +
    + +
    +

    + Emacs for TextMate junkies + + 6 + +

    +
    + Posted by sjs +
    +on Saturday, June 23 +
    +
    +

    Update #1: What I first posted will take out your < key by mistake (it's available via C-q <), it has since been revised to Do The Right Thing.

    + + +

    Update #2: Thanks to an anonymouse[sic] commenter this code is a little cleaner.

    + + +

    Update #3: I should read the Emacs manual sometime, especially since I have it in dead-tree form. Check out skeleton pairs in the Emacs manual.

    + + +

    Despite my current infatuation with Emacs there are many reasons I started using TextMate, especially little time-savers that are very addictive. I'll talk about one of those features tonight. When you have text selected in TextMate and you hit say the ' (single quote) then TextMate will surround the selected text with single quotes. The same goes for double quotes, parentheses, brackets, and braces. This little trick is one of my favourites so I had to come up with something similar in Emacs. It was easy since a mailing list post has a solution for surrounding the current region with tags, which served as a great starting point.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    (defun surround-region-with-tag (tag-name beg end)
    +      (interactive "sTag name: \nr")
    +      (save-excursion
    +        (goto-char beg)
    +        (insert "<" tag-name ">")
    +        (goto-char (+ end 2 (length tag-name)))
    +        (insert "</" tag-name ">")))
    + + +

    With a little modification I now have the following in my ~/.emacs file:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +
    ;; help out a TextMate junkie
    +
    +(defun wrap-region (left right beg end)
    +  "Wrap the region in arbitrary text, LEFT goes to the left and RIGHT goes to the right."
    +  (interactive)
    +  (save-excursion
    +    (goto-char beg)
    +    (insert left)
    +    (goto-char (+ end (length left)))
    +    (insert right)))
    +
    +(defmacro wrap-region-with-function (left right)
    +  "Returns a function which, when called, will interactively `wrap-region-or-insert' using LEFT and RIGHT."
    +  `(lambda () (interactive)
    +     (wrap-region-or-insert ,left ,right)))
    +
    +(defun wrap-region-with-tag-or-insert ()
    +  (interactive)
    +  (if (and mark-active transient-mark-mode)
    +      (call-interactively 'wrap-region-with-tag)
    +    (insert "<")))
    +
    +(defun wrap-region-with-tag (tag beg end)
    +  "Wrap the region in the given HTML/XML tag using `wrap-region'. If any
    +attributes are specified then they are only included in the opening tag."
    +  (interactive "*sTag (including attributes): \nr")
    +  (let* ((elems    (split-string tag " "))
    +         (tag-name (car elems))
    +         (right    (concat "</" tag-name ">")))
    +    (if (= 1 (length elems))
    +        (wrap-region (concat "<" tag-name ">") right beg end)
    +      (wrap-region (concat "<" tag ">") right beg end))))
    +
    +(defun wrap-region-or-insert (left right)
    +  "Wrap the region with `wrap-region' if an active region is marked, otherwise insert LEFT at point."
    +  (interactive)
    +  (if (and mark-active transient-mark-mode)
    +      (wrap-region left right (region-beginning) (region-end))
    +    (insert left)))
    +
    +(global-set-key "'"  (wrap-region-with-function "'" "'"))
    +(global-set-key "\"" (wrap-region-with-function "\"" "\""))
    +(global-set-key "`"  (wrap-region-with-function "`" "`"))
    +(global-set-key "("  (wrap-region-with-function "(" ")"))
    +(global-set-key "["  (wrap-region-with-function "[" "]"))
    +(global-set-key "{"  (wrap-region-with-function "{" "}"))
    +(global-set-key "<"  'wrap-region-with-tag-or-insert) ;; I opted not to have a wrap-with-angle-brackets
    + + +

    Download wrap-region.el

    + + +

    That more or less sums up why I like Emacs so much. I wanted that functionality so I implemented it (barely! It was basically done for me), debugged it by immediately evaluating sexps and then trying it out, and then once it worked I reloaded my config and used the wanted feature. That's just awesome, and shows one strength of open source.

    + +
    + +
    + +
    +

    + Embrace the database + + 0 + +

    +
    + Posted by sjs +
    +on Friday, June 22 +
    +
    +

    If you drink the Rails koolaid you may have read the notorious single layer of cleverness post by DHH. [5th post on the archive page] In a nutshell he states that it's better to have a single point of cleverness when it comes to business logic. The reasons for this include staying agile, staying in Ruby all the time, and being able to switch the back-end DB at any time. Put the logic in ActiveRecord and use the DB as a dumb data store, that is the Rails way. It's simple. It works. You don't need to be a DBA to be a Rails developer.

    + + +

    Stephen created a Rails plugin called dependent-raise which imitates a foreign key constraint inside of Rails. I want to try this out because I believe that data integrity is fairly important, but it's really starting to make me think about this single point of cleverness idea.

    + + +

    Are we not reinventing the wheel by employing methods such as this in our code? Capable DBs already do this sort of thing for us. I don't necessarily think it's bad to implement this sort of thing, but I think it's a symptom of NIH syndrome. Instead of reinventing this kind of thing why don't we embrace the DB as a semi-intelligent data store? The work has been done all we have to do is exploit it via Rails.

    + + +

    There are a few reasons that the Rails folks choose not to do so but perhaps some of them could be worked around. Adapting your solution as you progress and realise that things aren't exactly as you thought they were... I believe the word for that sort of thing is agility.

    + + +

    Database agnosticism

    + + +

    From SQLite to Oracle, just configure the connection, migrate, and run your app on any database. One of the biggest Rails myths that is backed by the Rails team themselves. It takes a fair amount of work to ensure that any significant app is fully agnostic. Sure you can develop on SQLite and deploy on MySQL without much trouble but there are significant diffirences between RDBMSs that will manifest themselves if you create an app that's more than a toy. Oh, you used finder_sql? Sorry but chances are your app is no longer DB agnostic. FAIL.

    + + +

    Solution: Drop the lie. Tell people the truth. Theoretically, theory and practice are the same; in practice they are not. Be honest that it's possible to be DB-agnostic but can be a challenge. Under no circumstances should we shun something useful in the name of claiming to be DB-agnostic.

    + + +

    Staying agile

    + + +

    If we start making use of FK constraints then we'll have to make changes to both our DB and our code. This makes change more time-consuming and error-prone which means change is less likely to happen. This goes against the grain of an agile methodology. Or does it?

    + + +

    Solution: Rails should use the features of the DB to keep data intact and fall back on an AR-only solution only if the DB doesn't support the operation. There doesn't need to be any duplication in logic rules either. If Rails could recognise a FK constraint that cascades on delete it could set up the has_many :foos, :dependent => :destroy relation for us. In fact I only see our code becoming DRYer (maybe even too DRY[1]).

    + + +

    Staying in Ruby

    + + +

    Using the DB from within Ruby is a solved problem. I don't see why this couldn't be extended to handle more of the DB as well. Use Ruby, but use it intelligently by embracing outside tools to get the job done.

    + + +

    Many relationships could be derived from constraints as people have pointed out before. There are benefits to using the features of a decent RDBMS, and in some cases I think that we might be losing by not making use of them. I am not saying we should move everything to the DB, I am saying that we should exploit the implemented and debugged capabilities of our RDBMSs the best we can while practicing the agile methods we know and love, all from within Ruby.

    + + +

    [1] I make liberal use of annotate_models as it is.

    + +
    + +
    + +
    +

    + Reinventing the wheel + + 0 + +

    +
    + Posted by sjs +
    +on Wednesday, June 20 +
    +
    +

    Emacs is very impressive. I only felt lost and unproductive for minutes and now it seems natural to use and get around in. I've got ElSchemo set as the default scheme, and running inferior processes interactively is an absolute dream. My scheme doesn't have readline support (which bothers me to the point where I've thought about adding it just so I can use the thing) but when running it under Emacs there's absoutely no need for anything like that since I have the power of my editor when interacting with any program.

    + + +

    There has been a considerable amount of work done to aide in Rails development which makes Emacs especially comfortable for me. I now know why people have Emacs windows maximized on their screens. Because of its age Emacs is a handy window manager that basically eliminates the need for anything like GNU screen or a window manager such as Rat poison (which is great if you like screen), just maximize that Emacs "frame" or open one for each display and get to it. If you need a shell you just split the window and run your shell, when you're done you can easily switch back to your editing and your shell will wait in the background until you need it again. With rails-mode on I can run script/console (or switch back to it) with C-c C-c s c. My zsh alias for script/console is sc and I have other similarly succint ones for other stuff, so I took right to the shortcuts for all the handy things that I no longer have to switch applications to do:

    + + +
      +
    • C-c C-c . - Run the tests for this file. If I'm in a unit test it runs it, if I'm in the model it runs the corresponding unit tests.
    • +
    • C-c C-c w s - Run the web server (script/server).
    • +
    • C-c C-c t - Run tests. The last value entered is the default choice, and the options are analogous to the rake test:* tasks.
    • +
    • and so on...
    • +
    + + +

    The Rails integration is simply stunning and I could go on all day about the mature indentation support, the Speedbar and what not, but I won't. I'm fairly sure that Emacs has taken the place of TextMate as my weapon of choice now, on all platforms. And after only 2 days!

    + + +

    Anyway, the point of all this was to mention the one thing that's missing: support for intelligent snippets which insert text at more than one point in the document (well, they appear to do so). I don't have any E-Lisp-fu to break out and solve the deficiency but if it ever bugs me enough I might try implementing it for Emacs one day. If they were useful to me outside of writing migrations I might have more incentive to do so, but I guess they aren't useful in normal editing situations (maybe I just haven't recognised the need).

    + +
    + +
    + +
    +

    + Back on Gentoo, trying new things + + 0 + +

    +
    + Posted by sjs +
    +on Tuesday, June 19 +
    +
    +

    I started using my Gentoo box for development again and there are a few things about Linux I didn't realize I had been missing.

    + + +

    Shell completion is awesome out of the box

    + + +

    zsh has an impressive completion system but I just don't feel the urge to ever customize it extensively. I just use the basic completion stuff on OS X because it's easy. On Gentoo I have rake tasks and all sorts of other crap completed for me by including a few lines in my .zshrc (iirc a script does this automatically anyway). Generally Linux distros try to knit everything together nicely so you never even think about things like whether or not a package will have readline support, and default configs will be tweaked and enhanced beyond the official zsh package.

    + + +

    Linux is stable. Really stable.

    + + +

    While people bash Microsoft daily for tying the GUI layer to the kernel, Apple seems to get away with it scot-free. I don't know if it's caused by my external display hooked up to the dock, or the Prolific Firewire chip in my external disk enclosure but something causes the mysterious "music plays till the end of the song, mouse can be moved, but nothing works" bug now and then and all I can do is a hard reset.

    + + +

    On Linux I currently use Fluxbox so everything is rock solid and fast (except Firefox! ;-), but in the extremely rare event that shit does hit the fan usually only a single app will crash, though sometimes X (and hence many others) go with it. A sudo /etc/init.d/gdm restart fixes that. The only times I've had to hard reset Linux was because of a random bug (strangely similar to my MacBook bug) with Nvidia's driver with dual head setups. All this is pretty moot since Linux is generally just stable.

    + + +

    Those are 2 relatively small things but the added comfort they provide is very nice.

    + + +

    In the spirit of switching things up I'm going to forgo my usual routine of using gvim on Linux and try out emacs. I've been frustrated with vim's lack of a decent file browser and I've never much liked the tree plugin. Vim is a fantastic editor when it comes to navigating, slicing, and dicing text. After that it sort of falls flat though. After getting hooked on TextMate I have come to love integration with all sorts of external apps such as Subversion, rake, and the shell because it makes my work easier. Emacs seems to embrace that sort of philosophy and I'm more impressed with the efforts to integrate Rails development into Emacs than vim. I'm typing this post using the Textile mode for Emacs and the markup is rendered giving me a live preview of my post. It's not WYSIWYG like Typo's preview but it's still pretty damn cool. I think can get used to emacs.

    + + +

    I'm just waiting for a bunch of crap to compile - because I use Gentoo - and soon I'll have a Gtk-enabled Emacs to work in. If I can paste to and from Firefox then I'll be happy. I'll have to open this in vim or gedit to paste it into Firefox, funny!

    + + +

    I'm also going to try replacing a couple of desktop apps with web alternatives. I'm starting with 2 no-brainers: mail and feeds with Gmail and Google Reader. I never got into the Gmail craze and never really even used Gmail very much. After looking at the shortcuts I think I can get used to it. Seeing j/k for up/down is always nice. Thunderbird is ok but there isn't a mail client on Linux that I really like, except mutt. That played a part in my Gmail choice. I hadn't used G-Reader before either and it seems alright, but it'll be hard to beat NetNewsWire.

    + +
    + +
    + +
    +

    + Begging the question + + 0 + +

    +
    + Posted by sjs +
    +on Friday, June 15 +
    +
    +

    I'm currently reading SICP since it's highly recommended by many people, available for free, and interesting. The fact that I have a little Scheme interpreter to play with makes it much more fun since I can add missing functionality to it as I progress through the book, thereby learning more Haskell in the process. Yay!

    + + +

    Anyway I was very pleased to see the only correct usage of the phrase "begs the question" I have seen in a while. It's a pet peeve of mine, but I have submitted myself to the fact that the phrase is so oft used to mean "begs for the following question to be asked..." that it may as well be re-defined. In its correct usage the sentence seems to hang there if you try to apply the commonly mistaken meaning to it. That's all very hazy so here's the usage in SICP (emphasis my own):

    + + +
    As a case in point, consider the problem of computing square roots. We can define the square-root function as + +

    This describes a perfectly legitimate mathematical function. We could use it to recognize whether one number is the square root of another, or to derive facts about square roots in general. On the other hand, the definition does not describe a procedure. Indeed, it tells us almost nothing about how to actually find the square root of a given number. It will not help matters to rephrase this definition in pseudo-Lisp:

    + + +
    (define (sqrt x)
    +  (the y (and (>= y 0)
    +              (= (square y) x))))
    + +This only begs the question. +
    + +

    Begging the question is to assume what one is trying to prove (or here, define) and use that as the basis for a conclusion. Read the Wikipedia article for a better definition and some nice examples.

    + +
    + +
    + +
    +

    + test/spec on rails declared awesome, just one catch + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, June 14 +
    +
    +

    This last week I've been getting to know test/spec via err's test/spec on rails plugin. I have to say that I really dig this method of testing my code and I look forward to trying out some actual BDD in the future.

    + + +

    I did hit a little snag with functional testing though. The method of declaring which controller to use takes the form:

    + + + + + +
    
    +
    use_controller :foo
    + + +

    and can be placed in the setup method, like so:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    # in test/functional/sessions_controller_test.rb
    +
    +context "A guest" do
    +  fixtures :users
    +
    +  setup do
    +    use_controller :sessions
    +  end
    +
    +  specify "can login" do
    +    post :create, :username => 'sjs', :password => 'blah'
    +    response.should.redirect_to user_url(users(:sjs))
    +    ...
    +  end
    +end
    + + +

    This is great and the test will work. But let's say that I have another controller that guests can access:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +
    # in test/functional/foo_controller_test.rb
    +
    +context "A guest" do
    +  setup do
    +    use_controller :foo
    +  end
    +
    +  specify "can do foo stuff" do
    +    get :fooriffic
    +    status.should.be :success
    +    ...
    +  end
    +end
    + + +

    This test will pass on its own as well, which is what really tripped me up. When I ran my tests individually as I wrote them, they passed. When I ran rake test:functionals this morning and saw over a dozen failures and errors I was pretty alarmed. Then I looked at the errors and was thoroughly confused. Of course the action fooriffic can't be found in SessionsController, it lives in FooController and that's the controller I said to use! What gives?!

    + + +

    The problem is that test/spec only creates one context with a specific name, and re-uses that context on subsequent tests using the same context name. The various setup methods are all added to a list and each one is executed, not just the one in the same context block as the specs. I can see how that's useful, but for me right now it's just a hinderance as I'd have to uniquely name each context. "Another guest" just looks strange in a file by itself, and I want my tests to work with my brain not against it.

    + + +

    My solution was to just create a new context each time and re-use nothing. Only 2 lines in test/spec need to be changed to achieve this, but I'm not sure if what I'm doing is a bad idea. My tests pass and right now that's basically all I care about though.

    + +
    + +
    + +
    +

    + More Scheming with Haskell + + 2 + +

    +
    + Posted by sjs +
    +on Thursday, June 14 +
    +
    +

    It's been a little while since I wrote about Haskell and the Scheme interpreter I've been using to learn and play with both Haskell and Scheme. I finished the tutorial and got myself a working Scheme interpreter and indeed it has been fun to use it for trying out little things now and then. (Normally I would use Emacs or Dr. Scheme for that sort of thing.) There certainly are interesting things to try floating around da intranet. And also things to read and learn from, such as misp (via Moonbase).

    + + +

    I'm going to describe two new features of my Scheme in this post. The second one is more interesting and was more fun to implement (cond).

    + + +

    Parsing Scheme integers

    + + +

    Last time I left off at parsing R5RS compliant numbers, which is exercise 3.3.4 if you're following along the tutorial. Only integers in binary, octal, decimal, and hexadecimal are parsed right now. The syntaxes for those are #b101010, #o52, 42 (or #d42), and #x2a, respectively. To parse these we use the readOct, readDec, readHex, and readInt functions provided by the Numeric module, and import them thusly:

    + + +
    import Numeric (readOct, readDec, readHex, readInt)
    + +

    In order to parse binary digits we need to write a few short functions to help us out. For some reason I couldn't find binDigit, isBinDigit and readBin in their respective modules but luckily they're trivial to implement. The first two are self-explanatory, as is the third if you look at the implementation of its relatives for larger bases. In a nutshell readBin says to: "read an integer in base 2, validating digits with isBinDigit."

    + + +
    -- parse a binary digit, analagous to decDigit, octDigit, hexDigit
    +binDigit :: Parser Char
    +binDigit = oneOf "01" 
    +
    +-- analogous to isDigit, isOctdigit, isHexDigit
    +isBinDigit :: Char -> Bool
    +isBinDigit c = (c == '0' || c == '1')
    +
    +-- analogous to readDec, readOct, readHex
    +readBin :: (Integral a) => ReadS a
    +readBin = readInt 2 isBinDigit digitToInt
    + +

    The next step is to augment parseNumber so that it can handle R5RS numbers in addition to regular decimal numbers. To refresh, the tutorial's parseNumber function looks like this:

    + + +
    parseNumber :: Parser LispVal
    +parseNumber = liftM (Number . read) $ many1 digit
    + +

    Three more lines in this function will give us a decent starting point:

    + + +
    parseNumber = do char '#'
    +                 base <- oneOf "bdox" 
    +                 parseDigits base
    +           <|> (many1 digit >>= return . Number . read)
    + +

    Translation: First look for an R5RS style base, and if found call parseDigits with the given base to do the dirty work. If that fails then fall back to parsing a boring old string of decimal digits.

    + + +

    That brings us to actually parsing the numbers. parseDigits is simple, but there might be a more Haskell-y way of doing this.

    + + +
    -- Parse a string of digits in the given base.
    +parseDigits :: Char -> Parser LispVal
    +parseDigits base = do digits <- many1 d
    +                      return . Number . fst . head . f $ digits
    +                      where f = case base of
    +                                  'b' -> readBin
    +                                  'd' -> readDec
    +                                  'o' -> readOct
    +                                  'x' -> readHex
    +                            d = case base of
    +                                  'b' -> binDigit
    +                                  'd' -> digit
    +                                  'o' -> octDigit
    +                                  'x' -> hexDigit
    + +

    The trickiest part of all this was figuring out how to use the various readFoo functions properly. They return a list of pairs so head grabs the first pair and fst grabs the first element of the pair. Once I had that straight it was smooth sailing. Having done this, parsing R5RS characters (#\a, #\Z, #\?, ...) is a breeze so I won't bore you with that.

    + + +

    The cond function

    + + +

    It still takes me some time to knit together meaningful Haskell statements. Tonight I spent said time cobbling together an implementation of cond as a new special form. Have a look at the code. The explanation follows.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +
    eval env (List (Atom "cond" : List (Atom "else" : exprs) : [])) =
    +    liftM last $ mapM (eval env) exprs
    +eval env (List (Atom "cond" : List (pred : conseq) : rest)) = 
    +    do result <- eval env $ pred
    +       case result of
    +         Bool False -> case rest of
    +                         [] -> return $ List []
    +                         _ -> eval env $ List (Atom "cond" : rest)
    +         _ -> liftM last $ mapM (eval env) conseq
    + + +
      +
    • Lines 1-2: Handle else clauses by evaluating the given expression(s), returning the last result. It must come first or it's overlapped by the next pattern.
    • +
    • Line 3: Evaluate a cond by splitting the first condition into predicate and consequence, tuck the remaining conditions into rest for later.
    • +
    • Line 4: Evaluate pred
    • +
    • Line 5: and if the result is:
    • +
    • Line 6: #f then look at the rest of the conditions.
    • +
    • Line 7: If there are no more conditions return the empty list.
    • +
    • Line 8: Otherwise call ourselves recursively with the remaining conditions.
    • +
    • Line 9: Anything other than #f is considered true and causes conseq to be evaluated and returned. Like else, conseq can be a sequence of expressions.
    • +
    + + +

    So far my Scheme weighs in at 621 lines, 200 more than the tutorial's final code listing. Hopefully I'll keep adding things on my TODO list and it will grow a little bit more. Now that I have cond it will be more fun to expand my stdlib.scm as well.

    + +
    + +
    + +
    +

    + so long typo (and thanks for all the timeouts) + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, June 09 +
    +
    +

    Well for just over a year Typo ran the show. I thought I had worked out most of the kinks with Typo and Dreamhost but the latest problem I ran into was pretty major. I couldn't post new articles. If the stars aligned perfectly and I sacrificed baby animals and virgins, every now and then I could get it to work. Ok, all I really had to do was refresh several dozen times, waiting 1 minute for it to timeout every time, but it sucked nonetheless.

    + + +

    Recently I had looked at converting Typo to Mephisto and it seemed pretty painless. I installed Mephisto and followed whatever instructions I found via Google and it all just worked, with one caveat. The Typo converter for Mephisto only supports Typo's schema version 56, while my Typo schema was at version 61. Rather than migrate backwards I brought Mephisto's Typo converter up to date instead. If you're interested, download the patch. The patch is relative to vendor/plugins, so patch accordingly.

    + + +

    After running that code snippet to fix my tags, I decided to completely ditch categories in favour of tags. I tagged each new Mephisto article with a tag for each Typo category it had previously belonged to. I fired up RAILS_ENV=production script/console and typed something similar to the following:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    require 'converters/base'
    +require 'converters/typo'
    +articles = Typo::Article.find(:all).map {|a| [a, Article.find_by_permalink(a.permalink)] }
    +articles.each do |ta, ma|
    +  next if ma.nil?
    +  ma.tags << Tag.find_or_create(ta.categories.map(&:name))
    +end
    + + +

    When I say something similar I mean exactly that. I just typed that from memory so it may not work, or even be syntactically correct. If any permalinks changed then you'll have to manually add new tags corresponding to old Typo categories. The only case where this bit me was when I had edited the title of an article, in which case the new Mephisto permalink matched the new title while the Typo permalink matched the initial title, whatever it was.

    + + +

    I really dig Mephisto so far. It's snappier than Typo and the admin interface is slick. I followed the herd and went with the scribbish theme. Perhaps I'll get around to customizing it sometime, but who knows maybe I'll like a white background for a change.

    + +
    + +
    + +
    +

    + 301 moved permanently + + 1 + +

    +
    + Posted by sjs +
    +on Saturday, June 09 +
    +
    +

    Last weekend I moved out of the apartment I lived in for the last 3 1/2 years. Moving was a cinch thanks to a friend's garage, conveniently placed smack between my old place and the new one. Google maps tells me that I moved just under 3.4 km, which is 2.1 mi for the metric impaired, so it wasn't much of a move at all! My roommate and I live in the basement of a house split into 3 apartments. Our upstairs neighbours are friendly and seem pretty cool, except one lady upstairs seems a bit strange. It's a great place though and in the winter the wood stove fireplace is going to be awesome.

    + +
    + +
    + +
    +

    + Finnish court rules CSS ineffective at protecting DVDs + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, May 26 +
    +
    +

    It's nice to see people making sane calls on issues like this. Ars has a nice summary and there's also a press release.

    + +
    + +
    + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/2007.08.11-sjs - geeky ramblings.html b/wayback/@done/2007.08.11-sjs - geeky ramblings.html new file mode 100644 index 0000000..2fe50be --- /dev/null +++ b/wayback/@done/2007.08.11-sjs - geeky ramblings.html @@ -0,0 +1,1419 @@ + + + + sjs - geeky ramblings + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + +
    +

    + Cheat from Emacs + + 4 + +

    +
    + Posted by sjs +
    +on Friday, August 10 +
    +
    +

    Update: I had inadvertently used string-join, a function provided by something in my ~/.emacs.d. The script has been updated to work with a vanilla Emacs (23, but should work with 22 as well).

    + + +

    Update #2 [2007/08/10]: Editing cheats and diffs have been implemented.

    + + +

    We all know and love cheat. Now you can cheat without leaving Emacs (and without using a shell in Emacs).

    + + +

    Just save cheat.el in ~/.emacs.d and then (require 'cheat) in your ~/.emacs. I also bind C-z C-c to cheat, you may want to do something similar.

    + + +

    You can't do everything you can do with cheat on the command line yet, and for most of the commands the cheat command itself is used. Now you can do everything the command line client does from within Emacs, though you may need to revert to using cheat-command (described below).

    + + +

    Here's the rundown:

    + + +
      +
    • cheat - Lookup a cheat sheet interactively (cheat <name>)
    • +
    • cheat-sheets - List all cheat sheets (cheat sheets)
    • +
    • cheat-recent - List recently added cheat sheets (cheat recent)
    • +
    • cheat-versions - List versions of a cheat sheet interactively (cheat <name> --versions)
    • +
    • cheat-clear-cache - Clear a cached sheet interactively, clear them all if no name is given. (cheat --clear-cache [<name>])
    • +
    • cheat-add-current-buffer - Add a new cheat using the specified name and the contents of the current buffer as the body. (cheat <name> --add)
    • +
    • cheat-edit - Retrieve a fresh copy of the named cheat and display the body in a buffer for editing.
    • +
    • cheat-save-current-buffer - Save the current cheat buffer, which should be named *cheat-<name>*.
    • +
    • cheat-diff - Show the diff between the current version and the given version of the named cheat. If the version given is of the form m:n then show the diff between versions m and n. (cheat <name> --diff <version>)
    • +
    • cheat-command - Pass any arguments you want to cheat interactively.
    • +
    + + +

    (Added) I may add support for --diff and --edit in the future.

    + + +

    Please do send me your patches so everyone can benefit from them.

    + +
    + +
    + +
    +

    + Snap, crunchle, pop + + 1 + +

    +
    + Posted by sjs +
    +on Thursday, August 09 +
    +
    +

    I think that every now and then we need to be reminded of the frail nature of our human bodies. Yesterday morning as I walked to my kitchen I was turning right by pivoting on my right foot when my 24 years of walking experience suddenly failed me. I clearly did something wrong, as I heard a crunching pop or two in my right ankle and went down. Luckily it's just a sprain but my foot is fairly bruised and still sore today. I'm trying to follow the RICE method for recuperating but one can only lay down for so long before having to eat, work, use the bathroom, etc. Thank goodness I don't work on my feet or I'd be out of commission. If it still hurts next week I'm going to see a doctor but till then I'm trying not to leave my house. The idea of hopping and hobbling to a bus to go to a doctor does not thrill me in the slightest.

    + + +

    Oh, if you find yourself in a bind an upside down hockey stick is a decent makeshift crutch. You'll need 2 hands to operate the thing though.

    + + +

    At the opposite end of the spectrum there are times when we seem to be amazingly resilient creatures. Check out a documentary called "101 Things Removed from the Human Head" if you can find it anywhere. One of those things was a boat anchor, I kid you not.

    + +
    + +
    + +
    +

    + ElSchemo: Boolean logic and branching + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, August 02 +
    +
    +

    Well it has been a while since my last post. I'll try not to do that +frequently. Anyhow, on to the good stuff.

    + + +

    I've been developing a Scheme +interpreter in Haskell called +ElSchemo. +It started from Jonathan's excellent Haskell +tutorial +which I followed in order to learn both Haskell and Scheme. Basically +that means the code here is for me to get some feedback as much +as to show others how to do this kind of stuff. This may not be too +interesting if you haven't at least browsed the tutorial.

    + + +

    I'm going to cover 3 new special forms: and, or, and cond. I +promised to cover the let family of special forms this time around +but methinks this is long enough as it is. My sincere apologies if +you've been waiting for those.

    + + + +
    + +
    + +
    +

    + people + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, July 12 +
    +
    +

    Sometimes this is difficult to remember for someone who (likes to think that he) thinks somewhat logically.

    + + +
    +

    When dealing with people, let us remember that we are not dealing with creatures of logic. We are dealing with creatures of emotion, creatures bristling with prejudices and motivated by pride and vanity.

    +
    + + +

    Dale Carnegie, How to Win Friends and Influence People

    + +
    + +
    + +
    +

    + See your regular expressions in Emacs + + 0 + +

    +
    + Posted by sjs +
    +on Friday, July 06 +
    +
    +

    First, if you are an Emacs newbie then be sure to read (at least) the introduction of Being Productive with Emacs. For some reason the PDF and HTML versions are slightly similar.

    + + +

    Anyway, it mentions re-builder which is an awesome little gem if you use regular expressions at all1. What this baby does is open a small window at the bottom of your screen in which you can type a regex. It is parsed as you type it and matches are highlighted in the other window. Genius.

    + + +

    [1] If you don't use them I encourage you to "learn them"http://regex.info/. Don't pay any attention to Jamie Zawinsky and his lack of appreciation for a fantastic tool.

    + +
    + +
    + +
    +

    + RushCheck: QuickCheck for Ruby + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, July 05 +
    +
    +

    I cannot wait to try out RushCheck. It is QuickCheck for Ruby. I don't have experience with QuickCheck or anything but it's clear to see how this helps you make certain your code is robust.

    + +
    + +
    + +
    +

    + A TextMate tip for Emacs users + + 0 + +

    +
    + Posted by sjs +
    +on Tuesday, July 03 +
    +
    +

    Update: The only place I've seen this mentioned is in a comment on the MacroMates blog.

    + + +

    My Linux box is down due to a hardware failure; a cheap SATA controller to be specific. Perhaps that will be a story for another day. As a result I've been working on my MacBook and back in TextMate. Old habits. And I haven't gotten comfortable in any of the OS X Emacsen yet.

    + + +

    This gave me an opportunity to accidentally discover some shortcuts in TextMate. A result of the Emacs shortcuts that my fingers are already wired to, here are some TextMate keyboard shortcuts that may or may not be documented (I need to RTFM some day).

    + + +
      +
    • As in most Cocoa text areas, C-f, C-b, C-n, C-p, C-a, C-e, and C-t work as expected (and others I'm sure).
    • +
    • C-k: behaves as a vanilla Emacs, killing till a newline or killing a bare newline. I use the word killing specifically because you can yank it back with...
    • +
    • C-y: yanks back the last thing on the kill ring (paste history). You still have to use C-S-v to yank previous items.
    • +
    + + +

    I think TextMate may have helped ease me into Emacs without me even knowing. I had my suspicions that Allan was an Emacs fan and now I'm certain of it. I keep finding things in one that the other has, which makes switching between them easy. Well done Allan.

    + +
    + +
    + +
    +

    + Controlling volume via the keyboard on Linux + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, June 30 +
    +
    +

    I was using Amarok's global keyboard shortcuts to control the volume of my music via the keyboard but I wanted to control the system volume as well. A quick script later and now I can control both, and thanks to libnotify I get some feedback on what happened. It's not as pretty as OS X's volume control or Growl but it'll certainly do.

    + + +

    ↓ Download volume.rb

    + + +

    I save this as ~/bin/volume and call it thusly: volume + and volume -. I bind Alt-+ and Alt—to those in my fluxbox config. If you don't have a preferred key binding program I recommend trying xbindkeys. apt-get install, emerge, paludis -i, or rpm -i as needed.

    + +
    + +
    + +
    +

    + Recent Ruby and Rails Regales + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, June 28 +
    +
    +

    Some cool Ruby and [the former on] Rails things are springing up and I haven't written much about the two Rs lately, though I work with them daily.

    + + +

    Rails on Rules

    + + +

    My friend Jim Roepcke is researching and implementing a plugin/framework designed to work with Rails called Rails on Rules. His inspiration is the rule system from WebObjects' Direct to Web. He posted a good example for me, but this baby isn't just for template/view logic. If some of the Rails conventions were specified in a default set of rules which the developer could further customize then you basically have a nice way of doing things that you would otherwise code by hand. I think it would be a boon for the ActiveScaffold project. We're meeting up to talk about this soon and I'll have more to say after then, but it sounds pretty cool.

    + + +

    Sake Bomb!

    + + +

    I've noticed a trend among some recent posts about Rake: the authors keep talking about booze. Are we nothing but a bunch of booze hounds?! Well one can hope. There's some motivation to learn more about a tool, having more time to drink after work. This week Chris Wanstrath dropped a Sake Bomb on the Ruby community. Like piston, sake is something you can just pick up and use instantly. Interestingly the different pronunciations of rake and sake help me from confusing the two on the command line... so far.

    + + +

    Secure Associations (for Rails)

    + + +

    Jordan McKible released the secure_associations plugin. It lets you protect your models' *_id attributes from mass-assignment via belongs_to_protected and has_many_protected. It's a mild enhancement, but an enhancement nonetheless. This is useful to enough people that it should be in Rails proper.

    + + +

    Regular expressions and strings with embedded objects

    + + +

    taw taught me a new technique for simplifying regular expressions by transforming the text in a reversible manner. In one example he replaced literal strings in SQL - which are easily parsed via a regex - with what he calls embedded objects. They're just tokens to identify the temporarily removed strings, but the important thing is that they don't interfere with the regexes that operate on the other parts of the SQL, which would have been very difficult to get right with the strings inside it. If I made it sound complicated just read the post, he explains it well.

    + + +

    If you believe anything Steve Yegge says then that last regex trick may come in handy for Q&D parsing in any language, be it Ruby, NBL, or whataver.

    + +
    + +
    + +
    +

    + Emacs: tagify-region-or-insert-tag + + 1 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    After axing half of wrap-region.el I renamed it to tagify.el and improved it ever so slightly. It's leaner, and does more!

    + + +

    tagify-region-or-insert-tag does the same thing as wrap-region-with-tag except if there is no region it now inserts the opening and closing tags and sets point in between them. I have this bound to C-z t, as I use C-z as my personal command prefix.

    + + +

    < is bound to tagify-region-or-insert-self which really doesn't warrant an explanation.

    + +
    + +
    + +
    +

    + RTFM! + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    I should read the Emacs manual sometime, especially since I have it in dead-tree form. Check out skeleton pairs in the Emacs manual, or better yet C-h f skeleton-pair-insert-maybe. skeleton-pair has already been massaged to do what you most likely want if you set the correct options. Cool. I like Emacs more every day.

    + + +

    This renders wrap-region useless, which is great! I like a trim .emacs and .emacs.d.

    + +
    + +
    + +
    +

    + Propaganda makes me sick + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    Things like this in modern times are surprising. Can't people spot this phony crap for what it is?

    + + +

    First they put away the dealers, keep our kids safe and off the streets
    +Then they put away the prostitutes, keep married men cloistered at home
    +Then they shooed away the bums, and they beat and bashed the queers
    +Turned away asylum-seekers, fed us suspicions and fears
    +We didn't raise our voice, we didn't make a fuss
    +It´s funny there was no one left to notice, when they came for us
    +
    +Looks like witches are in season, you better fly your flag and be aware
    +Of anyone who might fit the description, diversity is now our biggest fear
    +Now with our conversations tapped, and our differences exposed
    +How ya supposed to love your neighbour, with our minds and curtains +closed?
    +We used to worry ‘bout big brother
    +Now we got a big father and an even bigger mother

    +
    +And still you believe, this aristocracy gives a fuck about you
    +They put the mock in democracy, and you swallowed every hook
    +The sad truth is, you'd rather follow the school into the net
    +‘Cause swimming alone at sea, is not the kind of freedom that you +actually want
    +So go back to your crib, and suck on a tit
    +Bask in the warmth of your diaper, you're sitting in shit
    +And piss, while sucking on a giant pacifier
    +A country of adult infants, a legion of mental midgets
    +A country of adult infants, a country of adult infants
    +All regaining their unconsciousness
    +
    +—from the song Regaining Unconsciousness, by NOFX

    + +
    + +
    + +
    +

    + Floating point in ElSchemo + + 0 + +

    +
    + Posted by sjs +
    +on Sunday, June 24 +
    +
    +

    Update: I've cleaned the code up a little bit by having LispNum derive Eq, Ord and Show.

    + + +

    NB: My Scheme interpreter is based on Jonathan Tang's Write Yourself a Scheme in 48 hours Haskell tutorial. Not all of this makes sense outside that context, and the context of my previous posts on the subject.

    + + +

    My scheme interpreter has been christened ElSchemo, since it was sorely in need of a better name than "my Scheme interpreter". It's also seen far too much of my time and sports jazzy new features. I'll probably post the full code up here sooner or later, including my stdlib.scm and misp slightly modified to run with ElSchemo's limited vocabulary (namely the lack of define-syntax).

    + + +

    But that will be for another day, because today I want to talk about implementing floating point numbers, from parsing to operating on them.

    + + + +
    + +
    + +
    +

    + Emacs for TextMate junkies + + 6 + +

    +
    + Posted by sjs +
    +on Saturday, June 23 +
    +
    +

    Update #1: What I first posted will take out your < key by mistake (it's available via C-q <), it has since been revised to Do The Right Thing.

    + + +

    Update #2: Thanks to an anonymouse[sic] commenter this code is a little cleaner.

    + + +

    Update #3: I should read the Emacs manual sometime, especially since I have it in dead-tree form. Check out skeleton pairs in the Emacs manual.

    + + +

    Despite my current infatuation with Emacs there are many reasons I started using TextMate, especially little time-savers that are very addictive. I'll talk about one of those features tonight. When you have text selected in TextMate and you hit say the ' (single quote) then TextMate will surround the selected text with single quotes. The same goes for double quotes, parentheses, brackets, and braces. This little trick is one of my favourites so I had to come up with something similar in Emacs. It was easy since a mailing list post has a solution for surrounding the current region with tags, which served as a great starting point.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    (defun surround-region-with-tag (tag-name beg end)
    +      (interactive "sTag name: \nr")
    +      (save-excursion
    +        (goto-char beg)
    +        (insert "<" tag-name ">")
    +        (goto-char (+ end 2 (length tag-name)))
    +        (insert "</" tag-name ">")))
    + + +

    With a little modification I now have the following in my ~/.emacs file:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +
    ;; help out a TextMate junkie
    +
    +(defun wrap-region (left right beg end)
    +  "Wrap the region in arbitrary text, LEFT goes to the left and RIGHT goes to the right."
    +  (interactive)
    +  (save-excursion
    +    (goto-char beg)
    +    (insert left)
    +    (goto-char (+ end (length left)))
    +    (insert right)))
    +
    +(defmacro wrap-region-with-function (left right)
    +  "Returns a function which, when called, will interactively `wrap-region-or-insert' using LEFT and RIGHT."
    +  `(lambda () (interactive)
    +     (wrap-region-or-insert ,left ,right)))
    +
    +(defun wrap-region-with-tag-or-insert ()
    +  (interactive)
    +  (if (and mark-active transient-mark-mode)
    +      (call-interactively 'wrap-region-with-tag)
    +    (insert "<")))
    +
    +(defun wrap-region-with-tag (tag beg end)
    +  "Wrap the region in the given HTML/XML tag using `wrap-region'. If any
    +attributes are specified then they are only included in the opening tag."
    +  (interactive "*sTag (including attributes): \nr")
    +  (let* ((elems    (split-string tag " "))
    +         (tag-name (car elems))
    +         (right    (concat "</" tag-name ">")))
    +    (if (= 1 (length elems))
    +        (wrap-region (concat "<" tag-name ">") right beg end)
    +      (wrap-region (concat "<" tag ">") right beg end))))
    +
    +(defun wrap-region-or-insert (left right)
    +  "Wrap the region with `wrap-region' if an active region is marked, otherwise insert LEFT at point."
    +  (interactive)
    +  (if (and mark-active transient-mark-mode)
    +      (wrap-region left right (region-beginning) (region-end))
    +    (insert left)))
    +
    +(global-set-key "'"  (wrap-region-with-function "'" "'"))
    +(global-set-key "\"" (wrap-region-with-function "\"" "\""))
    +(global-set-key "`"  (wrap-region-with-function "`" "`"))
    +(global-set-key "("  (wrap-region-with-function "(" ")"))
    +(global-set-key "["  (wrap-region-with-function "[" "]"))
    +(global-set-key "{"  (wrap-region-with-function "{" "}"))
    +(global-set-key "<"  'wrap-region-with-tag-or-insert) ;; I opted not to have a wrap-with-angle-brackets
    + + +

    Download wrap-region.el

    + + +

    That more or less sums up why I like Emacs so much. I wanted that functionality so I implemented it (barely! It was basically done for me), debugged it by immediately evaluating sexps and then trying it out, and then once it worked I reloaded my config and used the wanted feature. That's just awesome, and shows one strength of open source.

    + +
    + +
    + +
    +

    + Embrace the database + + 0 + +

    +
    + Posted by sjs +
    +on Friday, June 22 +
    +
    +

    If you drink the Rails koolaid you may have read the notorious single layer of cleverness post by DHH. [5th post on the archive page] In a nutshell he states that it's better to have a single point of cleverness when it comes to business logic. The reasons for this include staying agile, staying in Ruby all the time, and being able to switch the back-end DB at any time. Put the logic in ActiveRecord and use the DB as a dumb data store, that is the Rails way. It's simple. It works. You don't need to be a DBA to be a Rails developer.

    + + +

    Stephen created a Rails plugin called dependent-raise which imitates a foreign key constraint inside of Rails. I want to try this out because I believe that data integrity is fairly important, but it's really starting to make me think about this single point of cleverness idea.

    + + +

    Are we not reinventing the wheel by employing methods such as this in our code? Capable DBs already do this sort of thing for us. I don't necessarily think it's bad to implement this sort of thing, but I think it's a symptom of NIH syndrome. Instead of reinventing this kind of thing why don't we embrace the DB as a semi-intelligent data store? The work has been done all we have to do is exploit it via Rails.

    + + +

    There are a few reasons that the Rails folks choose not to do so but perhaps some of them could be worked around. Adapting your solution as you progress and realise that things aren't exactly as you thought they were... I believe the word for that sort of thing is agility.

    + + +

    Database agnosticism

    + + +

    From SQLite to Oracle, just configure the connection, migrate, and run your app on any database. One of the biggest Rails myths that is backed by the Rails team themselves. It takes a fair amount of work to ensure that any significant app is fully agnostic. Sure you can develop on SQLite and deploy on MySQL without much trouble but there are significant diffirences between RDBMSs that will manifest themselves if you create an app that's more than a toy. Oh, you used finder_sql? Sorry but chances are your app is no longer DB agnostic. FAIL.

    + + +

    Solution: Drop the lie. Tell people the truth. Theoretically, theory and practice are the same; in practice they are not. Be honest that it's possible to be DB-agnostic but can be a challenge. Under no circumstances should we shun something useful in the name of claiming to be DB-agnostic.

    + + +

    Staying agile

    + + +

    If we start making use of FK constraints then we'll have to make changes to both our DB and our code. This makes change more time-consuming and error-prone which means change is less likely to happen. This goes against the grain of an agile methodology. Or does it?

    + + +

    Solution: Rails should use the features of the DB to keep data intact and fall back on an AR-only solution only if the DB doesn't support the operation. There doesn't need to be any duplication in logic rules either. If Rails could recognise a FK constraint that cascades on delete it could set up the has_many :foos, :dependent => :destroy relation for us. In fact I only see our code becoming DRYer (maybe even too DRY[1]).

    + + +

    Staying in Ruby

    + + +

    Using the DB from within Ruby is a solved problem. I don't see why this couldn't be extended to handle more of the DB as well. Use Ruby, but use it intelligently by embracing outside tools to get the job done.

    + + +

    Many relationships could be derived from constraints as people have pointed out before. There are benefits to using the features of a decent RDBMS, and in some cases I think that we might be losing by not making use of them. I am not saying we should move everything to the DB, I am saying that we should exploit the implemented and debugged capabilities of our RDBMSs the best we can while practicing the agile methods we know and love, all from within Ruby.

    + + +

    [1] I make liberal use of annotate_models as it is.

    + +
    + +
    + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/2007.09.10-sjs - geeky ramblings.html b/wayback/@done/2007.09.10-sjs - geeky ramblings.html new file mode 100644 index 0000000..8b35212 --- /dev/null +++ b/wayback/@done/2007.09.10-sjs - geeky ramblings.html @@ -0,0 +1,1309 @@ + + + + sjs - geeky ramblings + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + +
    +

    + 5 ways to avoid looking like a jerk on the Internet + + 3 + +

    +
    + Posted by sjs +
    +on Thursday, August 30 +
    +
    +

    Let me begin by stating that these are tips I have gathered by posting in many public forums on the Internet and I have learned most of these rules by making the mistakes myself. I'm not trying to point fingers at anyone or act all holier-than-thou. It's a cold, emotionless medium text is. It can be difficult to accurately convey one's feelings when typing a quick reply somewhere. John Gabriel's theory certainly plays a part as well, but I'll try and assume that you are generally a nice person. I also assume that we are talking about a text medium (IRC, forums, Slashdot/Reddit/Digg). None of that fancy voice or video conferencing stuff!

    + + +

    Also, this is not a guide on how to really be an arrogant prick, but just not look like one when you engage in conversations on the Internet. It's also not a guide on not being a jerk. Should you lack basic manners you will have to learn them elsewhere.

    + + +

    Rule #1: Forget the medium

    + + +

    One thing that is quite difficult to do is look past the medium and remember that these are all real people conversing with each other. Don't type anything that you wouldn't say to their face in real life. This is, of course, not exclusive to the Internet.

    + + +

    Rule #2: Remember the medium!

    + + +

    While obeying Rule #1 it's important to remember that in a text medium there is no emotion or tone to our words. If you think that smilies / emoticons are lame and for 12 year olds, well you're right. However, there's no reason for an adult to refrain from using them as well. They can be important quick clues to how your message should be interpreted. You can always rephrase what you write so that there's little ambiguity to your words, but if you're typing something quickly on Digg, Reddit or some forum then you probably aren't spell checking and proof reading each and every post.

    + + +

    Rule #3: Avoid know-it-all responses

    + + +

    Starting a reply with "But ...", "Well ...", "No ...", or "Your mother's a ..." often sounds confrontational. There's obviously no harm in using these in the right context, but many times I have found that removing these from the front of a sentence can drastically alter the tone and make it clear that I am trying to converse rather than argue.

    + + +

    Rule #4: Address the correct party

    + + +

    If you're not speaking directly to the reader avoid using "you" when you mean "one". This is a particularly hard one to get in the habit of doing, for me at least. I am just not used to speaking so formally but in writing it really does make a world of difference. People are defensive creatures by nature and we don't like being singled out or accused. Hell, half of the time we don't even like honest, kind advice.

    + + +

    Rule #5: Accept the fact that people know more than you

    + + +

    Geeks often come across as know-it-alls. While most geeks probably do think they're rather clever (guilty as charged) they probably also know that they don't know everything. When one knows nothing of a topic it's easy to admit that others are right and they are wrong (often because they won't have an opinion on the subject yet). The trouble starts once they learn something about the matter, once they have formed opinions and ideas about it.

    + + +

    I'm not saying that we should all stop discussing things we're not experts on, just that we should try harder to keep open minds about things and realize that others may have some insight we do not. If in doubt, partake in civil discourse and try not to dismiss others without even asking them to back up their claims or ideas.

    + + +

    Cue the comments pointing out how many of these rules I broke in this very post... :)

    + +
    + +
    + +
    +

    + Captivating little creatures + + 0 + +

    +
    + Posted by sjs +
    +on Sunday, August 26 +
    +
    +

    Someone posted this JavaScript implementation of an old gem on Reddit, Lemmings! There goes my Sunday! :)

    + +
    + +
    + +
    +

    + Cheat productively in Emacs + + 0 + +

    +
    + Posted by sjs +
    +on Tuesday, August 21 +
    +
    +

    By now you may have heard about cheat, the command line cheat sheet collection that's completely open to editing, wiki style. A couple of weeks ago I posted cheat.el which allows one to cheat from within Emacs. There's an update. However, before I get to cheat.el there's a small detour.

    + + +

    Cheat is not just about Ruby! A few examples of cheats available are:

    + + +
      +
    • bash and zsh
    • +
    • $EDITOR (if you happen to like e, TextMate, vi, emacs, RadRails, ...)
    • +
    • GNU screen
    • +
    • Version control (darcs, svn, git)
    • +
    • Firebug
    • +
    • Markdown and Textile
    • +
    • Oracle and MySQL
    • +
    • Regular expressions
    • +
    • and of course Ruby, Rails, Capistrano, etc.
    • +
    + + +

    As of today, Aug-21 2007, the count is at 166 cheat sheets so there's probably something there that you'll want to look up from the command line or Emacs sometime. That's enough stroking cheat's ego, but there seems to be a notion that cheat is only for Ruby stuff and that's really not the case.

    + + +

    So what's new in this version of cheat.el? Completion! The only thing that bothered me about cheating in Emacs was the lack of completion. It now has completion, thus it is now perfect. :) In all likeliness this won't be the last release, but I can't really foresee adding anything else to it in the near future. Enjoy!

    + + +

    Download it now: cheat.el

    + + +

    For any newcomers, just drop this into ~/.emacs.d, ~/.elisp, or any directory in your load-path and then (require 'cheat). For more info check the original article for a rundown on the cheat commands.

    + +
    + +
    + +
    +

    + Catch compiler errors at runtime + + 0 + +

    +
    + Posted by sjs +
    +on Sunday, August 19 +
    +
    +

    While coding just now I had a small epiphany about Ruby. Though Ruby is highly dynamic and compiled at runtime, that doesn't preclude one catching some mistakes at compile time. I'm not talking about mere syntax errors or anything either. The only proviso to catching mistakes at compile time is that you must have a decent chunk of code executed during compilation. One benefit of Ruby's blurring of compile time and runtime is that you can run real code at compile time. This is largely how metaprogramming tricks are pulled off elegantly and with ease in projects such as Rails.

    + + +

    Sure you won't get all the benefits of a strictly and/or statically typed compiler, but you can get some of them. If you have a library that makes substantial use of executing code at compile time then the mere act of loading your library causes your code to run, thus it compiles. If you require your lib and get true back then you know the code that bootstraps the runtime code is at least partially correct.

    + + +

    Compile time is runtime. Runtime is compile time. Just because you have to run the code to compile it doesn't mean you can't catch a good chunk of compiler errors before you send out your code. Tests will always be there for the rest of your mistakes, but if you can pull work into compile time then Ruby's compiler can augment your regular testing practices.

    + + +

    I admit that this is of limited use most of the time, but let it not be said that you can't catch any errors with your compiler just because you have to run your code to compile it. With Ruby the more meta you get the more the compiler rewards you.

    + + +

    [Of course this is true of languages such as Common Lisp too, which make available the full programming language at compile time. I just happened to be using Ruby when I realized this.]

    + +
    + +
    + +
    +

    + Opera is pretty slick + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, August 11 +
    +
    +

    Though I usually prefer free software, I don't have any problems using proprietary stuff if I think it's good. I had Firefox open for a couple of days and noticed that it was using 700M of memory. That's not a problem at all since I have 4G but it's also a lot of RAM to be in use for just one window with one tab open. The fact that Firefox gets sluggish after some time and needs to be restarted tells me that this isn't expected behaviour and is likely not due to caching for quick back/forward or whatever they claim is taking up the leaked memory.

    + + +

    Konqueror is ok but I'm not a huge fan of it, partly due to its kitchen-sink browser/file manager hybrid design. IMO the KDE folks should break out the file manager part, but I digress. I can't really put my finger on anything specific I dislike about Konqueror, it's just not for me. To my dismay it seems to be the snappiest browser on Linux.

    + + +

    The only other decent browser I know of (for Linux) is Opera so I found some quick instructions on the Ubuntu forums and shoehorned the x86 build of it into my amd64 installation. Everything went well, Flash works and all that stuff. Opera is not nearly as snappy as I like but it is still fairly pleasant to use, once you find a skin that fits into your desktop. For the record Firefox isn't snappy enough either. Apart from AdBlock I don't miss many extensions for every day browsing.

    + + +

    I'm not sure if I'm going to stick with it yet but I've been using it for 2 days and haven't really missed Firefox at all. Of course as soon as I do any development I need Firefox for Firebug and the Web Developer extension and such. I've yet to investigate development tools on Opera. I'm comfortable developing in Firefox already so why switch?

    + + +

    Man am I glad we're not in a Netscape/IE world anymore! If I open up my MacBook I can choose from at least 2 other browsers for every day browsing (Camino, Safari).

    + +
    + +
    + +
    +

    + Cheat from Emacs + + 4 + +

    +
    + Posted by sjs +
    +on Friday, August 10 +
    +
    +

    Update: I had inadvertently used string-join, a function provided by something in my ~/.emacs.d. The script has been updated to work with a vanilla Emacs (23, but should work with 22 as well).

    + + +

    Update #2 [2007.08.10]: Editing cheats and diffs have been implemented.

    + + +

    Update #3 [2007.08.21]: I added completion to cheat.el. The file linked on this page is still the latest version.

    + + +

    We all know and love cheat. Now you can cheat without leaving Emacs (and without using a shell in Emacs).

    + + +

    Just save cheat.el in ~/.emacs.d and then (require 'cheat) in your ~/.emacs. I also bind C-z C-c to cheat, you may want to do something similar.

    + + +

    You can't do everything you can do with cheat on the command line yet, and for most of the commands the cheat command itself is used. Now you can do everything the command line client does from within Emacs, though you may need to revert to using cheat-command (described below).

    + + +

    Here's the rundown:

    + + +

    Any time you enter a cheat name there are both completion and a cheat-specific history available. Unless you are adding a new cheat. In that case you should use a new, unique name (duh).

    + + +
      +
    • cheat - Lookup a cheat sheet interactively (cheat <name>)
    • +
    • cheat-sheets - List all cheat sheets (cheat sheets)
    • +
    • cheat-recent - List recently added cheat sheets (cheat recent)
    • +
    • cheat-versions - List versions of a cheat sheet interactively (cheat <name> --versions)
    • +
    • cheat-clear-cache - Clear all cached sheets.
    • +
    • cheat-add-current-buffer - Add a new cheat using the specified name and the contents of the current buffer as the body. (cheat <name> --add)
    • +
    • cheat-edit - Retrieve a fresh copy of the named cheat and display the body in a buffer for editing.
    • +
    • cheat-save-current-buffer - Save the current cheat buffer, which should be named *cheat-<name>*.
    • +
    • cheat-diff - Show the diff between the current version and the given version of the named cheat. If the version given is of the form m:n then show the diff between versions m and n. (cheat <name> --diff <version>)
    • +
    • cheat-command - Pass any arguments you want to cheat interactively.
    • +
    + + +

    (Added) I may add support for --diff and --edit in the future.

    + + +

    Please do send me your patches so everyone can benefit from them.

    + +
    + +
    + +
    +

    + Snap, crunchle, pop + + 1 + +

    +
    + Posted by sjs +
    +on Thursday, August 09 +
    +
    +

    I think that every now and then we need to be reminded of the frail nature of our human bodies. Yesterday morning as I walked to my kitchen I was turning right by pivoting on my right foot when my 24 years of walking experience suddenly failed me. I clearly did something wrong, as I heard a crunching pop or two in my right ankle and went down. Luckily it's just a sprain but my foot is fairly bruised and still sore today. I'm trying to follow the RICE method for recuperating but one can only lay down for so long before having to eat, work, use the bathroom, etc. Thank goodness I don't work on my feet or I'd be out of commission. If it still hurts next week I'm going to see a doctor but till then I'm trying not to leave my house. The idea of hopping and hobbling to a bus to go to a doctor does not thrill me in the slightest.

    + + +

    Oh, if you find yourself in a bind an upside down hockey stick is a decent makeshift crutch. You'll need 2 hands to operate the thing though.

    + + +

    At the opposite end of the spectrum there are times when we seem to be amazingly resilient creatures. Check out a documentary called "101 Things Removed from the Human Head" if you can find it anywhere. One of those things was a boat anchor, I kid you not.

    + +
    + +
    + +
    +

    + ElSchemo: Boolean logic and branching + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, August 02 +
    +
    +

    Well it has been a while since my last post. I'll try not to do that +frequently. Anyhow, on to the good stuff.

    + + +

    I've been developing a Scheme +interpreter in Haskell called +ElSchemo. +It started from Jonathan's excellent Haskell +tutorial +which I followed in order to learn both Haskell and Scheme. Basically +that means the code here is for me to get some feedback as much +as to show others how to do this kind of stuff. This may not be too +interesting if you haven't at least browsed the tutorial.

    + + +

    I'm going to cover 3 new special forms: and, or, and cond. I +promised to cover the let family of special forms this time around +but methinks this is long enough as it is. My sincere apologies if +you've been waiting for those.

    + + + +
    + +
    + +
    +

    + people + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, July 12 +
    +
    +

    Sometimes this is difficult to remember for someone who (likes to think that he) thinks somewhat logically.

    + + +
    +

    When dealing with people, let us remember that we are not dealing with creatures of logic. We are dealing with creatures of emotion, creatures bristling with prejudices and motivated by pride and vanity.

    +
    + + +

    Dale Carnegie, How to Win Friends and Influence People

    + +
    + +
    + +
    +

    + See your regular expressions in Emacs + + 0 + +

    +
    + Posted by sjs +
    +on Friday, July 06 +
    +
    +

    First, if you are an Emacs newbie then be sure to read (at least) the introduction of Being Productive with Emacs. For some reason the PDF and HTML versions are slightly similar.

    + + +

    Anyway, it mentions re-builder which is an awesome little gem if you use regular expressions at all1. What this baby does is open a small window at the bottom of your screen in which you can type a regex. It is parsed as you type it and matches are highlighted in the other window. Genius.

    + + +

    [1] If you don't use them I encourage you to "learn them"http://regex.info/. Don't pay any attention to Jamie Zawinsky and his lack of appreciation for a fantastic tool.

    + +
    + +
    + +
    +

    + RushCheck: QuickCheck for Ruby + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, July 05 +
    +
    +

    I cannot wait to try out RushCheck. It is QuickCheck for Ruby. I don't have experience with QuickCheck or anything but it's clear to see how this helps you make certain your code is robust.

    + +
    + +
    + +
    +

    + A TextMate tip for Emacs users + + 0 + +

    +
    + Posted by sjs +
    +on Tuesday, July 03 +
    +
    +

    Update: The only place I've seen this mentioned is in a comment on the MacroMates blog.

    + + +

    My Linux box is down due to a hardware failure; a cheap SATA controller to be specific. Perhaps that will be a story for another day. As a result I've been working on my MacBook and back in TextMate. Old habits. And I haven't gotten comfortable in any of the OS X Emacsen yet.

    + + +

    This gave me an opportunity to accidentally discover some shortcuts in TextMate. A result of the Emacs shortcuts that my fingers are already wired to, here are some TextMate keyboard shortcuts that may or may not be documented (I need to RTFM some day).

    + + +
      +
    • As in most Cocoa text areas, C-f, C-b, C-n, C-p, C-a, C-e, and C-t work as expected (and others I'm sure).
    • +
    • C-k: behaves as a vanilla Emacs, killing till a newline or killing a bare newline. I use the word killing specifically because you can yank it back with...
    • +
    • C-y: yanks back the last thing on the kill ring (paste history). You still have to use C-S-v to yank previous items.
    • +
    + + +

    I think TextMate may have helped ease me into Emacs without me even knowing. I had my suspicions that Allan was an Emacs fan and now I'm certain of it. I keep finding things in one that the other has, which makes switching between them easy. Well done Allan.

    + +
    + +
    + +
    +

    + Controlling volume via the keyboard on Linux + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, June 30 +
    +
    +

    I was using Amarok's global keyboard shortcuts to control the volume of my music via the keyboard but I wanted to control the system volume as well. A quick script later and now I can control both, and thanks to libnotify I get some feedback on what happened. It's not as pretty as OS X's volume control or Growl but it'll certainly do.

    + + +

    ↓ Download volume.rb

    + + +

    I save this as ~/bin/volume and call it thusly: volume + and volume -. I bind Alt-+ and Alt—to those in my fluxbox config. If you don't have a preferred key binding program I recommend trying xbindkeys. apt-get install, emerge, paludis -i, or rpm -i as needed.

    + +
    + +
    + +
    +

    + Recent Ruby and Rails Regales + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, June 28 +
    +
    +

    Some cool Ruby and [the former on] Rails things are springing up and I haven't written much about the two Rs lately, though I work with them daily.

    + + +

    Rails on Rules

    + + +

    My friend Jim Roepcke is researching and implementing a plugin/framework designed to work with Rails called Rails on Rules. His inspiration is the rule system from WebObjects' Direct to Web. He posted a good example for me, but this baby isn't just for template/view logic. If some of the Rails conventions were specified in a default set of rules which the developer could further customize then you basically have a nice way of doing things that you would otherwise code by hand. I think it would be a boon for the ActiveScaffold project. We're meeting up to talk about this soon and I'll have more to say after then, but it sounds pretty cool.

    + + +

    Sake Bomb!

    + + +

    I've noticed a trend among some recent posts about Rake: the authors keep talking about booze. Are we nothing but a bunch of booze hounds?! Well one can hope. There's some motivation to learn more about a tool, having more time to drink after work. This week Chris Wanstrath dropped a Sake Bomb on the Ruby community. Like piston, sake is something you can just pick up and use instantly. Interestingly the different pronunciations of rake and sake help me from confusing the two on the command line... so far.

    + + +

    Secure Associations (for Rails)

    + + +

    Jordan McKible released the secure_associations plugin. It lets you protect your models' *_id attributes from mass-assignment via belongs_to_protected and has_many_protected. It's a mild enhancement, but an enhancement nonetheless. This is useful to enough people that it should be in Rails proper.

    + + +

    Regular expressions and strings with embedded objects

    + + +

    taw taught me a new technique for simplifying regular expressions by transforming the text in a reversible manner. In one example he replaced literal strings in SQL - which are easily parsed via a regex - with what he calls embedded objects. They're just tokens to identify the temporarily removed strings, but the important thing is that they don't interfere with the regexes that operate on the other parts of the SQL, which would have been very difficult to get right with the strings inside it. If I made it sound complicated just read the post, he explains it well.

    + + +

    If you believe anything Steve Yegge says then that last regex trick may come in handy for Q&D parsing in any language, be it Ruby, NBL, or whataver.

    + +
    + +
    + +
    +

    + Emacs: tagify-region-or-insert-tag + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    After axing half of wrap-region.el I renamed it to tagify.el and improved it ever so slightly. It's leaner, and does more!

    + + +

    tagify-region-or-insert-tag does the same thing as wrap-region-with-tag except if there is no region it now inserts the opening and closing tags and sets point in between them. I have this bound to C-z t, as I use C-z as my personal command prefix.

    + + +

    < is bound to tagify-region-or-insert-self which really doesn't warrant an explanation.

    + +
    + +
    + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/@first 3.html b/wayback/@done/@first 3.html new file mode 100644 index 0000000..d3c96d5 --- /dev/null +++ b/wayback/@done/@first 3.html @@ -0,0 +1,461 @@ + + + + sjs - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + May + + JUN + + SEP + +
    + + Previous capture + + 14 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 7 captures +
    14 Jun 06 - 7 Aug 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    +
    +

    Urban extreme gymnastics?

    +

    +on Wednesday, February 15, 2006

    +

    This crazy russian goes all over the place scaling buildings, doing all sorts of flips, bouncing off the walls literally. He'd be impossible to catch.

    + +

    Russian parkour (urban extreme gymnastics)

    + + +

    Posted in  | no comments | no trackbacks

    +
    +
    +

    Touch-screen on steroids

    +

    +on Wednesday, February 08, 2006

    +

    If you thought the PowerBook's two-finger scrolling was cool check out this touch screen:

    + + +
    +

    Multi-Touch Interaction Research

    +

    "While touch sensing is commonplace for single points of contact, multi-touch sensing enables a user to interact with a system with more than one finger at a time, as in chording and bi-manual operations. Such sensing devices are inherently also able to accommodate multiple users simultaneously, which is especially useful for larger interaction scenarios such as interactive walls and tabletops."

    +
    + +

    This is really amazing. Forget traditional tablet PCs... this is revolutionary and useful in so many applications. I hope this kind of technology is mainstream by 2015.

    + + +

    Posted in  | no comments | no trackbacks

    +
    +
    +

    first post!

    +

    +on Wednesday, February 08, 2006

    +

    so it's 2am and i should be asleep, but instead i'm setting up a blog. i got a new desk last night and so today i finally got my apartment re-arranged and it's much better now. that's it for now... time to sleep.

    + + +

    (speaking of sleep, this new sleeping bag design makes so much sense. awesome.)

    + + +

    Posted in  | no comments | no trackbacks

    +
    + + +

    Older posts: 1 2 3

    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Apple pays attention to detail - samhuri.net.html b/wayback/@done/Apple pays attention to detail - samhuri.net.html new file mode 100644 index 0000000..5b6be10 --- /dev/null +++ b/wayback/@done/Apple pays attention to detail - samhuri.net.html @@ -0,0 +1,542 @@ + + + + Apple pays attention to detail - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Apple pays attention to detail

    +

    + Sun, 11 Jun 2006 08:30:00 GMT

    +

    I think this has to be one of the big reasons why people who love their Mac, love their Mac (or other Apple product). I usually just have cheap PC speakers plugged into my Mac mini, but I didn’t bring any with me to Munich and the internal Mac mini speaker isn’t very loud, so I’m using headphones to watch movies. My Mac remembers the volume setting when the headphones ore plugged in, and when they’re not, so I don’t accidentally blow my ears. It’s like my iPod pausing when the headphones are unplugged. It’s excruciating attention to the smallest, (seemingly) most unimportant detail. I love it, and I’m hooked.

    +
    +

    + Posted in , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/426 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo - samhuri.net.html b/wayback/@done/Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo - samhuri.net.html new file mode 100644 index 0000000..8c783c9 --- /dev/null +++ b/wayback/@done/Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo - samhuri.net.html @@ -0,0 +1,545 @@ + + + + Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

    +

    + Sun, 17 Sep 2006 05:11:00 GMT

    +

    Wouldn’t the sentence ‘I want to put a hyphen between the words Fish and And and And and Chips in my Fish-And-Chips sign’ have been clearer if quotation marks had been placed before Fish, and between Fish and and, and and and And, and And and and, and and and And, and And and and, and and and Chips, as well as after Chips?

    + + +

    Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

    +
    +

    + Posted in  | Tags  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/437 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Class method Instance method It doesn't matter to PHP - samhuri.net.html b/wayback/@done/Class method Instance method It doesn't matter to PHP - samhuri.net.html new file mode 100644 index 0000000..1241391 --- /dev/null +++ b/wayback/@done/Class method Instance method It doesn't matter to PHP - samhuri.net.html @@ -0,0 +1,593 @@ + + + + Class method? Instance method? It doesn't matter to PHP - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Class method? Instance method? It doesn't matter to PHP

    +

    + Fri, 21 Jul 2006 14:56:00 GMT

    +

    Update: This has been discussed for PHP6. A little late, but I guess better than never.

    + + +

    I made a mistake while I was coding, for shame! Anyway this particular mistake was that I invoked a class method on the wrong class. The funny part was that this method was an instance method in the class which I typed by mistake. In the error log I saw something like “Invalid use of $this in class function.”

    I knew for a fact I hadn’t used $this in a class method, so it was kind of a confusing error. I went to the file in question and found out that it was calling an instance method as a class method. Now that is some crazy shit.

    + + +

    I would fully expect the PHP parser to give me an error like “No class method [foo] in class [blah]”, rather than try and execute it as a class method. The syntax is completely different; you use :: to call a class method and -> to call an instance method. And you use the name of a class when you call a class method.

    + + +

    This code:

    + + +
    
    +class Foo {
    +  public static function static_fun()
    +  {
    +    return "This is a class method!\n";
    +  }
    +
    +  public function not_static()
    +  {
    +    return "This is an instance method!\n";
    +  }
    +}
    +
    +echo '<pre>';
    +echo "From Foo:\n";
    +echo Foo::static_fun();
    +echo Foo::not_static();
    +echo "\n";
    +
    +echo "From \$foo = new Foo():\n";
    +$foo = new Foo();
    +echo $foo->static_fun();
    +echo $foo->not_static();
    +echo '</pre>';
    +
    + +

    Produces:

    + + +
    +From Foo:
    +This is a class method!
    +This is an instance method!
    +
    +From $foo = new Foo():
    +This is a class method!
    +This is an instance method!
    +
    + +

    What the fuck?! http://www.php.net/manual/en/language.oop5.static.php is lying to everyone.

    +
    +

    + Posted in ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/431 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Coping with Windows XP activiation on a Mac - samhuri.net.html b/wayback/@done/Coping with Windows XP activiation on a Mac - samhuri.net.html new file mode 100644 index 0000000..1a26fba --- /dev/null +++ b/wayback/@done/Coping with Windows XP activiation on a Mac - samhuri.net.html @@ -0,0 +1,2063 @@ + + + + Coping with Windows XP activiation on a Mac - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Coping with Windows XP activiation on a Mac

    +

    + Mon, 18 Dec 2006 07:30:00 GMT

    +

    Update: This needs to be run at system startup, before you log in. I have XP Home and haven't been able to get it to run that way yet.

    + + +

    I can't test my method until I get XP Pro, if I get XP Pro at all. However chack left a comment saying that he got it to work on XP Pro, so it seems we've got a solution here.

    + + +
    + + +

    What is this about?

    + + +

    I recently deleted my Windows XP disk image for Parallels Desktop and created a Boot Camp partition for a new Windows XP installation. I created a new VM in Parallels and it used my Boot Camp partition without a problem. The only problem is that Windows XP Home wants to re-activate every time you change from Parallels to Boot Camp or vice versa. It's very annoying, so what can we do about it?

    + + +

    I was reading the Parallels forums and found out that you can backup your activation and restore it later. After reading that I developed a solution for automatically swapping your activation on each boot so you don't have to worry about it.

    + + +

    I try and stick to Linux and OS X especially for any shell work, and on Windows I would use zsh on cygwin if I use any shell at all, but I think I have managed to hack together a crude batch file to solve this activation nuisance. It's a hack but it sure as hell beats re-activating twice or more every day. It also reinforced my love of zsh and utter dislike of the Windows "shell".

    + + +

    If anyone actually knows how to write batch files I'd like to hear any suggestions you might have.


    + + +

    Make sure things will work

    + + +

    You will probably just want to test my method of testing for Parallels and Boot Camp first. The easiest way is to just open a command window and run this command:

    + + +
    ipconfig /all | find "Parallels"
    + +

    If you see a line of output like "Description . . . . : Parallels Network Adapter" and you are in Parallels then the test works. If you see no output and you are in Boot Camp then the test works.

    + + +

    If you see no output in Parallels or something is printed and you're in Boot Camp, then please double check that you copied the command line correctly, and that you really are running Windows where you think you are. ;-)

    + + +

    If you're lazy then you can download this test script and run it in a command window. Run it in both Parallels and Boot Camp to make sure it gets them both right. The output will either be "Boot Camp" or "Parallels", and a line above that which you can just ignore.

    + + +
    + + +

    NOTE: If you're running Windows in Boot Camp right now then do Step #2 before Step #1.

    + + +
    + + +

    Step #1

    + + +

    Run Windows in Parallels, activate it, then open a command window and run:

    + + +
    
    +mkdir C:\Windows\System32\Parallels
    +copy C:\Windows\System32\wpa.* C:\Windows\System32\Parallels
    +
    +Download backup-parallels-wpa.bat + +
    + + +

    Step #2

    + + +

    Run Windows using Boot Camp, activate it, then run:

    + + +
    
    +mkdir C:\Windows\System32\BootCamp
    +copy C:\Windows\System32\wpa.* C:\Windows\System32\BootCamp
    +
    +Download backup-bootcamp-wpa.bat + +
    + + +

    Step #3: Running the script at startup

    + + +

    Now that you have your activations backed up you need to have the correct ones copied into place every time your system boots. Save this file anywhere you want.

    + + +

    If you have XP Pro then you can get it to run using the Group Policy editor. Save the activate.bat script provided here anywhere and then have it run as a system service. Go Start -> Run... -> gpedit.msc [enter] Computer Configuration -> Windows Settings -> Scripts (Startup/Shutdown) -> Startup -> Add.

    + + +

    If you have XP Home then the best you can do is run this script from your Startup folder (Start -> All Programs -> Startup), but that is not really going to work because eventually Windows will not even let you log in until you activate it. What a P.O.S.

    + + +
    
    +@echo off
    +
    +ipconfig /all | find "Parallels" > network.tmp
    +for /F "tokens=14" %%x in (network.tmp) do set parallels=%x
    +del network.tmp
    +
    +if defined parallels (
    +  echo Parallels
    +  copy C:\Windows\System32\Parallels\wpa.* C:\Windows\System32
    +) else (
    +  echo Boot Camp
    +  copy C:\Windows\System32\BootCamp\wpa.* C:\Windows\System32
    +)
    +
    +
    +Download activate.bat + +
    + + +

    You're done!

    + + +

    That's all you have to do. You should now be able to run Windows in Boot Camp and Parallels as much as you want without re-activating the stupid thing again!

    + + +

    If MS doesn't get their act together with this activation bullshit then maybe the Parallels folks might have to include something hack-ish like this by default.

    + + +

    This method worked for me and hopefully it will work for you as well. I'm interested to know if it does or doesn't so please leave a comment or e-mail me.

    + + +
    + + +

    Off-topic rant

    + + +

    I finally bought Windows XP this week and I'm starting to regret it because of all the hoops they make you jump through to use it. I only use it to fix sites in IE because it can't render a web page properl and I didn't want to buy it just for that. I thought that it would be good to finally get a legit copy since I was using a pirated version and was sick of working around validation bullshit for updates. Now I have to work around MS's activation bullshit and it's just as bad! Screw Microsoft for putting their customers through this sort of thing. Things like this and the annoying balloons near the system tray just fuel my contempt for Windows and reinforce my love of Linux and Mac OS X.

    + + +

    I don't make money off any of my sites, which is why I didn't want to have to buy stupid Windows. I hate MS so much for making shitty IE the standard browser.

    +
    +

    + Posted in , , , ,  | 7 comments | 187 trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + + chack said about 14 hours later:
      +

      Followed the instructions with XP Pro. I have only done one test so far, but it seems like a success!

      + + +

      Thanks for your brilliant work, mate!

      +
    2. + + + + Sami Samhuri said about 17 hours later:
      +

      Awesome! I'm glad that the method is solid, now there just needs to be a more automated way of setting this up so that people don't have to muck around in the Windows command line.

      + + +

      I might have to break out the pirated corporate XP disc in order to code it myself, but even then I couldn't test it. I shudder at the thought of spending more than $100 again on a new copy.

      +
    3. + + + + Marcus Völkel said 4 days later:
      +

      Great done, Sami! Now as build 3094 Beta 2 is available and the reactivation issue should be fixed - are there already known issues with your solution? Just wanted to know before updating my Parallels installation.

      +
    4. + + + + Sami Samhuri said 5 days later:
      +

      Yes build 3094 is supposed to handle activation. I removed any trace of anything I had already done so as not to interfere with whatever Parallels does. I would recommend you do the same since this is all unnecessary now.

      +
    5. + + + + newmacuser said 10 days later:
      +

      I'm a bit confused... What gives you the idea that Parallels 3094 ‘handles' activation? I recently acquired 2 MBPs - one I got working with your solution (and I don't intend to change for a while) and another I continue to struggle with. Using a corporate/volume license version of XP fails to help us without that option... I really do appreciate sharing your original work - very much...

      +
    6. + + + + Sami Samhuri said 33 days later:
      +

      The release notes for that build said they fixed the activation issue.

      +
    7. + + + + carlospc said 33 days later:
      +

      It worked like a charm. The only thing you have to say when reactivating by phone is something like "i changed my video card and windows asked me for reactivation again".

      + + +

      thanks.

      +
    8. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/1003 +

    +
    1. + + + From buy cialis
      + buy cialis
      + news +
    2. +
    3. + + + From cheap phentermine
      + cheap phentermine
      + news +
    4. +
    5. + + + From cialis soft
      + cialis soft
      + news +
    6. +
    7. + + + From phentermine
      + phentermine
      + news +
    8. +
    9. + + + From generic cialis
      + generic cialis
      + news +
    10. +
    11. + + + From buy phentermine
      + buy phentermine
      + news +
    12. +
    13. + + + From cheap phentermine
      + cheap phentermine
      + news +
    14. +
    15. + + + From discount phentermine
      + discount phentermine
      + news +
    16. +
    17. + + + From buy phentermine
      + buy phentermine
      + news +
    18. +
    19. + + + From Buy hydrocodone.
      + Hydrocodone.
      + Hydrocodone. Hydrocodone versus oxycodone. Buying hydrocodone without a prescription. +
    20. +
    21. + + + From Phentermine without an rx cheap prices.
      + Buy cheap phentermine.
      + Cheap phentermine. Phentermine cheap. Cheap phentermine free shipping. Cheap phentermine cod. Buy phentermine buy cheap phentermine online. +
    22. +
    23. + + + From Phentermine overnight.
      + Phentermine.
      + Phentermine online. Cheap phentermine. Phentermine. Cheap phentermine online. Buy phentermine on line. +
    24. +
    25. + + + From phentermine
      + phentermine
      + news +
    26. +
    27. + + + From Endo 602 percocet.
      + Endo 602 percocet.
      + Endo 602 percocet. +
    28. +
    29. + + + From Hydrocodone online cod.
      + Hydrocodone online.
      + Buy hydrocodone online. +
    30. +
    31. + + + From Cheap phentermine.
      + Buy cheap phentermine.
      + Buy prozac phentermine online free shipping cheap. Phentermine cheap. Phentermine special promotion cheap. Uhi foundation forums xanax cheap phentermine. Phentermine very cheap. Cheap phentermine free shipping. Buy cheap phentermine now save. +
    32. +
    33. + + + From How long does hydrocodone stay in urine.
      + Hydrocodone.
      + Hydrocodone. Hydrocodone online. Hydrocodone bitartrate. Withdrawal frpm hydrocodone. +
    34. +
    35. + + + From hydrocodone
      + hydrocodone
      + news +
    36. +
    37. + + + From hydrocodone withdrawal
      + hydrocodone withdrawal
      + news +
    38. +
    39. + + + From Tramadol hcl.
      + Tramadol hcl 50 mg tablet.
      + Tramadol hcl. +
    40. +
    41. + + + From Cheap phentermine no dr rx.
      + Buy phentermine order cheap online.
      + Cheap phentermine. Cheap 37 5 phentermine. +
    42. +
    43. + + + From tramadol hcl
      + tramadol hcl
      + news +
    44. +
    45. + + + From buy tramadol
      + buy tramadol
      + news +
    46. +
    47. + + + From Cheapest tramadol available online.
      + Buy tramadol online save wholesale price yep.
      + Purchase tramadol online. Buy tramadol online save wholesale price yep. Tramadol hci online buy cheap tramadol hci online. Buy cheap tramadol mg tablets only in us online. Cheapest tramadol available online. Buy tramadol online best prices limited... +
    48. +
    49. + + + From Easy way to buy hydrocodone online.
      + Buy hydrocodone online without a prescription.
      + Easy way to buy hydrocodone online. Buy hydrocodone online. Buy hydrocodone online without a prescription. +
    50. +
    51. + + + From cheap tramadol
      + cheap tramadol
      + news +
    52. +
    53. + + + From tramadol hydrochloride
      + tramadol hydrochloride
      + news +
    54. +
    55. + + + From Hydrocodone online.
      + Hydrocodone online.
      + Hydrocodone online prescription pharmacy. Drugs online cheap hydrocodone buy. +
    56. +
    57. + + + From Phentermine cheap.
      + Cheap phentermine cod pharmacy online.
      + Cheap phentermine. Buy cheap phentermine. Phentermine lowest prices online cheap phentermine. Cheap phentermine diet pill. +
    58. +
    59. + + + From Buy tramadol.
      + Tramadol withdraw.
      + Tramadol hydrochloride. +
    60. +
    61. + + + From Phentermine.
      + Phentermine prescription.
      + Buy phentermine diet pill. Phentermine cod. +
    62. +
    63. + + + From foradil
      + foradil
      + news +
    64. +
    65. + + + From Discount phentermine prescription.
      + Discount phentermine.
      + Phentermine us discount. Discount phentermine. +
    66. +
    67. + + + From Phentermine pregnancy.
      + Picture of phentermine.
      + Cheap phentermine. Phentermine. Phentermine pregnancy. +
    68. +
    69. + + + From Phentermine on line.
      + Cheap phentermine online.
      + Phentermine. Phentermine yellow. +
    70. +
    71. + + + From ambien
      + ambien
      + news +
    72. +
    73. + + + From Phentermine pill online d.
      + Phentermine pill.
      + Phentermine pill. Phentermine diet pill. Cheap phentermine diet pill. +
    74. +
    75. + + + From Hydrocodone.
      + Hydrocodone apap.
      + Hydrocodone. Buy hydrocodone online. What is the lethal dose of hydrocodone. Hydrocodone 1923. Buy hydrocodone without a prescription. +
    76. +
    77. + + + From Easy way to buy hydrocodone online.
      + Drugs online cheap hydrocodone buy.
      + Easy way to buy hydrocodone online. Buy hydrocodone online. Buy hydrocodone online without a prescription. +
    78. +
    79. + + + From Dosages for percocet.
      + Difference between percocet and ultracet.
      + Percocet. Percocet dosages. Buy percocet and greece. +
    80. +
    81. + + + From buy hydrocodone no prescription
      + buy hydrocodone no prescription
      + news +
    82. +
    83. + + + From hydrocodone no prescription
      + hydrocodone no prescription
      + news +
    84. +
    85. + + + From buy hydrocodone without prescription
      + buy hydrocodone without prescription
      + news +
    86. +
    87. + + + From viagra
      + viagra
      + news +
    88. +
    89. + + + From viagra side effects
      + viagra side effects
      + news +
    90. +
    91. + + + From buy viagra
      + buy viagra
      + news +
    92. +
    93. + + + From hydrocodone withdrawal
      + hydrocodone withdrawal
      + news +
    94. +
    95. + + + From Cheapest tramadol available online.
      + Cheap tramadol.
      + Tramadol. +
    96. +
    97. + + + From Tramadol hydrochloride.
      + Tramadol hydrochloride.
      + Tramadol hydrochloride. +
    98. +
    99. + + + From Buy hydrocodone online.
      + Easy way to buy hydrocodone online.
      + Buy hydrocodone online consultation. Buy hydrocodone online. Buy hydrocodone online without a prescription. +
    100. +
    101. + + + From Buy hydrocodone online.
      + Buy hydrocodone online.
      + Where to buy hydrocodone online. Easy way to buy hydrocodone online. Buy hydrocodone online consultation. Buy hydrocodone online. +
    102. +
    103. + + + From Buy hydrocodone online.
      + Buy hydrocodone online.
      + Where to buy hydrocodone online. Easy way to buy hydrocodone online. Buy hydrocodone online consultation. Buy hydrocodone online. +
    104. +
    105. + + + From incontro adulto
      + incontro adulto
      + news +
    106. +
    107. + + + From incontro donna veneto
      + incontro donna veneto
      + news +
    108. +
    109. + + + From generic cialis
      + generic cialis
      + news +
    110. +
    111. + + + From incontro gratis
      + incontro gratis
      + news +
    112. +
    113. + + + From sesso gay
      + sesso gay
      + news +
    114. +
    115. + + + From Tramadol use in canines.
      + Tramadol.
      + Comparative potencies of opioids tramadol. Tramadol. +
    116. +
    117. + + + From Discount phentermine.
      + Discount phentermine for 103.
      + Phentermine us discount. Discount phentermine. Discount phentermine pharmacy online. +
    118. +
    119. + + + From Tramadol hcl 50 mg tablet abuse.
      + Tramadol hcl 50 mg tablet abuse.
      + The lowest tramadol hcl price guaranteed fast. Tramadol hcl 50 mg tablet. +
    120. +
    121. + + + From Tramadol hcl 50 mg tablet abuse.
      + Tramadol hcl 50 mg tablet abuse.
      + The lowest tramadol hcl price guaranteed fast. Tramadol hcl 50 mg tablet. +
    122. +
    123. + + + From Tramadol.
      + Tramadol.
      + Tramadol. What is tramadol. Ultram tramadol. +
    124. +
    125. + + + From discount phentermine
      + discount phentermine
      + news +
    126. +
    127. + + + From Tramadol hydrochloride.
      + Tramadol hydrochloride.
      + Tramadol hydrochloride. Tramacet tramadol hydrochloride. Hydrochloride tramadol. +
    128. +
    129. + + + From Buy hydrocodone online.
      + Buy hydrocodone online without prescription.
      + Hydrocodone online. Easy way to buy hydrocodone online. Buy hydrocodone online. Online pharmacy hydrocodone. +
    130. +
    131. + + + From Tramadol hydrochloride.
      + Tramadol hydrochloride liquid.
      + Tramadol hydrochloride. Hydrochloride tramadol. +
    132. +
    133. + + + From Buy phentermine order cheap online.
      + Cheap phentermine diet pill.
      + Cheap phentermine. Buy cheap online phentermine. Phentermine cheap no prescription. Phentermine cheap. Cheap extra phentermine. +
    134. +
    135. + + + From Tramadol hcl 50 mg tablet abuse.
      + Tramadol hcl 50mg.
      + Tramadol hcl liquid. Tramadol hcl. Tramadol hcl 50 mg tablet. +
    136. +
    137. + + + From Tramadol.
      + Canine tramadol.
      + Tramadol. What is the street value for tramadol. +
    138. +
    139. + + + From Valium.
      + Can you overdose a dog with valium.
      + Valium snort. Xanax valium. Valium 5mg how long in system. Valium no prescription. +
    140. +
    141. + + + From Buy hydrocodone online without a prescription.
      + Where to buy hydrocodone online.
      + Where to buy hydrocodone online. Easy way to buy hydrocodone online. Buy hydrocodone online. Drugs online cheap hydrocodone buy. +
    142. +
    143. + + + From Tramadol hcl 93.
      + Will tramadol hcl test positive in drug testing.
      + Tramadol hcl. Tramadol hcl 50mg. The lowest tramadol hcl price guaranteed fast. Tramadol hcl 93. +
    144. +
    145. + + + From Tramadol hcl 93.
      + Will tramadol hcl test positive in drug testing.
      + Tramadol hcl. Tramadol hcl 50mg. The lowest tramadol hcl price guaranteed fast. Tramadol hcl 93. +
    146. +
    147. + + + From Discount phentermine.
      + Discount phentermine.
      + Discount phentermine. +
    148. +
    149. + + + From Hydrochloride tramadol.
      + Tramadol hydrochloride.
      + Tramadol hydrochloride. Tramacet tramadol hydrochloride. Hydrochloride tramadol. +
    150. +
    151. + + + From Tramadol pill appearance.
      + Diet pill tape worm buy tramadol now.
      + What is the pill tramadol. Tramadol pill appearance. Diet pill tape worm buy tramadol now. +
    152. +
    153. + + + From ambien empty stomach
      + ambien empty stomach
      + news +
    154. +
    155. + + + From buy ambien online cod
      + buy ambien online cod
      + news +
    156. +
    157. + + + From ambien online no prescription overnight delivery
      + ambien online no prescription overnight delivery
      + news +
    158. +
    159. + + + From Amoxicillin.
      + Amoxicillin milk.
      + Amoxicillin. Amoxicillin for acne. When amoxicillin works for acne. Amoxicillin trihydrate. What is amoxicillin. How quickly does amoxicillin work. +
    160. +
    161. + + + From Hydrocodone online.
      + Hydrocodone online.
      + Hydrocodone online. Easy way to buy hydrocodone online. Online prescription for hydrocodone. Drugs online cheap hydrocodone buy. +
    162. +
    163. + + + From Oxycontin.
      + Oxycontin and other opiates help.
      + Oxycontin withdrawl. Oxycontin. Oxycontin sales no prescription. Craigslist oxycontin. No quarter is max boot using oxycontin. Oxycontin abuse. +
    164. +
    165. + + + From Phentermine diet pills.
      + Phentermine diet pills overnight shipping.
      + Phentermine diet pills no membership. Phentermine diet pills. Www.phentermine diet pills shipped c.o.d.. +
    166. +
    167. + + + From Hydrocodone and online and prescriptions.
      + Hydrocodone.
      + Hydrocodone from mexico. +
    168. +
    169. + + + From Tramadol hcl 50mg.
      + Tramadol hcl.
      + Tramadol hcl 20 mg 93. Tramadol hcl liquid. Tramadol hcl. Tramadol hcl 50 mg tablet abuse. Tramadol hcl 50 mg tablet. +
    170. +
    171. + + + From Easy way to buy hydrocodone online.
      + Hydrocodone buy online.
      + Where to buy hydrocodone online. +
    172. +
    173. + + + From viagra for order lamisil viagra
      + viagra for order lamisil viagra
      + news +
    174. +
    175. + + + From buy ambien without a prescription
      + buy ambien without a prescription
      + news +
    176. +
    177. + + + From ambien overnight
      + ambien overnight
      + news +
    178. +
    179. + + + From phentermine
      + phentermine
      + news +
    180. +
    181. + + + From order phentermine online
      + order phentermine online
      + news +
    182. +
    183. + + + From Drugs online cheap hydrocodone buy.
      + Hydrocodone buy online.
      + Where to buy hydrocodone online. Easy way to buy hydrocodone online. Buy hydrocodone online. Buy hydrocodone online without a prescription. +
    184. +
    185. + + + From Purchase hydrocodone online.
      + Hydrocodone online.
      + Hydrocodone online. +
    186. +
    187. + + + From foradil
      + foradil
      + news +
    188. +
    189. + + + From Cheapest tramadol.
      + Tramadol cod.
      + Tramadol abuse. Tramadol hcl 50mg. Tramadol. +
    190. +
    191. + + + From hydrocodone no prescription
      + hydrocodone no prescription
      + news +
    192. +
    193. + + + From cialis drug
      + cialis drug
      + news +
    194. +
    195. + + + From generic cialis
      + generic cialis
      + news +
    196. +
    197. + + + From Buy hydrocodone online.
      + Cheap hydrocodone online.
      + Easy way to buy hydrocodone online. Buy hydrocodone online. Buy hydrocodone online without a prescription. Purchase hydrocodone online. Hydrocodone buy online. Hydrocodone online without a script. Drugs online cheap hydrocodone buy. +
    198. +
    199. + + + From Phentermine free shipping.
      + Phentermine.
      + Phentermine. Phentermine result. Phentermine no prescription. Danger of phentermine. Phentermine on line. Phentermine florida. Phentermine forum. Phentermine cod. +
    200. +
    201. + + + From Buy hydrocodone online consultation.
      + Hydrocodone online.
      + Hydrocodone online. Buying hydrocodone online. Buy hydrocodone online without a prescription. +
    202. +
    203. + + + From cialis
      + cialis
      + news +
    204. +
    205. + + + From hydrocodone side effects
      + hydrocodone side effects
      + news +
    206. +
    207. + + + From snorting hydrocodone
      + snorting hydrocodone
      + news +
    208. +
    209. + + + From buy hydrocodone online
      + buy hydrocodone online
      + news +
    210. +
    211. + + + From hydrocodone extraction
      + hydrocodone extraction
      + news +
    212. +
    213. + + + From Cheap phentermine buy online.
      + Buy cheap phentermine mg tabs.
      + Cheap phentermine. Cheap phentermine online. Buy cheap phentermine now save. Cheap free phentermine shipping. Buy cheap phentermine. +
    214. +
    215. + + + From Cheap tramadol.
      + Tramadol cheap no rx free from india.
      + Cheap tramadol shipped by c.o.d. Cheap tramadol cod buy cheap cod online tramadol. Cheap tramadol. Buy tramadol at a cheap price online. Cheap tramadol prescriptions online. Tramadol cheap no rx. +
    216. +
    217. + + + From Effects of hydrocodone.
      + Hydrocodone without prescription.
      + Hydrocodone. Hydrocodone without prescription. Hydrocodone guaifenesin syreth. +
    218. +
    219. + + + From Cheapest tramadol.
      + Tramadol 180 cod.
      + Tramadol cod. Dog s tramadol. Tramadol. Tramadol maintence. +
    220. +
    221. + + + From phentermine
      + phentermine
      + news +
    222. +
    223. + + + From Drugs online cheap hydrocodone buy.
      + Buy hydrocodone online.
      + Where to buy hydrocodone online. Buy hydrocodone online consultation. Buy hydrocodone online. Drugs online cheap hydrocodone buy. +
    224. +
    225. + + + From Buy phentermine using mastercard.
      + Phentermine with mastercard.
      + Phentermine with mastercard. Buy phentermine with mastercard. Phentermine 37.5 mg online prescription mastercard. Phentermine mastercard. Phentermine online mastercard. +
    226. +
    227. + + + From Diazepam.
      + Diazepam.
      + Diazepam benefits. Diazepam how long it last on cats. Duration of diazepam. Diazepam. +
    228. +
    229. + + + From Tramadol.
      + Cheap tramadol.
      + Cheap tramadol. Cheap tramadol fedex overnight. +
    230. +
    231. + + + From Buy tramadol online cod.
      + Off for tramadol online free fedex low cost.
      + Buy tramadol online cod. +
    232. +
    233. + + + From Phentermine.
      + Phentermine overnight.
      + Buy phentermine. Phentermine. Buy phentermine online. Phentermine no prescription. Cheapest phentermine online. +
    234. +
    235. + + + From Buy cheap phentermine.
      + 180 count phentermine cheap.
      + Cheap phentermine. Phentermine cheap. Buy cheap phentermine mg tabs lowest prices. Cheap phentermine online. Buy cheap phentermine on line now save. Buy cheap phentermine now save. +
    236. +
    237. + + + From Lowes t online phentermine price.
      + Buy phentermine online.
      + Phentermine online purchase. Buy cheap phentermine online. Phentermine online pharmacy. Online phentermine. +
    238. +
    239. + + + From Buy hydrocodone online.
      + Buy hydrocodone online.
      + Easy way to buy hydrocodone online. Buy hydrocodone online. Drugs online cheap hydrocodone buy. +
    240. +
    241. + + + From Hydrochloride tramadol.
      + Tramadol hydrochloride.
      + Tramadol hydrochloride. +
    242. +
    243. + + + From Adipex p and phentermine diet pills shipped cod.
      + Phentermine diet pills.
      + Phentermine diet pills overnight shipping. Phentermine diet pills. Phentermine diet pills without pecription. Diet pills phentermine. +
    244. +
    245. + + + From Hydrocodone online.
      + Buy hydrocodone online discount cheap pharmacy.
      + Hydrocodone online. Buy hydrocodone online consultation. Hydrocodone and online and prescriptions. +
    246. +
    247. + + + From IeriWinner_43
      + IeriWinner_43
      + HI! I've have similar topic at my blog! Please check it.. Thanks. [url=http://www.google.com][/url] http://www.google.com +
    248. +
    249. + + + From Purchase hydrocodone online.
      + Hydrocodone online.
      + Hydrocodone online. Hydrocodone and online and prescriptions. Phentermine and also hydrocodone ordering online. +
    250. +
    251. + + + From Discount phentermine.
      + Discount phentermine prescription.
      + Discount phentermine. +
    252. +
    253. + + + From Buy phentermine online no prescription.
      + Phentermine online.
      + Buy phentermine online buy. Buy c heap phentermine online. Buy phentermine online. Order phentermine online. Phentermine pill online d. +
    254. +
    255. + + + From Tramadol hcl.
      + Tramadol hcl.
      + Will tramadol hcl test positive in drug testing. Tramadol hcl. Tramadol hcl 50 mg tablet. +
    256. +
    257. + + + From Cheap phentermine.
      + Extra cheap phentermine.
      + Phentermine cheap. Cheap phentermine free shipping. +
    258. +
    259. + + + From Cheap phentermine.
      + Extra cheap phentermine.
      + Phentermine cheap. Cheap phentermine free shipping. +
    260. +
    261. + + + From Cheap phentermine.
      + Extra cheap phentermine.
      + Phentermine cheap. Cheap phentermine free shipping. +
    262. +
    263. + + + From Valium liquid form.
      + Valium liquid form.
      + Valium liquid form. +
    264. +
    265. + + + From Hydrocodone online.
      + Hydrocodone online.
      + Hydrocodone online. Buy hydrocodone online. Purchase hydrocodone online. Drugs online cheap hydrocodone buy. +
    266. +
    267. + + + From Tramadol hydrochloride.
      + Tramadol hydrochloride.
      + Tramadol hydrochloride. Tramacet tramadol hydrochloride. +
    268. +
    269. + + + From The lowest tramadol hcl price guaranteed fast.
      + Tramadol hcl 50mg.
      + Tramadol hcl 20 mg 93. Tramadol hcl. +
    270. +
    271. + + + From Phentermine discount.
      + Discount phentermine.
      + Discount phentermine. Phentermine pill online discount. Phentermine discount. +
    272. +
    273. + + + From Buy hydrocodone online.
      + Buy hydrocodone online without prescription.
      + Easy way to buy hydrocodone online. Buy hydrocodone online consultation. Buy hydrocodone online. +
    274. +
    275. + + + From Hydrocodone apap 5/500.
      + No consultation no r/x buy hydrocodone.
      + Hydrocodone. Signs of addictions to hydrocodone. Buy hydrocodone online. +
    276. +
    277. + + + From Phentermine at discount prices.
      + Discount phentermine.
      + Discount phentermine. Discount phentermine no prescription required. +
    278. +
    279. + + + From Hydrocodone free consultation.
      + Hydrocodone.
      + Hydrocodone. +
    280. +
    281. + + + From Hydrocodone.
      + How long does hydrocodone stay in your system.
      + Effects of hydrocodone. +
    282. +
    283. + + + From What does the pill tramadol look like?.
      + Tramadol-pill.
      + Tramadol starting from per pill. What does the pill tramadol look like?. Tramadol-pill. +
    284. +
    285. + + + From Purchase xenical online.
      + Where can i purchase xenical online.
      + Xenical online to buy. Purchase xenical online. Online xenical. Where can i purchase xenical online. Xenical online. +
    286. +
    287. + + + From Hydrocodone/apap.
      + Ways hydrocodone-apap can be abused or used.
      + Hydrocodone/apap. Hydrocodone apap fact sheet. Étiquettes de l apap 10mg2f650mg de hydrocodone. Hydrocodone apap solution qua. Hydrocodone/apap no prescription. +
    288. +
    289. + + + From Tramadol hcl.
      + Tramadol hcl.
      + Tramadol hcl. +
    290. +
    291. + + + From Hydrocodone.
      + Hydrocodone.
      + Hydrocodone. Effects of hydrocodone. Hydrocodone cod delivery online no prescription. Online prescription for hydrocodone. Hydrocodone watson 349. +
    292. +
    293. + + + From Phentermine boards.
      + Phentermine.
      + Phentermine without prescription. Phentermine. +
    294. +
    295. + + + From Where to buy cheap phentermine?.
      + Extra cheap phentermine.
      + Phentermine cheap. +
    296. +
    297. + + + From Tramadol hcl.
      + Tramadol hcl.
      + Tramadol hcl 50 mg tab. Tramadol hcl. +
    298. +
    299. + + + From Valium injectables.
      + Valium withdrawal.
      + India pharmacies ativan valium xanax. Valium withdrawal. Le valium et l alcool effectuent. Valium as a sleep aid. Valium. +
    300. +
    301. + + + From Hydrocodone.
      + Hydrocodone.
      + Hydrocodone. +
    302. +
    303. + + + From Tramadol hcl.
      + Tramadol hcl.
      + Tramadol hcl-acetaminophenpar. Tramadol hcl acetaminophe. Tramadol hcl. Tramadol hcl 50mg information. What is tramadol hcl. +
    304. +
    305. + + + From buy viagra
      + buy viagra
      + news +
    306. +
    307. + + + From viagra for women
      + viagra for women
      + news +
    308. +
    309. + + + From buy phentermine
      + buy phentermine
      + news +
    310. +
    311. + + + From cheap phentermine
      + cheap phentermine
      + news +
    312. +
    313. + + + From phentermine
      + phentermine
      + news +
    314. +
    315. + + + From phentermine no prescription
      + phentermine no prescription
      + news +
    316. +
    317. + + + From cod phentermine as well as cialis cheap reviews
      + cod phentermine as well as cialis cheap reviews
      + news +
    318. +
    319. + + + From valium no prescription
      + valium no prescription
      + news +
    320. +
    321. + + + From buy valium c.o.d.
      + buy valium c.o.d.
      + news +
    322. +
    323. + + + From cheap phentermine
      + cheap phentermine
      + news +
    324. +
    325. + + + From buy phentermine
      + buy phentermine
      + news +
    326. +
    327. + + + From discount phentermine
      + discount phentermine
      + news +
    328. +
    329. + + + From cheap phentermine
      + cheap phentermine
      + news +
    330. +
    331. + + + From xenical
      + xenical
      + news +
    332. +
    333. + + + From hydrocodone
      + hydrocodone
      + news +
    334. +
    335. + + + From ringtones
      + ringtones
      + news +
    336. +
    337. + + + From cingular ringtones
      + cingular ringtones
      + news +
    338. +
    339. + + + From free nextel ringtones
      + free nextel ringtones
      + news +
    340. +
    341. + + + From download free ringtones
      + download free ringtones
      + news +
    342. +
    343. + + + From free ringtones
      + free ringtones
      + news +
    344. +
    345. + + + From phentermine no prescription
      + phentermine no prescription
      + news +
    346. +
    347. + + + From cialis
      + cialis
      + news +
    348. +
    349. + + + From hydrocodone sales
      + hydrocodone sales
      + news +
    350. +
    351. + + + From baccarat cigar
      + baccarat cigar
      + news +
    352. +
    353. + + + From age of bruce baccarat
      + age of bruce baccarat
      + news +
    354. +
    355. + + + From baccarat crystal eagle
      + baccarat crystal eagle
      + news +
    356. +
    357. + + + From Xanax.
      + Xanax.
      + Xanax. +
    358. +
    359. + + + From Xanax.
      + Xanax.
      + Xanax. +
    360. +
    361. + + + From Protonix.
      + Protonix.
      + Protonix. +
    362. +
    363. + + + From Cialis.
      + Cialis.
      + Cialis. +
    364. +
    365. + + + From Cialis.
      + Cialis.
      + Cialis. +
    366. +
    367. + + + From Protonix.
      + Protonix.
      + Protonix. +
    368. +
    369. + + + From Tramadol.
      + Tramadol.
      + Tramadol. +
    370. +
    371. + + + From Xanax.
      + Xanax.
      + Xanax. +
    372. +
    373. + + + From Soma.
      + Soma.
      + Soma. +
    374. +
    375. + + + From Xanax.
      + Xanax.
      + Xanax. +
    376. +
    377. + + + From cialis
      + cialis
      + news +
    378. +
    + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Full-screen Cover Flow - samhuri.net.html b/wayback/@done/Full-screen Cover Flow - samhuri.net.html new file mode 100644 index 0000000..7b0b977 --- /dev/null +++ b/wayback/@done/Full-screen Cover Flow - samhuri.net.html @@ -0,0 +1,346 @@ + + + + Full-screen Cover Flow - samhuri.net + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Full-screen Cover Flow

    +

    + Tue, 06 Mar 2007 21:51:00 GMT

    +

    Cover Flow now comes in a full-screen flavour. It's pretty sweet, but unfortunately the remote controls iTunes exactly the same so you need a mouse to flick through the covers.

    + + +

    That made me wonder if Front Row used this full-screen Cover Flow view for albums now, but it doesn't. I hope Apple gets on this and adds it to Front Row and the Apple TV. I'm sure it's already on their list.

    + + +

    I would love to be able to flick through my albums with the remote right now, but I'm not going to install one of those 3rd-party remote config tools. Guess I have to wait for Apple to do it.

    +
    +

    + Posted in  | Tags ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/1363 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Generate self.down in your Rails migrations - samhuri.net.html b/wayback/@done/Generate self.down in your Rails migrations - samhuri.net.html new file mode 100644 index 0000000..6451fa6 --- /dev/null +++ b/wayback/@done/Generate self.down in your Rails migrations - samhuri.net.html @@ -0,0 +1,546 @@ + + + + Generate self.down in your Rails migrations - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Oct + + NOV + + MAR + +
    + + Previous capture + + 1 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 3 captures +
    1 Nov 06 - 17 Mar 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Generate self.down in your Rails migrations

    +

    + on Friday, March 03, 2006

    +

    Scott wrote a really cool program that will scan self.up and then consult db/schema.rb to automatically fill in self.down for you. Brilliant!

    +
    +

    + Posted in ,  | Tags , ,  | 2 comments | no trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + Avatar + Duane Johnson said 4 days later:
      +

      Just FYI, these features have been included in the Rails bundle by default now. We (syncPEOPLE) also made our 1.0 (hurray!) release today: http://syncpeople.com/downloads.

      + + +

      Thanks for your help, Sami!

      + + +

      P.S. You get a big mention on the screencast, hope I pronounced your name right!

      +
    2. + + + Avatar + Sami Samhuri said 4 days later:
      +

      You pronounced it perfectly. Pretty impressive, really. I get called "samurai" a lot. :)

      + + +

      this bundle rocks!

      +
    3. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/35 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Girlfriend X.html b/wayback/@done/Girlfriend X.html new file mode 100644 index 0000000..861eee6 --- /dev/null +++ b/wayback/@done/Girlfriend X.html @@ -0,0 +1,567 @@ + + + + sjs - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + May + + JUN + + SEP + +
    + + Previous capture + + 14 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 10 captures +
    14 Jun 06 - 9 Oct 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    +
    +

    TextMate: Insert text into self.down

    +

    +on Tuesday, February 21, 2006

    +

    UPDATE: I got everything working and it's all packaged up here. There's an installation script this time as well.

    + + +

    Thanks to a helpful thread on the TextMate mailing list I have the beginning of a solution to insert text at 2 (or more) locations in a file.

    + + +

    I implemented this for a new snippet I was working on for migrations, rename_column. Since the command is the same in self.up and self.down simply doing a reverse search for rename_column in my hackish macro didn't return the cursor the desired location.

    + + Read more... +

    Posted in , ,  | Tags , , , ,  | no comments | no trackbacks

    +
    +
    +

    TextMate: Move selection to self.down

    +

    +on Tuesday, February 21, 2006

    +

    UPDATE: This is obsolete, see this post for a better solution.

    + + +

    Duane's comment prompted me to think about how to get the drop_table and remove_column lines inserted in the right place. I don't think TextMate's snippets are built to do this sort of text manipulation. It would be nicer, but a quick hack will suffice for now.

    + + Read more... +

    Posted in , ,  | Tags , , ,  | no comments | no trackbacks

    +
    +
    +

    TextMate Snippets for Rails Assertions

    +

    +on Monday, February 20, 2006

    +

    This time I've got a few snippets for assertions. Using these to type up your tests quickly, and then hitting ⌘R to run the tests without leaving TextMate, makes testing your Rails app that much more convenient. Just when you thought it was already too easy! (Don't forget that you can use ⌥⌘↓ to move between your code and the corresponding test case.)

    + + +

    This time I'm posting the .plist files to make it easier for you to add them to TextMate. All you need to do is copy these to ~/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Snippets.

    + + +

    Assertion Snippets for Rails

    + + +

    If anyone would rather I list them all here I can do that as well. Just leave a comment.

    + + +

    (I wanted to include a droplet in the zip file that will copy the snippets to the right place, but my 3-hour attempt at writing the AppleScript to do so left me feeling quite bitter. Maybe I was just mistaken in thinking it would be easy to pick up AppleScript.)

    + + +

    Posted in , ,  | Tags , , ,  | no comments | no trackbacks

    +
    +
    +

    Now these are desks!

    +

    +on Monday, February 20, 2006

    +

    I will take one of these desks any day! I particularly like the "epic". But you know when you have to contact them to hear the price that's bad, bad news. Ah well, add it to the list of things to get once I have money.

    + + +

    Posted in ,  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    Obligatory Post about Ruby on Rails

    +

    +on Monday, February 20, 2006

    +

    I'm a Rails newbie and eager to learn. I welcome any suggestions or criticism you have. You can direct them to my inbox or leave me a comment below.

    + + +

    I finally set myself up with a blog. I mailed my dad the address and mentioned that it was running Typo, which is written in Ruby on Rails. The fact that it is written in Rails was a big factor in my decision. I am currently reading Agile Web Development With Rails and it will be great to use Typo as a learning tool, since I will be modifying my blog anyways regardless of what language it's written in.

    + + +

    Clearly Rails made an impression on me somehow or I wouldn't be investing this time on it. But my dad asked me a very good question:

    + + +
    +

    Rails? What is so special about it? I looked at your page and it looks pretty normal to me. I miss the point of this new Rails technique for web development.

    +
    + + +

    It's unlikely that he was surprised at my lengthy response, but I was. I have been known to write him long messages on topics that interest me. However, I've only been learning Rails for two weeks or so. Could I possibly have so much to say about it already? Apparently I do.

    + + Read more... +

    Posted in ,  | Tags , , ,  | 2 comments | no trackbacks

    +
    +
    +

    Virtue

    +

    +on Sunday, February 19, 2006

    +

    Man am I glad I saw Duane's post about Virtue. It's a virtual desktop manager for Mac OS X Tiger. Desktop Manager almost had it, but it didn't quite feel right to me. This app is exactly what I've been looking for in virtual desktops. It has bugs, but it mostly works.

    + + +

    My gentoo box has some serious competition now. Recently I feel like I spend more time developing on my Mac mini than my dual Opteron. I didn't expect that 5 months ago when I got the mini as my first Mac!

    + + +

    Posted in , ,  | Tags  | 2 comments | no trackbacks

    +
    +
    +

    syncPeople on Rails Bundle for TextMate

    +

    +on Sunday, February 19, 2006

    +

    It's too fast I just can't keep up! :) Duane has posted a bundle with even more than go to view/controller. Now it has:

    + + +
      +
    1. Open Controller / View — option-command-up
    2. +
    3. Create Partial from Selection — option-command-p
    4. +
    5. Intelligent Go To File — keypad 'enter' key
    6. +
    + + +

    I'd love to see a central place for rails bundle development. We'll see what happens.

    + + +

    Posted in , ,  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    Some TextMate snippets for Rails Migrations

    +

    +on Saturday, February 18, 2006

    +

    My arsenal of snippets and macros in TextMate is building as I read through the rails canon, Agile Web Development... I'm only 150 pages in so I haven't had to add much so far because I started with the bundle found on the rails wiki. The main ones so far are for migrations.

    + + Read more... +

    Posted in , ,  | Tags , ,  | 6 comments | no trackbacks

    +
    +
    +

    Girlfriend X

    +

    +on Saturday, February 18, 2006

    +

    This is hilarious! Someone wrote software that manages a "parallel" dating style.

    + + +
    +

    In addition to storing each woman's contact information and picture, the Girlfriend profiles include a Score Card where you track her sexual preferences, her menstrual cycles and how she styles her pubic hair.

    +
    + + +

    It's called Girlfriend X, but that's a link to an article about it. I didn't go to the actual website. I just thing it's amusing someone went through the trouble to do this. Maybe there's a demand for it. * shrug *

    + + +

    Posted in  | Tags ,  | no comments | no trackbacks

    +
    +
    +

    Jump to view/controller in TextMate

    +

    +on Saturday, February 18, 2006

    +

    Duane came up with a way to jump to the controller method for the view you're editing, or vice versa in TextMate while coding using Rails. This is a huge time-saver, thanks!

    + + +

    Posted in , ,  | Tags ,  | no comments | no trackbacks

    +
    + + +

    Older posts: 1 2 3

    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/I don't mind FairPlay either - samhuri.net.html b/wayback/@done/I don't mind FairPlay either - samhuri.net.html new file mode 100644 index 0000000..2b9abec --- /dev/null +++ b/wayback/@done/I don't mind FairPlay either - samhuri.net.html @@ -0,0 +1,544 @@ + + + + I don't mind FairPlay either - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    I don't mind FairPlay either

    +

    + Sat, 04 Mar 2006 05:56:00 GMT

    +

    I think that Jim is right about Apple’s DRM not being all that evil.

    + + +

    I buy music from the iTunes Music Store because I bought an iPod. The fact I can’t play them on another device doesn’t matter to me. With my purchased songs I can:

    + + +
      +
    • listen to the songs I buy all I want
    • +
    • burn them to CD
    • +
    • stream them to my amplifier via AirPort Express
    • +
    + + +

    I don’t buy a ton of music from the iTMS, but I can’t tell the difference between any of those songs and the songs I ripped from CDs and they’re all mixed in one collection. That’s good enough for me.

    + + +

    I dislike DRM as much as the next guy, but like CSS encryption on DVDs, FairPlay is something I can live with.

    + + +

    It reminds me of how here in North America I have to live with the crappy cell phone companies that lock their phones to their networks. If it’s something I need or want, sometimes I’ll live with restrictions because there are no alternatives yet.

    + + +

    Update: It’s almost settled. The pope got an iPod so all that’s left is to see if he buys any music off of iTunes. If he does, then it can’t be evil. heh…

    +
    +

    + Posted in , ,  | Tags , , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/37 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Ich bin Ausländer und spreche nicht gut Deutsch - samhuri.net.html b/wayback/@done/Ich bin Ausländer und spreche nicht gut Deutsch - samhuri.net.html new file mode 100644 index 0000000..37e0e1e --- /dev/null +++ b/wayback/@done/Ich bin Ausländer und spreche nicht gut Deutsch - samhuri.net.html @@ -0,0 +1,531 @@ + + + + Ich bin Ausländer und spreche nicht gut Deutsch - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Aug + + SEP + + DEC + +
    + + Previous capture + + 27 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 5 captures +
    27 Sep 06 - 9 Oct 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Ich bin Ausländer und spreche nicht gut Deutsch

    +

    + on Monday, June 05, 2006

    +

    How's this for an update: I'm working in Munich for the summer at a European search engine called Seekport. The search engine isn't all they do, as right now I'm programming a desktop widget that shows live scores & news from World Cup matches (in English and Arabic). I'm building it on top of the Yahoo! Widget Engine because it needs to run on Windows. Even though I quite like the Y! Engine, I would still prefer to be coding in straight HTML, CSS & JavaScript like Dashboard programmers get to use. The Y! Engine uses XML (it is somewhat HTML-like) and JavaScript.

    The place I'm living in is like a dormitory for younger people. I share a bathroom & kitchen with a German guy named Sebastian who is 21 and an artist; a stonecutter actually. I only met him briefly yesterday, but he seems nice. I'm going to teach him English, and he'll teach me German, though his English is much better than my German. It's a pretty quiet place, and we get breakfast included, dinner can be bought for €2,50, and Internet access is included as well. I brought my Mac Mini with me, and as soon as I find an AC adapter I'll be ready to go with the 'net at home. I probably won't blog again till then, since I'm at work right now.

    + + +

    Germany is great so far, and as soon as I get learning some German I'll be a much happier person. I consider it rude of me to expect everyone to converse with me in English, like I have to do right now.

    + + +

    (Oh, and they sell beer by the litre in Germany! They call it a maß.)

    +
    +

    + Posted in  | Tags , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/423 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Intelligent Migration Snippets 0.1 for TextMate - samhuri.net.html b/wayback/@done/Intelligent Migration Snippets 0.1 for TextMate - samhuri.net.html new file mode 100644 index 0000000..17a4cd1 --- /dev/null +++ b/wayback/@done/Intelligent Migration Snippets 0.1 for TextMate - samhuri.net.html @@ -0,0 +1,573 @@ + + + + Intelligent Migration Snippets 0.1 for TextMate - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Feb + + MAR + + SEP + +
    + + Previous capture + + 21 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 7 captures +
    21 Mar 06 - 6 Aug 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Intelligent Migration Snippets 0.1 for TextMate

    +

    + on Wednesday, February 22, 2006

    +

    This should be working now. I've tested it under a new user account here.

    + + +

    This does requires the syncPeople bundle to be installed to work. That's ok, because you should get the syncPeople on Rails bundle anyways.

    + + +

     

    + + +

    When writing database migrations in Ruby on Rails it is common to create a table in the self.up method and then drop it in self.down. The same goes for adding, removing and renaming columns.

    + + +

    I wrote a Ruby program to insert code into both methods with a single snippet. All the TextMate commands and macros that you need are included.

    + + +

    See it in action

    + + +

    I think this looks cool in action. Plus I like to show off what what TextMate can do to people who may not use it, or don't have a Mac. It's just over 30 seconds long and weighs in at around 700kb.

    + + +

    Download Download Demo Video

    + + +

    Features

    + + +

    There are 3 snippets which are activated by the following tab triggers:

    + + +
      +
    • mcdt: Migration Create and Drop Table
    • +
    • marc: Migration Add and Remove Column
    • +
    • mnc: Migration Rename Column
    • +
    + + +

    Installation

    + + +

    Run Quick Install.app to install these commands to your syncPeople on Rails bundle if it exists, and to the default Rails bundle otherwise. (I highly recommend you get the syncPeople bundle if you haven't already.)

    + + +

    Download Download Intelligent Migration Snippets

    + + +

    This is specific to Rails migrations, but there are probably other uses for something like this. You are free to use and distribute this code.

    +
    +

    + Posted in , , ,  | Tags ,  | 4 comments | no trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + Avatar + Duane Johnson said about 20 hours later:
      +

      Hi Sami,

      + + +

      I've downloaded the Intelligent Migration Snippets, and I think I can guess what they're going to do, but unfortunately there's little glitch in the system: the command that the macro calls contains your username hardcoded in to the bundlePath and supportPath arguments.

      + + +

      I'm trying a few things to see if there's a work around. Until then, let me know if you find anything else!

      + + +

      Thanks for your research and work in to this, I think it's a great idea!

      +
    2. + + + Avatar + Sami said about 21 hours later:
      +

      Doh! I forgot about TextMate hardcoding the command paths in the macros. The install script takes care of this now. Sorry about that.

      +
    3. + + + Avatar + Allan Odgaard said about 22 hours later:
      +

      It shouldn't be necessary to modify the macros at install time.

      + + +

      Preferebly place the scripts in «target bundle»/Support/bin — this will be in the path when replaying the macro. Note however that while recording the macro, the target bundle is unknown, so at that time, it will not be in the path. But having the scripts, while recording, someplace else, which is in the path should allow graceful recording.

      + + +

      Alternatively one can use $TM_SUPPORT_PATH in the command to execute. Remember double quotes.

      + + +

      I would btw suggest putting these things in a bundle of its own, and ship that bundle. That way if you update these commands, only that bundle needs replacing — currently you will have to hunt for the old files in the Rails or syncPeople on Rails bundle, and the latter bundle might overwrite your stuff, if user downloads a new version and double clicks to install.

      +
    4. + + + Avatar + Sami said 1 day later:
      +

      Ok I think I realized my mistake in recording the macros. I appreciate the feedback. I will post a bundle for this fairly soon, with even more in it.

      +
    5. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/23 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Jump to view controller in TextMate - samhuri.net.html b/wayback/@done/Jump to view controller in TextMate - samhuri.net.html new file mode 100644 index 0000000..d38b7c1 --- /dev/null +++ b/wayback/@done/Jump to view controller in TextMate - samhuri.net.html @@ -0,0 +1,485 @@ + + + + Jump to view/controller in TextMate - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Feb + + MAR + + NOV + +
    + + Previous capture + + 24 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 3 captures +
    24 Mar 06 - 30 Apr 09
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Jump to view/controller in TextMate

    +

    + on Saturday, February 18, 2006

    +

    Duane came up with a way to jump to the controller method for the view you're editing, or vice versa in TextMate while coding using Rails. This is a huge time-saver, thanks!

    +
    +

    + Posted in , ,  | Tags ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/8 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Late static binding - samhuri.net.html b/wayback/@done/Late static binding - samhuri.net.html new file mode 100644 index 0000000..d49abca --- /dev/null +++ b/wayback/@done/Late static binding - samhuri.net.html @@ -0,0 +1,601 @@ + + + + Late static binding - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Late static binding

    +

    + Wed, 19 Jul 2006 17:23:00 GMT

    +

    Update: This has been discussed and will be uh, sort of fixed, in PHP6. You’ll be able to use static::my_method() to get the real reference to self in class methods. Not optimal, but still a solution I guess.

    + + +

    As colder on ##php (freenode) told me today, class methods in PHP don’t have what they call late static binding. What’s that? It means that this code:

    + + +
    +
    +class Foo
    +{
    +  public static function my_method()
    +  {
    +    echo "I'm a " . get_class() . "!\n";
    +  }
    +}
    +
    +class Bar extends Foo
    +{}
    +
    +Bar::my_method();
    +
    +
    + +

    outputs “I’m a Foo!”, instead of “I’m a Bar!”. That’s not fun.

    Using __CLASS__ in place of get_class() makes zero difference. You end up with proxy methods in each subclass of Foo that pass in the real name of the calling class, which sucks.

    + + +
    +
    +class Bar extends Foo
    +{
    +  public static function my_method()
    +  {
    +    return parent::my_method( get_class() );
    +  }
    +}
    +
    +
    + +

    I was told that they had a discussion about this on the internal PHP list, so at least they’re thinking about this stuff. Too bad PHP5 doesn’t have it. I guess I should just be glad I won’t be maintaining this code.

    + + +

    The resident PHP coder said “just make your code simpler”, which is what I was trying to do by removing duplication. Too bad that plan sort of backfired. I guess odd things like this are where PHP starts to show that OO was tacked on as an after-thought.

    +
    +

    + Posted in ,  | Tags ,  | 2 comments | no trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + Avatar + Jim Roepcke said 25 days later:
      +

      That’s the worst of both worlds.

      + + +

      In Objective-C, that would work properly. In Java, it wouldn’t work at all because static methods (Java doesn’t have class methods) aren’t inherited by subclasses, so at least if you called the method on the superclass the result would be consistent…. but this, this crap (as PHP always is), well, it isn’t consistent with anything. Doesn’t get any worse. But, I’m hardly surprised.

      +
    2. + + + Avatar + Sami said 34 days later:
      +

      Interesting about Java, I didn’t know static methods weren’t inherited.

      + + +

      I have to say that I don’t know if I can work another job using PHP and keep my sanity. :)

      +
    3. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/430 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Never buy a German keyboard! - samhuri.net.html b/wayback/@done/Never buy a German keyboard! - samhuri.net.html new file mode 100644 index 0000000..6e57be8 --- /dev/null +++ b/wayback/@done/Never buy a German keyboard! - samhuri.net.html @@ -0,0 +1,531 @@ + + + + Never buy a German keyboard! - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Aug + + SEP + + DEC + +
    + + Previous capture + + 27 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 6 captures +
    27 Sep 06 - 9 Oct 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Never buy a German keyboard!

    +

    + on Friday, June 09, 2006

    +

    Nothing personal, but the backtick/tilde is located where the rest of the left shift key should be, and the return key is double-height, forcing the backslash/bar to the right of the dash/underscore (that'd be the apostrophe/double quote for pretty much everyone else who types qwerty). Note that I'm talking about using a German keyboard with an English layout. The German layout is flat out impossible for coding.

    German Apple Keyboard

    + + +

    For some reason it gets even worse with a German Apple keyboard. Square brackets, where for art though? Through trial and error I found them using Alt/Opt+5/6... non-Apple German keyboards I've seen use Alt Gr+8/9, which is just as bad but at least they were labeled. I know why coders here don't use the German layout! I feel uneasy just talking about it.

    + + +

    Here's a text file with each character of the 4 rows in it, normal and then shifted, in qwerty, qwertz, and dvorak. I personally think that some ways the German keys change must be some sick joke (double quote moved up to shift-2, single quote almost staying put, angle brackets being shoved aside only to put the semi-colon and colon on different keys as well). If you ask me lots of that could be avoided by getting rid of the key that replaced the backtick/tilde, and putting the 3 vowels with the umlaut (ü, ö, and ä) on Alt Gr/Opt+<a, o, u>. But hey, I don't type in German so what do I know.

    +
    +

    + Posted in  | Tags , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/424 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/OS X and Fitt's law - samhuri.net.html b/wayback/@done/OS X and Fitt's law - samhuri.net.html new file mode 100644 index 0000000..03693fd --- /dev/null +++ b/wayback/@done/OS X and Fitt's law - samhuri.net.html @@ -0,0 +1,522 @@ + + + + OS X and Fitt's law - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    OS X and Fitt's law

    +

    + Mon, 08 May 2006 03:43:00 GMT

    +

    I’ve realized that OS X really does obey Fitt’s law in all 4 corners now. Apple menu in the top left, Spotlight top right, and the bottom 2 are always accessible for drag n drop, unless the dock is hidden. I rarely ever use it because I usually have pretty good chunks of the desktop showing, but it is useful.

    +
    +

    + Posted in ,  | Tags , , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/65 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Obligatory Post about Ruby on Rails - samhuri.net.html b/wayback/@done/Obligatory Post about Ruby on Rails - samhuri.net.html new file mode 100644 index 0000000..8a59646 --- /dev/null +++ b/wayback/@done/Obligatory Post about Ruby on Rails - samhuri.net.html @@ -0,0 +1,769 @@ + + + + Obligatory Post about Ruby on Rails - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Feb + + MAR + + Apr + +
    + + Previous capture + + 16 + + Next capture + +
    + + 2006 + + 2007 + + 2008 + +
    +
    + 1 captures +
    16 Mar 07 - 16 Mar 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Obligatory Post about Ruby on Rails

    +

    + on Monday, February 20, 2006

    +

    I'm a Rails newbie and eager to learn. I welcome any suggestions or criticism you have. You can direct them to my inbox or leave me a comment below.

    + + +

    I finally set myself up with a blog. I mailed my dad the address and mentioned that it was running Typo, which is written in Ruby on Rails. The fact that it is written in Rails was a big factor in my decision. I am currently reading Agile Web Development With Rails and it will be great to use Typo as a learning tool, since I will be modifying my blog anyways regardless of what language it's written in.

    + + +

    Clearly Rails made an impression on me somehow or I wouldn't be investing this time on it. But my dad asked me a very good question:

    + + +
    +

    Rails? What is so special about it? I looked at your page and it looks pretty normal to me. I miss the point of this new Rails technique for web development.

    +
    + + +

    It's unlikely that he was surprised at my lengthy response, but I was. I have been known to write him long messages on topics that interest me. However, I've only been learning Rails for two weeks or so. Could I possibly have so much to say about it already? Apparently I do.

    Ruby on Rails background

    + + +

    I assume a pretty basic knowledge of what Rails is, so if you're not familiar with it now's a good time to read something on the official Rails website and watch the infamous 15-minute screencast, where Rails creator, David Heinemeier Hansson, creates a simple blog application.

    + + +

    The screencasts are what sparked my curiosity, but they hardly scratch the surface of Rails. After that I spent hours reading whatever I could find about Rails before deciding to take the time to learn it well. As a result, a lot of what you read here will sound familiar if you've read other blogs and articles about Rails. This post wasn't planned so there's no list of references yet. I hope to add some links though so please contact me if any ideas or paraphrasing here is from your site, or if you know who I should give credit to.

    + + +

    Rails through my eyes

    + + +

    Black & Decker tools Rails is like my Black & Decker toolkit. I have a hammer, power screwdriver, tape measure, needle-nose pliers, wire cutters, a level, etc. This is exactly what I need—no more, no less. It helps me get things done quickly and easily that would otherwise be painful and somewhat difficult. I can pick up the tools and use them without much training. Therefore I am instantly productive with them.

    + + +

    The kit is suitable for many people who need these things at home, such as myself. Companies build skyscrapers and huge malls and apartments, and they clearly need more powerful tools than I. There are others that just need to drive in a nail to hang a picture, in which case the kit I have is overkill. They're better off just buying and using a single hammer. I happen to fall in the big grey middle chunk, not the other two.

    + + +

    I'm a university student. I code because it's satisfying and fun to create software. I do plan on coding for a living when I graduate. I don't work with ancient databases, or create monster sites like Amazon, Google, or Ebay. The last time I started coding a website from scratch I was using PHP, that was around the turn of the millennium. [It was a fan site for a favourite band of mine.]

    + + +

    After a year or so I realized I didn't have the time to do it properly (ie. securely and cleanly) if I wanted it to be done relatively soon. A slightly customized MediaWiki promptly took it's place. It did all that I needed quite well, just in a less specific way.

    + + +

    The wiki is serving my site extremely well, but there's still that itch to create my own site. I feel if Rails was around back then I may have been able to complete the project in a timely manner. I was also frustrated with PHP. Part of that is likely due to a lack of experience and of formal programming education at that time, but it was still not fun for me. It wasn't until I started learning Rails that I thought "hey, I could create that site pretty quickly using this!"

    + + +

    Rails fits my needs like a glove, and this is where it shines. Many professionals are making money creating sites in Rails, so I'm not trying to say it's for amateurs only or something equally silly.

    + + +

    Web Frameworks and iPods?

    + + +

    Some might say I have merely been swept up in hype and am following the herd. You may be right, and that's okay. I'm going to tell you a story. There was a guy who didn't get one of the oh-so-shiny iPods for a long time, though they looked neat. His discman plays mp3 CDs, and that was good enough for him. The latest iPod, which plays video, was sufficiently cool enough for him to forget that everyone at his school has an iPod and he would be trendy just like them now.

    + + +

    Shocker ending: he is I, and I am him. Now I know why everyone has one of those shiny devices. iPods and web frameworks have little in common except that many believe both the iPod and Rails are all hype and flash. I've realized that something creating this kind of buzz may actually just be a good product. I feel that this is the only other thing the iPod and Rails have in common: they are both damn good. Enough about the iPod, everyone hates hearing about it. My goal is to write about the other thing everyone is tired of hearing about.

    + + +

    Why is Rails special?

    + + +

    Ruby on Rails Rails is not magic. There are no exclusive JavaScript libraries or HTML tags. We all have to produce pages that render in the same web browsers. My dad was correct, there is nothing special about my website either. It's more or less a stock Typo website.

    + + +

    So what makes developing with Rails different? For me there are four big things that set Rails apart from the alternatives:

    + + +
      +
    1. Separating data, function, and design
    2. +
    3. Readability (which is underrated)
    4. +
    5. Database migrations
    6. +
    7. Testing is so easy it hurts
    8. +
    + + +

    MVC 101 (or, Separating data, function, and design)

    + + +

    Now I'm sure you've heard about separating content from design. Rails takes that one step further from just using CSS to style your website. It uses what's known as the MVC paradigm: Model-View-Controller. This is a tried and tested development method. I'd used MVC before in Cocoa programming on Mac OS X, so I was already sold on this point.

    + + +
      +
    • The model deals with your data. If you're creating an online store you have a product model, a shopping cart model, a customer model, etc. The model takes care of storing this data in the database (persistence), and presenting it to you as an object you can manipulate at runtime.
    • +
    + + +
      +
    • The view deals only with presentation. That's it, honestly. An interface to your app.
    • +
    + + +
      +
    • The controller binds the model to the view, so that when the user clicks on the Add to cart link the controller is wired to call the add_product method of the cart model and tell it which product to add. Then the controller takes the appropriate action such as redirecting the user to the shopping cart view.
    • +
    + + +

    Of course this is not exclusive to Rails, but it's an integral part of it's design.

    + + +

    Readability

    + + +

    Rails, and Ruby, both read amazingly like spoken English. This code is more or less straight out of Typo. You define relationships between objects like this:

    + + +
    class Article < Content
    +  has_many :comments, :dependent => true, :order => "created_at ASC"
    +  has_many :trackbacks, :dependent => true, :order => "created_at ASC"
    +  has_and_belongs_to_many :categories, :foreign_key => 'article_id'
    +  has_and_belongs_to_many :tags, :foreign_key => 'article_id'
    +  belongs_to :user
    +...
    + +

    dependent => true means if an article is deleted, it's comments go with it. Don't worry if you don't understand it all, this is just for you to see some actual Rails code.

    + + +

    In the Comment model you have:

    + + +
    class Comment < Content
    +  belongs_to :article
    +  belongs_to :user
    +
    +  validates_presence_of :author, :body
    +  validates_against_spamdb :body, :url, :ip
    +  validates_age_of :article_id
    +...
    + +

    (I snuck in some validations as well)

    + + +

    But look how it reads! Read it out loud. I'd bet that my mom would more or less follow this, and she's anything but a programmer. That's not to say programming should be easy for grandma, but code should be easily understood by humans. Let the computer understand things that are natural for me to type, since we're making it understand a common language anyways.

    + + +

    Ruby and Ruby on Rails allow and encourage you to write beautiful code. That is so much more important than you may realize, because it leads to many other virtues. Readability is obvious, and hence maintainability. You must read code to understand and modify it. Oh, and happy programmers will be more productive than frustrated programmers.

    + + +

    Database Migrations

    + + +

    Here's one more life-saver: migrations. Migrations are a way to version your database schema from within Rails. So you have a table, call it albums, and you want to add the date the album was released. You could modify the database directly, but that's not fun. Even if you only have one server, all your configuration will be in one central place, the app. And Rails doesn't care if you have PostgreSQL, MySQL, or SQLite behind it. You can develop and test on SQLite and deploy on MySQL and the migrations will just work in both environments.

    + + +
    class AddDateReleased < ActiveRecord::Migration
    +  def self.up
    +      add_column "albums", "date_released", :datetime
    +      Albums.update_all "date_released = now()"
    +  end
    +
    +  def self.down
    +      remove_column "albums", "date_released"
    +  end
    +end
    + +

    Then you run the migration (rake migrate does that) and boom, your up to date. If you're wondering, the self.down method indeed implies that you can take this the other direction as well. Think rake migrate VERSION=X.

    + + +

    Along with the other screencasts is one on migrations featuring none other than David Hansson. You should take a look, it's the third video.

    + + +

    Testing so easy it hurts

    + + +

    To start a rails project you type rails project_name and it creates a directory structure with a fresh project in it. This includes a directory appropriately called test which houses unit tests for the project. When you generate models and controllers it creates test stubs for you in that directory. Basically, it makes it so easy to test that you're a fool not to do it. As someone wrote on their site: It means never having to say "I introduced a new bug while fixing another."

    + + +

    Rails builds on the unit testing that comes with Ruby. On a larger scale, that means that Rails is unlikely to flop on you because it is regularly tested using the same method. Ruby is unlikely to flop for the same reason. That makes me look good as a programmer. If you code for a living then it's of even more value to you.

    + + +

    I don't know why it hurts. Maybe it hurts developers working with other frameworks or languages to see us have it so nice and easy.

    + + +

    Wrapping up

    + + +

    Rails means I have fun doing web development instead of being frustrated (CSS hacks aside). David Hansson may be right when he said you have to have been soured by Java or PHP to fully appreciate Rails, but that doesn't mean you won't enjoy it if you do like Java or PHP.

    + + +

    Justin Gehtland rewrote a Java app using Rails and the number of lines of code of the Rails version was very close to that of the XML configuration for the Java version. Java has strengths, libraries available now seems to be a big one, but it's too big for my needs. If you're like me then maybe you'll enjoy Rails as much as I do.

    + + +

    You're not done, you lied to me!

    + + +

    Sort of... there are a few things that it seems standard to include when someone writes about how Rails saved their life and gave them hope again. For completeness sake, I feel compelled to mention some principles common amongst those who develop Rails, and those who develop on Rails. It's entirely likely that there's nothing new for you here unless you're new to Rails or to programming, in which case I encourage you to read on.

    + + +

    DRY

    + + +

    Rails follows the DRY principle religiously. That is, Don't Repeat Yourself. Like MVC, I was already sold on this. I had previously encountered it in The Pragmatic Programmer. Apart from telling some_model it belongs_to :other_model and other_model that it has_many :some_models nothing has jumped out at me which violates this principle. However, I feel that reading a model's code and seeing it's relationships to other models right there is a Good Thingâ„¢.

    + + +

    Convention over configuration (or, Perceived intelligence)

    + + +

    Rails' developers also have the mantra "convention over configuration", which you can see from the video there. (you did watch it, didn't you? ;) Basically that just means Rails has sane defaults, but is still flexible if you don't like the defaults. You don't have to write even one line of SQL with Rails, but if you need greater control then you can write your own SQL. A standard cliché: it makes the simple things easy and the hard possible.

    + + +

    Rails seems to have a level of intelligence which contributes to the wow-factor. After these relationships are defined I can now filter certain negative comments like so:

    + + +
    article = Article.find :first
    +for comment in article.comments do
    +  print comment unless comment.downcase == 'you suck!'
    +end
    + +

    Rails knows to look for the field article_id in the comments table of the database. This is just a convention. You can call it something else but then you have to tell Rails what you like to call it.

    + + +

    Rails understands pluralization, which is a detail but it makes everything feel more natural. If you have a Person model then it will know to look for the table named people.

    + + +

    Code as you learn

    + + +

    I love how I've only been coding in Rails for a week or two and I can do so much already. It's natural, concise and takes care of the inane details. I love how I know that I don't even have to explain that migration example. It's plainly clear what it does to the database. It doesn't take long to get the basics down and once you do it goes fast.

    +
    +

    + Posted in ,  | Tags , , ,  | 2 comments | no trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + + Tracey said 11 days later:
      +

      Great post on the Rails. I agree with what you said about 'readability'. Code beauty is very important to me.

      +
    2. + + + + Sami said 12 days later:
      +

      Thanks Tracey, glad you enjoyed it.

      +
    3. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/15 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Ruby and Rails have spoiled me rotten - samhuri.net.html b/wayback/@done/Ruby and Rails have spoiled me rotten - samhuri.net.html new file mode 100644 index 0000000..1d147bb --- /dev/null +++ b/wayback/@done/Ruby and Rails have spoiled me rotten - samhuri.net.html @@ -0,0 +1,551 @@ + + + + Ruby and Rails have spoiled me rotten - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Ruby and Rails have spoiled me rotten

    +

    + Mon, 17 Jul 2006 12:40:00 GMT

    +

    It’s true. I’m sitting here coding in PHP using the Zend Framework and all I can think about is how much nicer Rails is, or how much easier it is to do [x] in Ruby. It’s not that the Zend Framework is bad or anything, it’s quite nice, but you just can’t match Ruby’s expressiveness in a language like PHP. Add the amazing convenience Rails builds on top of Ruby and that’s a really hard combo to compete with.

    I’d love to be using mixins instead of mucking around with abstract classes and interfaces, neither of which will just let you share a method between different classes. Writing proxy methods in these tiny in-between classes is annoying. (ie. inherit from Zend_class, then my real classes inherit from the middle-man class) I could add things to Zend’s classes, but then upgrades are a bitch. I miss Ruby. I could use something like whytheluckystiff’s PHP mixins, which is a clever hack, but still a hack.

    + + +

    I keep looking at Rails code to see how things are done there, and I already coded a nearly complete prototype in Rails as a reference. I could have finished the thing in Rails by now, seriously. I’m still playing catch-up writing validations and model classes for all my objects, stuff I could’ve had for free using Rails, with an extra 10 mins to add validations and make sure they’re all working nicely.

    + + +

    It’s no wonder David H. Hansson wasn’t able to write a framework he was happy with in PHP. After using Rails everything seems like a chore. I’m just coding solved problems over again in an inferior language.

    + + +

    But hey, I’m learning things and I still got to use Ruby even if the code won’t be used later. I guess this experience will just make me appreciate the richness of Ruby and Rails even more.

    +
    +

    + Posted in , , ,  | Tags , , , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/429 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/SJ's Rails Bundle 0.2 for TextMate - samhuri.net.html b/wayback/@done/SJ's Rails Bundle 0.2 for TextMate - samhuri.net.html new file mode 100644 index 0000000..272ae2b --- /dev/null +++ b/wayback/@done/SJ's Rails Bundle 0.2 for TextMate - samhuri.net.html @@ -0,0 +1,594 @@ + + + + SJ's Rails Bundle 0.2 for TextMate - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    SJ's Rails Bundle 0.2 for TextMate

    +

    + Fri, 24 Feb 2006 01:18:00 GMT

    +

    Everything that you’ve seen posted on my blog is now available in one bundle. Snippets for Rails database migrations and assertions are all included in this bundle.

    + + +

    There are 2 macros for class-end and def-end blocks, bound to ⌃C and ⌃D respectively. Type the class or method definition, except for class or def, and then type the keyboard shortcut and the rest is filled in for you.

    + + +

    I use an underscore to denote the position of the cursor in the following example:

    + + +
    method(arg1, arg2_)
    + +

    Typing ⌃D at this point results in this code:

    + + +
    def method(arg1, arg2)
    +  _
    +end
    + +

    There is a list of the snippets in Features.rtf, which is included in the disk image. Of course you can also browse them in the Snippets Editor built into TextMate.

    + + +

    Without further ado, here is the bundle:

    + + +

    Download Download SJ’s Rails Bundle 0.2

    + + +

    This is a work in progress, so any feedback you have is very helpful in making the next release better.

    +
    +

    + Posted in , ,  | Tags , , , ,  | 3 comments | no trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + Avatar + Duane Johnson said 3 days later:
      +

      Hi Sami! I’ve added your superb work to the Rails bundle itself. I love it! Thanks again.

      + + +

      Release candidate 4: +http://blog.inquirylabs.com/

      +
    2. + + + Avatar + Duane Johnson said 8 days later:
      +

      With the inspiration of Scott Barron (and a tip from Kyle Maxwell) I’ve added the reverse migration to the Rails bundle also. You can now use the “mdct” snippet and it will create the corresponding table for the drop_table, using your db/schema.rb as source material. Only in SVN at this point.

      +
    3. + + + Avatar + Sami said 8 days later:
      +

      That’s excellent! I added the ability to reverse the snippets just yesterday, but I never thought to get data from schema.rb to do it in that clever way.

      + + +

      I’ll have to take a look at it. Thanks. :)

      +
    4. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/29 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Some TextMate snippets for Rails Migrations - samhuri.net.html b/wayback/@done/Some TextMate snippets for Rails Migrations - samhuri.net.html new file mode 100644 index 0000000..292a6c3 --- /dev/null +++ b/wayback/@done/Some TextMate snippets for Rails Migrations - samhuri.net.html @@ -0,0 +1,623 @@ + + + + Some TextMate snippets for Rails Migrations - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + MAY + + JUN + + JUL + +
    + + Previous capture + + 15 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 31 captures +
    3 Mar 06 - 21 Mar 09
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Some TextMate snippets for Rails Migrations

    +

    + on Saturday, February 18, 2006

    +

    My arsenal of snippets and macros in TextMate is building as I read through the rails canon, Agile Web Development... I'm only 150 pages in so I haven't had to add much so far because I started with the bundle found on the rails wiki. The main ones so far are for migrations.

    Initially I wrote a snippet for adding a table and one for dropping a table, but I don't want to write it twice every time! If I'm adding a table in up then I probably want to drop it in down.

    + +

    What I did was create one snippet that writes both lines, then it's just a matter of cut & paste to get it in down. The drop_table line should be inserted in the correct method, but that doesn't seem possible. I hope I'm wrong!

    + +

    Scope should be source.ruby.rails and the triggers I use are above the snippets.

    + +

     

    + +

    mcdt: Migration Create and Drop Table

    + +
    create_table "${1:table}" do |t|
    +    $0
    +end
    +${2:drop_table "$1"}
    +
    + +

    mcc: Migration Create Column

    + +
    t.column "${1:title}", :${2:string}
    +
    + +

    marc: Migration Add and Remove Column

    + +
    add_column "${1:table}", "${2:column}", :${3:string}
    +${4:remove_column "$1", "$2"}
    +
    + +

    I realize this might not be for everyone, so here are my original 4 snippets that do the work of marc and mcdt.

    + +

     

    + +

    mct: Migration Create Table

    + +
    create_table "${1:table}" do |t|
    +    $0
    +end
    +
    + +

    mdt: Migration Drop Table

    + +
    drop_table "${1:table}"
    +
    + +

    mac: Migration Add Column

    + +
    add_column "${1:table}", "${2:column}", :${3:string}
    +
    + +

    mrc: Migration Rremove Column

    + +
    remove_column "${1:table}", "${2:column}"
    +
    + +

    I'll be adding more snippets and macros. There should be a central place where the rails bundle can be improved and extended. Maybe there is...

    +
    +

    + Posted in , ,  | Tags , ,  | 6 comments | no trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + Avatar + Duane Johnson said about 8 hours later:
      +

      Hi Sami,

      + + +

      This looks great! I agree, we should have some sort of central place for these things, and preferably something that's not under the management of the core Rails team as they have too much to worry about already.

      + + +

      Would you mind if I steal your snippets and put them in the syncPeople on Rails bundle?

      +
    2. + + + Avatar + Sami said about 20 hours later:
      +

      Not at all. I'm excited about this bundle you've got. Keep up the great work.

      +
    3. + + + Avatar + Duane Johnson said 1 day later:
      +

      Just added the snippets, Sami. I'll try to make a release tonight. Great work, and keep it coming!

      + + +

      P.S. I tried several ways to get the combo-snippets to put the pieces inside the right functions but failed. We'll see tomorrow if Allan (creator of TextMate) has any ideas.

      +
    4. + + + Avatar + dvdplm said 31 days later:
      +

      Need some help here...

      + + +

      Installed the syncPeople bundle. It's in ~/Library/Application Support/TextMate/Bundles/Rails.tmbundle/

      + + +

      Inside there is a Support/bin folder with the scripts needed for the macros/snippets, but typing "mcdt\t" gives an error: "/bin/bash: line 1: intelligent_migration_snippet.rb: command not found". Not really sure where TextMate look, but not in the right place. If I put the absolute path to the rb script in the "command" everything works.

      + + +

      So, do I need some environment vars set? Some other config magic? An installation note would be great...

      + + +

      :-/

      +
    5. + + + Avatar + Sami Samhuri said 32 days later:
      +

      I can't reproduce that behaviour here. TextMate should search ~/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Support/bin automatically.

      + + +

      On a new user account here I installed TM, then installed the syncPeople bundle and it just worked. Perhaps some cruft is affecting things. If possible I suggest starting with a fresh Rails.tmbundle from syncPeople. If that fails maybe starting with a fresh ~/Library/Application Support/TextMate folder will help.

      +
    6. + + + Avatar + Fernando Reig Matthies said 62 days later:
      +

      I get the same error when using mcdt\t> + + +

      /Users/freig/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Support/bin/intelligent_migration_snippet.rb:54:in /bin/bash: -c: line 1: unexpected EOF while looking for matching `'' +/bin/bash: -c: line 3: syntax error: unexpected end of fileinsert_migration' + from /Users/freig/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Support/bin/intelligent_migration_snippet.rb:75

      +
    7. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/10 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Some features you might have missed in iTunes 7 - samhuri.net.html b/wayback/@done/Some features you might have missed in iTunes 7 - samhuri.net.html new file mode 100644 index 0000000..49b5f10 --- /dev/null +++ b/wayback/@done/Some features you might have missed in iTunes 7 - samhuri.net.html @@ -0,0 +1,606 @@ + + + + Some features you might have missed in iTunes 7 - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Sep + + OCT + + NOV + +
    + + Previous capture + + 18 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 8 captures +
    18 Oct 06 - 13 Mar 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Some features you might have missed in iTunes 7

    +

    + on Friday, September 22, 2006

    +

    New menu

    + + +

    Besides the big changes in iTunes 7 there have been some minor changes that are still pretty useful.

    + + +

    Here's a quick recap of a few major features:

    + + +
      +
    • Coverflow built in, new views to flip through album covers and video thumbnails
    • +
    • iTunes Music Store is now just the iTunes Store
    • +
    • New look, no more brushed metal
    • +
    • The menu on the left is more structured and easier to navigate (for me)
    • +
    • Games support
    • +
    + + +

    And now some of the smaller gems are listed below.

    Video controls

    + + +

    iTunes video controls

    + + +

    Similar to the Quicktime full screen controls, iTunes now sports video controls as well. It was really annoying to have to exit fullscreen to control the video, and now we don't have to. The controls are available when you have a floating video window open as well as when you're full screen.

    + + +

    Smart playlists

    + + +

    It's always bothered me that I couldn't remove tracks from smart playlists. After all they are supposed to be smart, so they should remember customizations to them since even the basic ones do that. They're getting smarter. You still can't add arbitrary tracks to one, but I've never wanted to do that except just now to see if you could.

    + + +

    Gapless playback (and more)

    + + +

    Gapless playback

    + + +

    You can set tracks to be part of a gapless album, and your iPod makes use of that information too. Sweet. Another new flag is "Skip when shuffling".

    + + +

    There's also a new field for audio named "Album Artist", but I have no idea what that means.

    + + +

    More video metadata

    + + +

    iTunes video controls

    + + +

    For videos you can now set the Show, Season Number, Episode Number, and Episode ID for each video. Why they let you do this for Movies and Music Videos I'm not sure, but there it is.

    + + +

    What's still missing?

    + + +

    I want to be able to change more than one movie's type to Movie, Music Video, or TV Show at once. Manually doing it for more than one season of a show gets old very fast, and I'm reluctant to write a program to let you do just that but I may if I have time.

    + + +

    I'm sure I have other gripes, but honestly iTunes is a full-featured app and while there's room for improvement they do get a lot right with it as well.

    +
    +

    + Posted in  | Tags ,  | 3 comments | no trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + Avatar + Alexei Templeton said about 5 hours later:
      +

      The 'Album Artist' field is for the cases (namely rap) where 50 artists collaborate. The 'Get Album Artwork' query is dependent on this field over artist, if it is available.

      +
    2. + + + Avatar + Sami Samhuri said about 12 hours later:
      +

      Ah that makes sense. I don't listen to much rap, didn't even think of that. Thanks!

      +
    3. + + + Avatar + Joe said 4 days later:
      +

      This site totally made my day. You should give this game a try.

      + + +

      Visit <a href=

      +
    4. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/439 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Spore - samhuri.net.html b/wayback/@done/Spore - samhuri.net.html new file mode 100644 index 0000000..384401a --- /dev/null +++ b/wayback/@done/Spore - samhuri.net.html @@ -0,0 +1,525 @@ + + + + Spore - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Spore

    +

    + Sat, 04 Mar 2006 05:43:00 GMT

    +

    This game that Jim blogged about is probably the coolest game I’ve seen.

    + + +

    You really just have to watch the video, I won’t bother explaining it here. I don’t really play games much, but this I would play.

    +
    +

    + Posted in ,  | Tags , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/36 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/TextMate Insert text into self.down - samhuri.net.html b/wayback/@done/TextMate Insert text into self.down - samhuri.net.html new file mode 100644 index 0000000..8ae4889 --- /dev/null +++ b/wayback/@done/TextMate Insert text into self.down - samhuri.net.html @@ -0,0 +1,528 @@ + + + + TextMate: Insert text into self.down - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Feb + + MAR + + JUN + +
    + + Previous capture + + 3 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 4 captures +
    3 Mar 06 - 16 Mar 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    TextMate: Insert text into self.down

    +

    + on Tuesday, February 21, 2006

    +

    UPDATE: I got everything working and it's all packaged up here. There's an installation script this time as well.

    + + +

    Thanks to a helpful thread on the TextMate mailing list I have the beginning of a solution to insert text at 2 (or more) locations in a file.

    + + +

    I implemented this for a new snippet I was working on for migrations, rename_column. Since the command is the same in self.up and self.down simply doing a reverse search for rename_column in my hackish macro didn't return the cursor the desired location.

    That's enough introduction, here's the program to do the insertion:

    + + +
    #!/usr/bin/env ruby
    +def indent(s)
    +  s =~ /^(\s*)/
    +  ' ' * $1.length
    +end
    +
    +up_line = 'rename_column "${1:table}", "${2:column}", "${3:new_name}"$0'
    +down_line = "rename_column \"$$1\", \"$$3\", \"$$2\"\n"
    +
    +# find the end of self.down and insert 2nd line
    +lines = STDIN.read.to_a.reverse
    +ends_seen = 0
    +lines.each_with_index do |line, i|
    +  ends_seen += 1    if line =~ /^\s*end\b/
    +  if ends_seen == 2
    +    lines[i..i] = [lines[i], indent(lines[i]) * 2 + down_line]
    +    break
    +  end
    +end
    +
    +# return the new text, escaping special chars
    +print up_line + lines.reverse.to_s.gsub('[$`\\]', '\\\\\1').gsub('\\$\\$', '$')
    + +

    Save this as a command in your Rails, or syncPeople on Rails, bundle. The command options should be as follows:

    + + +
      +
    • Save: Nothing
    • +
    • Input: Selected Text or Nothing
    • +
    • Output: Insert as Snippet
    • +
    • Activation: Whatever you want, I'm going to use a macro described below and leave this empty
    • +
    • Scope Selector: source.ruby.rails
    • +
    + + +

    The first modification it needs is to get the lines to insert as command line arguments so we can use it for other snippets. Secondly, regardless of the Re-indent pasted text setting the text returned is indented incorrectly.

    + + +The macro I'm thinking of to invoke this is tab-triggered and will simply: +
      +
    • Select word (⌃W)
    • +
    • Delete (⌫)
    • +
    • Select to end of file (⇧⌘↓)
    • +
    • Run command "Put in self.down"
    • +
    +
    +

    + Posted in , ,  | Tags , , , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/20 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/TextMate Move selection to self.down - samhuri.net.html b/wayback/@done/TextMate Move selection to self.down - samhuri.net.html new file mode 100644 index 0000000..8af6b35 --- /dev/null +++ b/wayback/@done/TextMate Move selection to self.down - samhuri.net.html @@ -0,0 +1,508 @@ + + + + TextMate: Move selection to self.down - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Feb + + MAR + + NOV + +
    + + Previous capture + + 21 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 3 captures +
    21 Mar 06 - 16 Mar 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    TextMate: Move selection to self.down

    +

    + on Tuesday, February 21, 2006

    +

    UPDATE: This is obsolete, see this post for a better solution.

    + + +

    Duane's comment prompted me to think about how to get the drop_table and remove_column lines inserted in the right place. I don't think TextMate's snippets are built to do this sort of text manipulation. It would be nicer, but a quick hack will suffice for now.

    Use MCDT to insert:

    + + +
    create_table "table" do |t|
    +
    +end
    +drop_table "table"
    + +

    Then press tab once more after typing the table name to select the code drop_table "table". I created a macro that cuts the selected text, finds def self.down and pastes the line there. Then it searches for the previous occurence of create_table and moves the cursor to the next line, ready for you to add some columns.

    + + +

    I have this bound to ⌃⌥⌘M because it wasn't in use. If your Control key is to the left the A key it's quite comfortable to hit this combo. Copy the following file into ~/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Macros.

    + + +

    Move selection to self.down

    + + +

    This works for the MARC snippet as well. I didn't tell you the whole truth, the macro actually finds the previous occurence of (create_table|add_column).

    + + +

    The caveat here is that if there is a create_table or add_column between self.down and the table you just added, it will jump back to the wrong spot. It's still faster than doing it all manually, but should be improved. If you use these exclusively, the order they occur in self.down will be opposite of that in self.up. That means either leaving things backwards or doing the re-ordering manually. =/

    +
    +

    + Posted in , ,  | Tags , , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/19 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/TextMate Snippets for Rails Assertions - samhuri.net.html b/wayback/@done/TextMate Snippets for Rails Assertions - samhuri.net.html new file mode 100644 index 0000000..085d0d1 --- /dev/null +++ b/wayback/@done/TextMate Snippets for Rails Assertions - samhuri.net.html @@ -0,0 +1,558 @@ + + + + TextMate Snippets for Rails Assertions - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Feb + + MAR + + Apr + +
    + + Previous capture + + 16 + + Next capture + +
    + + 2006 + + 2007 + + 2008 + +
    +
    + 1 captures +
    16 Mar 07 - 16 Mar 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    TextMate Snippets for Rails Assertions

    +

    + on Monday, February 20, 2006

    +

    This time I've got a few snippets for assertions. Using these to type up your tests quickly, and then hitting ⌘R to run the tests without leaving TextMate, makes testing your Rails app that much more convenient. Just when you thought it was already too easy! (Don't forget that you can use ⌥⌘↓ to move between your code and the corresponding test case.)

    + + +

    This time I'm posting the .plist files to make it easier for you to add them to TextMate. All you need to do is copy these to ~/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Snippets.

    + + +

    Assertion Snippets for Rails

    + + +

    If anyone would rather I list them all here I can do that as well. Just leave a comment.

    + + +

    (I wanted to include a droplet in the zip file that will copy the snippets to the right place, but my 3-hour attempt at writing the AppleScript to do so left me feeling quite bitter. Maybe I was just mistaken in thinking it would be easy to pick up AppleScript.)

    +
    +

    + Posted in , ,  | Tags , , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/18 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/There's nothing regular about regular expressions - samhuri.net.html b/wayback/@done/There's nothing regular about regular expressions - samhuri.net.html new file mode 100644 index 0000000..6244366 --- /dev/null +++ b/wayback/@done/There's nothing regular about regular expressions - samhuri.net.html @@ -0,0 +1,539 @@ + + + + There's nothing regular about regular expressions - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + Sep + + OCT + + DEC + +
    + + Previous capture + + 18 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 8 captures +
    18 Oct 06 - 9 Oct 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    There's nothing regular about regular expressions

    +

    + on Saturday, June 10, 2006

    +

    I'm almost half way reading Jeffrey Friedl's book Mastering Regular Expressions and I have to say that for a book on something that could potentially bore you to tears, he really does an excellent job of keeping it interesting. Even though a lot of the examples are contrived (I'm sure out of necessity), he also uses real examples of regexes that he's actually used at Yahoo!.

    As someone who has to know how everything works it's also an excellent lesson in patience, as he frequently says "here, take this knowledge and just accept it for now until I can explain why in the next chapter (or in 3 chapters!)". But it's all with good reason and when he does explain he does it well.

    + + +

    Reading about the different NFA and DFA engines and which tools use which made me go "ahhh, /that's/ why I can't do that in grep!" It's not just that I like to know how things work either, he's 100% correct about having to know information like that to wield the power of regexes in all situations. This book made me realize that regex implementations can be wildly different and that you really need to consider the job before jumping into using a specific regex flavour, as he calls them. I'm fascinated by learning why DFA regex implementations would successfully allow ^\w+=.(\\\n.)* to match certain lines, allowing for trailing backslashes to mean continuation but why NFA engines would fail to do the same without tweaking it a bit.

    + + +

    It requires more thinking than the last 2 computer books I read, "Programming Ruby": (the "pixaxe" book) and Agile Web Development With Rails so it's noticeably slower reading. It's also the kind of book I will read more than once, for sure. There's just no way I can glean everything from it in one reading. If you use regular expressions at all then you need this book. This is starting to sound like an advertisement so I'll say no more.

    + + +QOTD, p. 329, about matching nested pairs of parens: +
    \(([^()]|\(([^()]|\(([^()]|\(([^()])*\))*\))*\))*\)
    +Wow, that's ugly.
    +
    + +

    (Don't worry, there's a much better solution on the next 2 pages after that quote.)

    +
    +

    + Posted in  | Tags ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/425 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/@done/Ubuntu Linux for Linux users please - samhuri.net.html b/wayback/@done/Ubuntu Linux for Linux users please - samhuri.net.html new file mode 100644 index 0000000..62384b5 --- /dev/null +++ b/wayback/@done/Ubuntu Linux for Linux users please - samhuri.net.html @@ -0,0 +1,551 @@ + + + + Ubuntu: Linux for Linux users please - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Ubuntu: Linux for Linux users please

    +

    + Thu, 13 Jul 2006 15:34:00 GMT

    +

    Ubuntu is a fine Linux distro, which is why it's popular. I still use Gentoo on my servers but Ubuntu is fast to set up for a desktop. Linux for humans it certainly is, but dammit sometimes I want Linux like I'm used to.

    + + +

    It should ship with build-essentials (gcc & others) installed. It shouldn't ask me if I'm sure I want to restart at the GDM login screen. I have no session open and already clicked twice to choose Restart.

    + + +

    Other things aren't quite ready for humans yet. Network config needs some work. It's very slow to apply changes. Connecting to Windows printers should be easier (ie. let us browse to find them, or just search and present a list). Fonts aren't amazing yet, though Mac OS X has spoiled me as far as fonts are concerned.

    + + +

    Other than these things I think Ubuntu Dapper is a fine release. It installed on my work laptop without a problem and detected the volume keys and wireless network card flawlessly.

    +
    +

    + Posted in  | Tags ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/428 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Where are my headphones - samhuri.net.html b/wayback/@done/Where are my headphones - samhuri.net.html new file mode 100644 index 0000000..85301c7 --- /dev/null +++ b/wayback/@done/Where are my headphones - samhuri.net.html @@ -0,0 +1,556 @@ + + + + Where are my headphones? - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Where are my headphones?

    +

    + Tue, 22 Aug 2006 14:31:00 GMT

    +

    Some people left Seekport this month and 2 of the remaining employees moved into the office I’m working in. That’s fine, and I’m leaving at the end of the week, but man I’m going crazy. This guy’s pounding on his keyboard like it’s a fucking whack-a-mole game! I don’t know what kind of keyboard he learned to type on but it must’ve been horrible. It sounds like he must go through at least 10 of those things in a year. I don’t know if I’ll make it till Friday without yelling “AGH! STOP THE MADNESS YOU CRAZY BASTARD YOU JUST HAVE TO TOUCH THE KEYS!”

    +
    +

    + Posted in  | Tags  | 2 comments | no trackbacks +

    + +

    Comments

    + +
      + +
    1. + + + Avatar + emil.eberhardt@amperegeruch.de said 1 day later:
      +

      Sami, obviously you are right, but I think you will survive the next few days. If you can’t withstand that noise you could pour some sweet and sticky drink into his keyboard, or just kick it out of the window ;-) I have to find a way to survive +much longer … +
      Torsten

      +
    2. + + + Avatar + Sami said 3 days later:
      +

      I survived! :) It wasn’t all that bad really, but I do feel a little sorry for you.

      +
    3. + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/433 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/WikipediaFS on Linux, in Python - samhuri.net.html b/wayback/@done/WikipediaFS on Linux, in Python - samhuri.net.html new file mode 100644 index 0000000..e796cf3 --- /dev/null +++ b/wayback/@done/WikipediaFS on Linux, in Python - samhuri.net.html @@ -0,0 +1,525 @@ + + + + WikipediaFS on Linux, in Python - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    WikipediaFS on Linux, in Python

    +

    + Mon, 08 May 2006 03:49:00 GMT

    +

    Till now I’ve been using my own version of pywikipedia for scripting MediaWiki, and it works well. But I read about WikipediaFS and had to check it out. It’s a user space filesystem for Linux that’s built using the Python bindings for FUSE. What it does is mounts a filesystem that represents your wiki, with articles as text files. You can use them just like any other files with mv, cp, ls, vim, and so on.

    + + +

    There hasen’t been any action on that project for 13 months though, and it doesn’t work on my wiki (MediaWiki 1.4.15) so I’m going to try and make it work after I upgrade to MediaWiki 1.6.3 tonight. This will be pretty cool when it works. I haven’t looked at the code yet but it’s only 650 lines.

    +
    +

    + Posted in , ,  | Tags , , , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/66 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/Working with the Zend Framework - samhuri.net.html b/wayback/@done/Working with the Zend Framework - samhuri.net.html new file mode 100644 index 0000000..5422f80 --- /dev/null +++ b/wayback/@done/Working with the Zend Framework - samhuri.net.html @@ -0,0 +1,554 @@ + + + + Working with the Zend Framework - samhuri.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +

    Working with the Zend Framework

    +

    + Thu, 06 Jul 2006 14:36:00 GMT

    +

    At Seekport I'm currently working on an app to handle the config of their business-to-business search engine. It's web-based and I'm using PHP, since that's what they're re-doing the front-end in. Right now it's a big mess of Perl, the main developer (for the front-end) is gone, and they're having trouble managing it. I have read through it, and it's pretty dismal. They have config mixed with logic and duplicated code all over the place. There's an 1100 line sub in one of the perl modules. Agh!

    Anyway, I've been looking at basically every damn PHP framework there is and most of them aren't that great (sorry to the devs, but they're not). It's not really necessary for my little project, but it helps in both writing and maintaining it. Many of them are unusable because they're still beta and have bugs, and I need to develop the app not debug a framework. Some of them are nice, but not really what I'm looking for, such as Qcodo, which otherwise look really cool.

    + + +

    CakePHP and Symfony seem to want to be Rails so badly, but fall short in many ways, code beauty being the most obvious one.

    + + +

    I could go on about them all, I looked at over a dozen and took at least 5 of them for a test-drive. The only one I really think has a chance to be the PHP framework is the Zend Framework. I really don't find it that amazing, but it feels right, whereas the others feel very thrown-together. In other words, it does a good job of not making it feel like PHP. ;-)

    + + +

    Nothing they're doing is relovutionary, and I question the inclusion of things like PDF handling when they don't even seem to have relationships figured out, but it provides a nice level of convenience above PHP without forcing you into their pattern of thinking. A lot of the other frameworks I tried seemed like one, big, unbreakable unit. With Zend I can really tell that nothing is coupled.

    + + +

    So I'll probably be writing some notes here about my experience with this framework. I also hope to throw Adobe's Spry into the mix. That little JS library is a lot of fun.

    +
    +

    + Posted in , ,  | Tags , , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/427 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + diff --git a/wayback/@done/sjs 301 moved permanently.html b/wayback/@done/sjs 301 moved permanently.html new file mode 100644 index 0000000..57819e9 --- /dev/null +++ b/wayback/@done/sjs 301 moved permanently.html @@ -0,0 +1,627 @@ + + + + sjs: 301 moved permanently + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + 301 moved permanently + + 1 + +

    +
    + Posted by sjs +
    +on Saturday, June 09 +
    +
    +

    Last weekend I moved out of the apartment I lived in for the last 3 1/2 years. Moving was a cinch thanks to a friend's garage, conveniently placed smack between my old place and the new one. Google maps tells me that I moved just under 3.4 km, which is 2.1 mi for the metric impaired, so it wasn't much of a move at all! My roommate and I live in the basement of a house split into 3 apartments. Our upstairs neighbours are friendly and seem pretty cool, except one lady upstairs seems a bit strange. It's a great place though and in the winter the wood stove fireplace is going to be awesome.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + cj – + June 22, 2007 @ 08:29 PM +
      +
      +

      What??? You moved?!? Send me your new address!! I hope you like your new place!

      +
      +
    2. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs 5 ways to avoid looking like a jerk on the Internet.html b/wayback/@done/sjs 5 ways to avoid looking like a jerk on the Internet.html new file mode 100644 index 0000000..a5cc0c7 --- /dev/null +++ b/wayback/@done/sjs 5 ways to avoid looking like a jerk on the Internet.html @@ -0,0 +1,662 @@ + + + + sjs: 5 ways to avoid looking like a jerk on the Internet + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + 5 ways to avoid looking like a jerk on the Internet + + 2 + +

    +
    + Posted by sjs +
    +on Thursday, August 30 +
    +
    +

    Let me begin by stating that these are tips I have gathered by posting in many public forums on the Internet and I have learned most of these rules by making the mistakes myself. I'm not trying to point fingers at anyone or act all holier-than-thou. It's a cold, emotionless medium text is. It can be difficult to accurately convey one's feelings when typing a quick reply somewhere. John Gabriel's theory certainly plays a part as well, but I'll try and assume that you are generally a nice person. I also assume that we are talking about a text medium (IRC, forums, Slashdot/Reddit/Digg). None of that fancy voice or video conferencing stuff!

    + + +

    Also, this is not a guide on how to really be an arrogant prick, but just not look like one when you engage in conversations on the Internet. It's also not a guide on not being a jerk. Should you lack basic manners you will have to learn them elsewhere.

    + + +

    Rule #1: Forget the medium

    + + +

    One thing that is quite difficult to do is look past the medium and remember that these are all real people conversing with each other. Don't type anything that you wouldn't say to their face in real life. This is, of course, not exclusive to the Internet.

    + + +

    Rule #2: Remember the medium!

    + + +

    While obeying Rule #1 it's important to remember that in a text medium there is no emotion or tone to our words. If you think that smilies / emoticons are lame and for 12 year olds, well you're right. However, there's no reason for an adult to refrain from using them as well. They can be important quick clues to how your message should be interpreted. You can always rephrase what you write so that there's little ambiguity to your words, but if you're typing something quickly on Digg, Reddit or some forum then you probably aren't spell checking and proof reading each and every post.

    + + +

    Rule #3: Avoid know-it-all responses

    + + +

    Starting a reply with "But ...", "Well ...", "No ...", or "Your mother's a ..." often sounds confrontational. There's obviously no harm in using these in the right context, but many times I have found that removing these from the front of a sentence can drastically alter the tone and make it clear that I am trying to converse rather than argue.

    + + +

    Rule #4: Address the correct party

    + + +

    If you're not speaking directly to the reader avoid using "you" when you mean "one". This is a particularly hard one to get in the habit of doing, for me at least. I am just not used to speaking so formally but in writing it really does make a world of difference. People are defensive creatures by nature and we don't like being singled out or accused. Hell, half of the time we don't even like honest, kind advice.

    + + +

    Rule #5: Accept the fact that people know more than you

    + + +

    Geeks often come across as know-it-alls. While most geeks probably do think they're rather clever (guilty as charged) they probably also know that they don't know everything. When one knows nothing of a topic it's easy to admit that others are right and they are wrong (often because they won't have an opinion on the subject yet). The trouble starts once they learn something about the matter, once they have formed opinions and ideas about it.

    + + +

    I'm not saying that we should all stop discussing things we're not experts on, just that we should try harder to keep open minds about things and realize that others may have some insight we do not. If in doubt, partake in civil discourse and try not to dismiss others without even asking them to back up their claims or ideas.

    + + +

    Cue the comments pointing out how many of these rules I broke in this very post... :)

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + Danny – + August 30, 2007 @ 04:32 PM +
      +
      +

      excellent post, very well put. I started to use emoticons when i text girls or online because they love that shit, never thought to apply it to forums. No RSS feed??? Dude, I'll fight you for that, disservice to yo self =)

      +
      +
    2. + +
    3. +
      + sjs – + August 30, 2007 @ 06:32 PM +
      +
      +

      There's a feed, just not a link to it. I should remedy that.

      + +

      http://feeds.feedburner.com/sjs

      +
      +
    4. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs A Scheme parser in Haskell Part 1.html b/wayback/@done/sjs A Scheme parser in Haskell Part 1.html new file mode 100644 index 0000000..dff1fd2 --- /dev/null +++ b/wayback/@done/sjs A Scheme parser in Haskell Part 1.html @@ -0,0 +1,760 @@ + + + + sjs: A Scheme parser in Haskell: Part 1 + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + A Scheme parser in Haskell: Part 1 + +

    +
    + Posted by sjs +
    +on Thursday, May 03 +
    +
    + From Write Yourself a Scheme in 48 hours: +
    +

    Basically, a monad is a way of saying “there’s some extra information attached to this value, which most functions don’t need to worry about”. In this example, the “extra information” is the fact that this action performs IO, and the basic value is nothing, represented as “()”. Monadic values are often called “actions”, because the easiest way to think about the IO monad is a sequencing of actions that each might affect the outside world.

    +
    + + +

    I really like this tutorial. I’m only on part 3.3 of 12, parsing, but I’m new to Haskell so I’m learning left, right & centre. The exercises are taking me hours of reading and experimenting, and it’s lots of fun! ghc’s errors are usually quite helpful and of course ghci is a big help as well.

    + + +

    I’m going to explain one of the exercises because converting between the various syntax for dealing with monads wasn’t plainly obvious to me. Perhaps I wasn’t paying enough attention to the docs I read. In any case if you’re interested in Haskell at all, I recommend the tutorial and if you’re stuck on exercise 3.3.1 like I was then come on back here. Whether you’re following the tutorial or not the point of this post should stand on its own with a basic knowledge of Haskell.

    + + +

    Last night I rewrote parseNumber using do and >>= (bind) notations (ex. 3.3.1). Here’s parseNumber using the liftM method given in the tutorial:

    + + +
    parseNumber :: Parser LispVal
    +parseNumber :: liftM (Number . read) $ many1 digit
    +
    + +

    Okay that’s pretty simple right? Let’s break it down, first looking at the right-hand side of the $ operator, then the left.

    + + +
      +
    • many1 digit reads as many decimal digits as it can.
    • +
    + + +
      +
    • Number . read is a function composition just like we’re used to using in math. It applies read to its argument, then applies Number to that result.
    • +
    + + +
      +
    • liftM is concisely and effectively defined elsewhere, and I’ll borrow their description:
    • +
    + + +
    +

    liftM f m lets a non-monadic function f operate on the contents of monad m

    +
    + + +

    liftM’s type is also quite telling: liftM :: (Monad m) => (a -> b) -> (m a -> m b)

    + + +

    In a nutshell liftM turns a function from a to b to a function from a monad containing a to a monad containing b.

    + + +

    That results in a function on the left-hand side of $, which operates on and outputs a monad. The content of the input monad is a String. The content of the output monad is a LispVal (defined earlier in the tutorial). Specifically it is a Number.

    + + +

    The $ acts similar to a pipe in $FAVOURITE_SHELL, and is right associative which means the expression on the right is passed to the expression (function) on the left. It’s exactly the same as (liftM (Number . read)) (many1 digit) except it looks cleaner. If you know LISP or Scheme (sadly I do not) then it’s analogous to the apply function.

    + + +

    So how does a Haskell newbie go about re-writing that using other notations which haven’t even been explained in the tutorial? Clearly one must search the web and read as much as they can until they understand enough to figure it out (which is one thing I like about the tutorial). If you’re lazy like me, here are 3 equivalent pieces of code for you to chew on. parseNumber’s type is Parser LispVal (Parser is a monad).

    + + +Familiar liftM method: +
    parseNumber -> liftM (Number . read) $ many1 digit
    +
    + +Using do notation: +
    parseNumber -> do digits <- many1 digit
    +                  return $ (Number . read) digits
    +
    + +

    If you’re thinking “Hey a return, I know that one!” then the devious masterminds behind Haskell are certainly laughing evilly right now. return simply wraps up it’s argument in a monad of some sort. In this case it’s the Parser monad. The return part may seem strange at first. Since many1 digit yields a monad why do we need to wrap anything? The answer is that using <- causes digits to contain a String, stripped out of the monad which resulted from many1 digit. Hence we no longer use liftM to make (Number . read) monads, and instead need to use return to properly wrap it back up in a monad.

    + + +

    In other words liftM eliminates the need to explicitly re-monadize the contents as is necessary using do.

    + + +Finally, using >>= (bind) notation: +
    parseNumber -> many1 digit >>= \digits ->
    +               return $ (Number . read) digits
    +
    + +

    At this point I don’t think this warrants much of an explanation. The syntactic sugar provided by do should be pretty obvious. Just in case it’s not, >>= passes the contents of its left argument (a monad) to the function on its right. Once again return is needed to wrap up the result and send it on its way.

    + + +

    When I first read about Haskell I was overwhelmed by not knowing anything, and not being able to apply my previous knowledge of programming to anything in Haskell. One piece of syntax at a time I am slowly able to understand more of the Haskell found in the wild.

    + + +

    I’m currently working on ex. 3.3.4, which is parsing R5RS compliant numbers (e.g. #o12345670, #xff, #d987). I’ll probably write something about that once I figure it out, but in the meantime if you have any hints I’m all ears.

    + + +

    Update #1: I should do more proof-reading if I’m going to try and explain things. I made some changes in wording.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + Edward Kmett – + May 11, 2007 @ 10:26 AM +
      +
      + In your above example, you can view return as another function in the chain of functions to apply, yielding: + +parseNumber = many1 digit >>= return . Number . read + +or + +parseNumber = do digits <- many1 digit; return . Number . read $ digits + +of course, this is just unrolling the definition of liftM, so its not surprising. +
      +
    2. + +
    3. +
      + sjs – + May 11, 2007 @ 10:26 AM +
      +
      + Ah, that makes perfect sense. Thanks for that. Every little bit helps my understanding of monads. +
      +
    4. + +
    5. +
      + anonymous – + May 29, 2007 @ 01:49 PM +
      +
      +

      You might also want to know that for monads,

      + + +
      liftM = fmap
      + + +

      This is useful (at least for me), because I have different intuitions for liftM and fmap:

      + + +

      I see liftM as a function lifting ordinary functions to monadic functions, while I think of (fmap f) as a function manipulating the “contents” of a monadic value using f, just like the ordinary map on lists manipulates the elements of lists.

      + + +

      (Depending on context, I use both liftM and fmap.)

      + + +

      In your case, I’d use fmap (this choice is completely subjective, of course), to stress that I just want to change the contents of the monadic return value of (many1 digits):

      + + +
      fmap (Number . read) $ many1 digits
      + + +

      Also, some prefer to write this using infix notation:

      + + +
      Number . read `fmap` many1 digits
      + + +

      This way you see that fmap can be tought of being ($), only modulo monadic stuff.

      + + +

      BTW, fmap is useful on many other data structures, too:

      + + +
      fmap f (Just x) = Just (f x)
      +fmap f Nothing  = Nothing
      + + +
      fmap f (Left  x) = Left x
      +fmap f (Right x) = Right (f x)
      +-- You need Control.Monad.Error for this one.
      + + +
      fmap f xs = map f xs
      +-- With xs :: [a]
      + + +

      Happy Haskelling!

      +
      +
    6. + +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs A TextMate tip for Emacs users.html b/wayback/@done/sjs A TextMate tip for Emacs users.html new file mode 100644 index 0000000..db6a1bb --- /dev/null +++ b/wayback/@done/sjs A TextMate tip for Emacs users.html @@ -0,0 +1,652 @@ + + + + sjs: A TextMate tip for Emacs users + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + A TextMate tip for Emacs users + + 1 + +

    +
    + Posted by sjs +
    +on Tuesday, July 03 +
    +
    +

    Update: The only place I've seen this mentioned is in a comment on the MacroMates blog.

    + + +

    My Linux box is down due to a hardware failure; a cheap SATA controller to be specific. Perhaps that will be a story for another day. As a result I've been working on my MacBook and back in TextMate. Old habits. And I haven't gotten comfortable in any of the OS X Emacsen yet.

    + + +

    This gave me an opportunity to accidentally discover some shortcuts in TextMate. A result of the Emacs shortcuts that my fingers are already wired to, here are some TextMate keyboard shortcuts that may or may not be documented (I need to RTFM some day).

    + + +
      +
    • As in most Cocoa text areas, C-f, C-b, C-n, C-p, C-a, C-e, and C-t work as expected (and others I'm sure).
    • +
    • C-k: behaves as a vanilla Emacs, killing till a newline or killing a bare newline. I use the word killing specifically because you can yank it back with...
    • +
    • C-y: yanks back the last thing on the kill ring (paste history). You still have to use C-S-v to yank previous items.
    • +
    + + +

    I think TextMate may have helped ease me into Emacs without me even knowing. I had my suspicions that Allan was an Emacs fan and now I'm certain of it. I keep finding things in one that the other has, which makes switching between them easy. Well done Allan.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + Ches Martin – + September 24, 2007 @ 11:39 PM +
      +
      +

      While I concur that this is great stuff, and in saying "well done Allan" in general, he got this behavior for free in TextMate :-)

      + +

      Everything you mentioned (with the exception of C-S-v which *is* TextMate-specific) is standard behavior for NSTextArea, the de facto text area class in Cocoa. In other words, they'll work in most OS X-native applications! This rocks. I've used a few while typing this comment in Camino :-)

      + +

      A handy addition to your list is C-d, for forward-delete. You get even more Emacs-like goodness in Terminal.app when you enable the "Use option key as meta key" option in the 'Keyboard' section of Window Settings (be sure to make it default!), along with a few suggestions fromm the Macromates blog. That'll give you Opt-b and Opt-f for moving by word (just like Opt+arrows in NSTextArea, but no picking up your hands), Opt-backspace for delete word, Opt-d for forward delete word, and so forth. Sometimes I wish I could switch these on throughout OS X...

      + +

      Happy hacking.

      +
      +
    2. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs ActiveRecord Base.find_or_create and find_or_initialize.html b/wayback/@done/sjs ActiveRecord Base.find_or_create and find_or_initialize.html new file mode 100644 index 0000000..da8a72f --- /dev/null +++ b/wayback/@done/sjs ActiveRecord Base.find_or_create and find_or_initialize.html @@ -0,0 +1,718 @@ + + + + sjs: ActiveRecord::Base.find_or_create and find_or_initialize + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + ActiveRecord::Base.find_or_create and find_or_initialize + + 0 + +

    +
    + Posted by sjs +
    +on Wednesday, April 11 +
    +
    +

    I've extended ActiveRecord with find_or_create(params) and find_or_initialize(params). Those are actually just wrappers around find_or_do(action, params) which does the heavy lifting.

    + + +

    They work exactly as you'd expect them to work with possibly one gotcha. If you pass in an id attribute then it will just find that record directly. If it fails it will try and find the record using the other params as it would have done normally.

    + + +

    Enough chat, here's the self-explanatory code:

    + + + + + +
    1
    +2
    +3
    +4
    +
    # extend ActiveRecord::Base with find_or_create and find_or_initialize.
    +ActiveRecord::Base.class_eval do
    +  include ActiveRecordExtensions
    +end
    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +
    module ActiveRecordExtensions
    +  def self.included(base)
    +    base.extend(ClassMethods)
    +  end
    +  
    +  module ClassMethods
    +    def find_or_initialize(params)
    +      find_or_do('initialize', params)
    +    end
    +
    +    def find_or_create(params)
    +      find_or_do('create', params)
    +    end
    +    
    +    private
    +    
    +    # Find a record that matches the attributes given in the +params+ hash, or do +action+
    +    # to retrieve a new object with the given parameters and return that.
    +    def find_or_do(action, params)
    +      # if an id is given just find the record directly
    +      self.find(params[:id])
    +
    +    rescue ActiveRecord::RecordNotFound => e
    +      attrs = {}     # hash of attributes passed in params
    +
    +      # search for valid attributes in params
    +      self.column_names.map(&:to_sym).each do |attrib|
    +        # skip unknown columns, and the id field
    +        next if params[attrib].nil? || attrib == :id
    +
    +        attrs[attrib] = params[attrib]
    +      end
    +
    +      # no valid params given, return nil
    +      return nil if attrs.empty?
    +
    +      # call the appropriate ActiveRecord finder method
    +      self.send("find_or_#{action}_by_#{attrs.keys.join('_and_')}", *attrs.values)
    +    end
    +  end
    +end
    + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Back on Gentoo, trying new things.html b/wayback/@done/sjs Back on Gentoo, trying new things.html new file mode 100644 index 0000000..a522024 --- /dev/null +++ b/wayback/@done/sjs Back on Gentoo, trying new things.html @@ -0,0 +1,638 @@ + + + + sjs: Back on Gentoo, trying new things + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Back on Gentoo, trying new things + + 0 + +

    +
    + Posted by sjs +
    +on Tuesday, June 19 +
    +
    +

    I started using my Gentoo box for development again and there are a few things about Linux I didn't realize I had been missing.

    + + +

    Shell completion is awesome out of the box

    + + +

    zsh has an impressive completion system but I just don't feel the urge to ever customize it extensively. I just use the basic completion stuff on OS X because it's easy. On Gentoo I have rake tasks and all sorts of other crap completed for me by including a few lines in my .zshrc (iirc a script does this automatically anyway). Generally Linux distros try to knit everything together nicely so you never even think about things like whether or not a package will have readline support, and default configs will be tweaked and enhanced beyond the official zsh package.

    + + +

    Linux is stable. Really stable.

    + + +

    While people bash Microsoft daily for tying the GUI layer to the kernel, Apple seems to get away with it scot-free. I don't know if it's caused by my external display hooked up to the dock, or the Prolific Firewire chip in my external disk enclosure but something causes the mysterious "music plays till the end of the song, mouse can be moved, but nothing works" bug now and then and all I can do is a hard reset.

    + + +

    On Linux I currently use Fluxbox so everything is rock solid and fast (except Firefox! ;-), but in the extremely rare event that shit does hit the fan usually only a single app will crash, though sometimes X (and hence many others) go with it. A sudo /etc/init.d/gdm restart fixes that. The only times I've had to hard reset Linux was because of a random bug (strangely similar to my MacBook bug) with Nvidia's driver with dual head setups. All this is pretty moot since Linux is generally just stable.

    + + +

    Those are 2 relatively small things but the added comfort they provide is very nice.

    + + +

    In the spirit of switching things up I'm going to forgo my usual routine of using gvim on Linux and try out emacs. I've been frustrated with vim's lack of a decent file browser and I've never much liked the tree plugin. Vim is a fantastic editor when it comes to navigating, slicing, and dicing text. After that it sort of falls flat though. After getting hooked on TextMate I have come to love integration with all sorts of external apps such as Subversion, rake, and the shell because it makes my work easier. Emacs seems to embrace that sort of philosophy and I'm more impressed with the efforts to integrate Rails development into Emacs than vim. I'm typing this post using the Textile mode for Emacs and the markup is rendered giving me a live preview of my post. It's not WYSIWYG like Typo's preview but it's still pretty damn cool. I think can get used to emacs.

    + + +

    I'm just waiting for a bunch of crap to compile - because I use Gentoo - and soon I'll have a Gtk-enabled Emacs to work in. If I can paste to and from Firefox then I'll be happy. I'll have to open this in vim or gedit to paste it into Firefox, funny!

    + + +

    I'm also going to try replacing a couple of desktop apps with web alternatives. I'm starting with 2 no-brainers: mail and feeds with Gmail and Google Reader. I never got into the Gmail craze and never really even used Gmail very much. After looking at the shortcuts I think I can get used to it. Seeing j/k for up/down is always nice. Thunderbird is ok but there isn't a mail client on Linux that I really like, except mutt. That played a part in my Gmail choice. I hadn't used G-Reader before either and it seems alright, but it'll be hard to beat NetNewsWire.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Begging the question.html b/wayback/@done/sjs Begging the question.html new file mode 100644 index 0000000..cd744d0 --- /dev/null +++ b/wayback/@done/sjs Begging the question.html @@ -0,0 +1,623 @@ + + + + sjs: Begging the question + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Begging the question + + 0 + +

    +
    + Posted by sjs +
    +on Friday, June 15 +
    +
    +

    I'm currently reading SICP since it's highly recommended by many people, available for free, and interesting. The fact that I have a little Scheme interpreter to play with makes it much more fun since I can add missing functionality to it as I progress through the book, thereby learning more Haskell in the process. Yay!

    + + +

    Anyway I was very pleased to see the only correct usage of the phrase "begs the question" I have seen in a while. It's a pet peeve of mine, but I have submitted myself to the fact that the phrase is so oft used to mean "begs for the following question to be asked..." that it may as well be re-defined. In its correct usage the sentence seems to hang there if you try to apply the commonly mistaken meaning to it. That's all very hazy so here's the usage in SICP (emphasis my own):

    + + +
    As a case in point, consider the problem of computing square roots. We can define the square-root function as + +

    This describes a perfectly legitimate mathematical function. We could use it to recognize whether one number is the square root of another, or to derive facts about square roots in general. On the other hand, the definition does not describe a procedure. Indeed, it tells us almost nothing about how to actually find the square root of a given number. It will not help matters to rephrase this definition in pseudo-Lisp:

    + + +
    (define (sqrt x)
    +  (the y (and (>= y 0)
    +              (= (square y) x))))
    + +This only begs the question. +
    + +

    Begging the question is to assume what one is trying to prove (or here, define) and use that as the basis for a conclusion. Read the Wikipedia article for a better definition and some nice examples.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Captivating little creatures.html b/wayback/@done/sjs Captivating little creatures.html new file mode 100644 index 0000000..d3cfcce --- /dev/null +++ b/wayback/@done/sjs Captivating little creatures.html @@ -0,0 +1,627 @@ + + + + sjs: Captivating little creatures + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Captivating little creatures + + 1 + +

    +
    + Posted by sjs +
    +on Sunday, August 26 +
    +
    +

    Someone posted this JavaScript implementation of an old gem on Reddit, Lemmings! There goes my Sunday! :)

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + Cassandra – + September 17, 2007 @ 12:10 PM +
      +
      +

      NO WAY!!!!! I used to LOVE that game!

      +
      +
    2. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Catch compiler errors at runtime.html b/wayback/@done/sjs Catch compiler errors at runtime.html new file mode 100644 index 0000000..35e96d4 --- /dev/null +++ b/wayback/@done/sjs Catch compiler errors at runtime.html @@ -0,0 +1,629 @@ + + + + sjs: Catch compiler errors at runtime + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Catch compiler errors at runtime + + 0 + +

    +
    + Posted by sjs +
    +on Sunday, August 19 +
    +
    +

    While coding just now I had a small epiphany about Ruby. Though Ruby is highly dynamic and compiled at runtime, that doesn't preclude one catching some mistakes at compile time. I'm not talking about mere syntax errors or anything either. The only proviso to catching mistakes at compile time is that you must have a decent chunk of code executed during compilation. One benefit of Ruby's blurring of compile time and runtime is that you can run real code at compile time. This is largely how metaprogramming tricks are pulled off elegantly and with ease in projects such as Rails.

    + + +

    Sure you won't get all the benefits of a strictly and/or statically typed compiler, but you can get some of them. If you have a library that makes substantial use of executing code at compile time then the mere act of loading your library causes your code to run, thus it compiles. If you require your lib and get true back then you know the code that bootstraps the runtime code is at least partially correct.

    + + +

    Compile time is runtime. Runtime is compile time. Just because you have to run the code to compile it doesn't mean you can't catch a good chunk of compiler errors before you send out your code. Tests will always be there for the rest of your mistakes, but if you can pull work into compile time then Ruby's compiler can augment your regular testing practices.

    + + +

    I admit that this is of limited use most of the time, but let it not be said that you can't catch any errors with your compiler just because you have to run your code to compile it. With Ruby the more meta you get the more the compiler rewards you.

    + + +

    [Of course this is true of languages such as Common Lisp too, which make available the full programming language at compile time. I just happened to be using Ruby when I realized this.]

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Cheat from Emacs.html b/wayback/@done/sjs Cheat from Emacs.html new file mode 100644 index 0000000..b24fbdb --- /dev/null +++ b/wayback/@done/sjs Cheat from Emacs.html @@ -0,0 +1,695 @@ + + + + sjs: Cheat from Emacs + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Cheat from Emacs + + 4 + +

    +
    + Posted by sjs +
    +on Friday, August 10 +
    +
    +

    Update: I had inadvertently used string-join, a function provided by something in my ~/.emacs.d. The script has been updated to work with a vanilla Emacs (23, but should work with 22 as well).

    + + +

    Update #2 [2007.08.10]: Editing cheats and diffs have been implemented.

    + + +

    Update #3 [2007.08.21]: I added completion to cheat.el. The file linked on this page is still the latest version.

    + + +

    We all know and love cheat. Now you can cheat without leaving Emacs (and without using a shell in Emacs).

    + + +

    Just save cheat.el in ~/.emacs.d and then (require 'cheat) in your ~/.emacs. I also bind C-z C-c to cheat, you may want to do something similar.

    + + +

    You can't do everything you can do with cheat on the command line yet, and for most of the commands the cheat command itself is used. Now you can do everything the command line client does from within Emacs, though you may need to revert to using cheat-command (described below).

    + + +

    Here's the rundown:

    + + +

    Any time you enter a cheat name there are both completion and a cheat-specific history available. Unless you are adding a new cheat. In that case you should use a new, unique name (duh).

    + + +
      +
    • cheat - Lookup a cheat sheet interactively (cheat <name>)
    • +
    • cheat-sheets - List all cheat sheets (cheat sheets)
    • +
    • cheat-recent - List recently added cheat sheets (cheat recent)
    • +
    • cheat-versions - List versions of a cheat sheet interactively (cheat <name> --versions)
    • +
    • cheat-clear-cache - Clear all cached sheets.
    • +
    • cheat-add-current-buffer - Add a new cheat using the specified name and the contents of the current buffer as the body. (cheat <name> --add)
    • +
    • cheat-edit - Retrieve a fresh copy of the named cheat and display the body in a buffer for editing.
    • +
    • cheat-save-current-buffer - Save the current cheat buffer, which should be named *cheat-<name>*.
    • +
    • cheat-diff - Show the diff between the current version and the given version of the named cheat. If the version given is of the form m:n then show the diff between versions m and n. (cheat <name> --diff <version>)
    • +
    • cheat-command - Pass any arguments you want to cheat interactively.
    • +
    + + +

    (Added) I may add support for --diff and --edit in the future.

    + + +

    Please do send me your patches so everyone can benefit from them.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + rj ryan – + August 10, 2007 @ 07:15 AM +
      +
      +

      Thought you might like to know that WebSense denied me access from work because your site is in the 'Sex' category =).

      +
      +
    2. + +
    3. +
      + sjs – + August 10, 2007 @ 09:57 AM +
      +
      +

      That is really strange. The only thing I could think of that is remotely sex-related on my site is: http://sami.samhuri.net/2006/2/18/girlfriend-x ... lame filter!

      +
      +
    4. + +
    5. +
      + jkc – + August 10, 2007 @ 11:22 AM +
      +
      +

      I just tried it with emacs 22 and it can't find one of the functions: +Symbol's function definition is void: string-join +There must be some dependency I assume?

      +
      +
    6. + +
    7. +
      + sjs – + August 10, 2007 @ 11:40 AM +
      +
      +

      That was a mistake on my part. Thanks for letting me know. I'll be sure to test code I publish with emacs -q in the future!

      +
      +
    8. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Cheat productively in Emacs.html b/wayback/@done/sjs Cheat productively in Emacs.html new file mode 100644 index 0000000..c5bc802 --- /dev/null +++ b/wayback/@done/sjs Cheat productively in Emacs.html @@ -0,0 +1,649 @@ + + + + sjs: Cheat productively in Emacs + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Cheat productively in Emacs + + 0 + +

    +
    + Posted by sjs +
    +on Tuesday, August 21 +
    +
    +

    By now you may have heard about cheat, the command line cheat sheet collection that's completely open to editing, wiki style. A couple of weeks ago I posted cheat.el which allows one to cheat from within Emacs. There's an update. However, before I get to cheat.el there's a small detour.

    + + +

    Cheat is not just about Ruby! A few examples of cheats available are:

    + + +
      +
    • bash and zsh
    • +
    • $EDITOR (if you happen to like e, TextMate, vi, emacs, RadRails, ...)
    • +
    • GNU screen
    • +
    • Version control (darcs, svn, git)
    • +
    • Firebug
    • +
    • Markdown and Textile
    • +
    • Oracle and MySQL
    • +
    • Regular expressions
    • +
    • and of course Ruby, Rails, Capistrano, etc.
    • +
    + + +

    As of today, Aug-21 2007, the count is at 166 cheat sheets so there's probably something there that you'll want to look up from the command line or Emacs sometime. That's enough stroking cheat's ego, but there seems to be a notion that cheat is only for Ruby stuff and that's really not the case.

    + + +

    So what's new in this version of cheat.el? Completion! The only thing that bothered me about cheating in Emacs was the lack of completion. It now has completion, thus it is now perfect. :) In all likeliness this won't be the last release, but I can't really foresee adding anything else to it in the near future. Enjoy!

    + + +

    Download it now: cheat.el

    + + +

    For any newcomers, just drop this into ~/.emacs.d, ~/.elisp, or any directory in your load-path and then (require 'cheat). For more info check the original article for a rundown on the cheat commands.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Controlling volume via the keyboard on Linux.html b/wayback/@done/sjs Controlling volume via the keyboard on Linux.html new file mode 100644 index 0000000..b9bff0d --- /dev/null +++ b/wayback/@done/sjs Controlling volume via the keyboard on Linux.html @@ -0,0 +1,611 @@ + + + + sjs: Controlling volume via the keyboard on Linux + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Controlling volume via the keyboard on Linux + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, June 30 +
    +
    +

    I was using Amarok's global keyboard shortcuts to control the volume of my music via the keyboard but I wanted to control the system volume as well. A quick script later and now I can control both, and thanks to libnotify I get some feedback on what happened. It's not as pretty as OS X's volume control or Growl but it'll certainly do.

    + + +

    ↓ Download volume.rb

    + + +

    I save this as ~/bin/volume and call it thusly: volume + and volume -. I bind Alt-+ and Alt—to those in my fluxbox config. If you don't have a preferred key binding program I recommend trying xbindkeys. apt-get install, emerge, paludis -i, or rpm -i as needed.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Digg v4 Reply to replies (Greasemonkey script).html b/wayback/@done/sjs Digg v4 Reply to replies (Greasemonkey script).html new file mode 100644 index 0000000..2318d05 --- /dev/null +++ b/wayback/@done/sjs Digg v4 Reply to replies (Greasemonkey script).html @@ -0,0 +1,618 @@ + + + + sjs: Digg v4: Reply to replies (Greasemonkey script) + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Digg v4: Reply to replies (Greasemonkey script) + + 0 + +

    +
    + Posted by sjs +
    +on Friday, March 09 +
    +
    +

    It's nearly identical to the previous one but works with Digg v4 and should be slightly more efficient. I'm working on making it faster because I believe it is quite inefficient as it is. It was David Bendit's (the original author) first script though so kudos to him for starting this thing because I love it. I just hate a slow greasemonkey script on pages with hundreds of comments.

    + + +

    Please leave me some comments if you appreciate this, or have any feedback on the code.

    + + +

    Happy Digging!

    + + +

    Digg this script!

    + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Diggscuss 0.9.html b/wayback/@done/sjs Diggscuss 0.9.html new file mode 100644 index 0000000..dbaa9a8 --- /dev/null +++ b/wayback/@done/sjs Diggscuss 0.9.html @@ -0,0 +1,578 @@ + + + + sjs: Diggscuss 0.9 + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Diggscuss 0.9 + + 0 + +

    +
    + Posted by sjs +
    +on Sunday, March 25 +
    +
    +

    The biggest change is that it uses XPath for the dirty work, which makes it quite a bit more readable. It's 100 lines longer than the previous version, but it does twice as much.

    + + +

    Now both a [reply] and a [quote] link are added to each comment. Replying to parent comments now adds @username: to the comment field as well as the links added by the script.

    + + +

    Regression: The link to the parent comment is no longer displayed. If you miss this then let me know and I will add it back in.

    + + +

    Any comments, criticism or feature requests are welcome just leave me a comment here or on userscripts.org.

    + + +

    Happy Digging!

    + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs ElSchemo Boolean logic and branching.html b/wayback/@done/sjs ElSchemo Boolean logic and branching.html new file mode 100644 index 0000000..27e9587 --- /dev/null +++ b/wayback/@done/sjs ElSchemo Boolean logic and branching.html @@ -0,0 +1,806 @@ + + + + sjs: ElSchemo: Boolean logic and branching + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + ElSchemo: Boolean logic and branching + +

    +
    + Posted by sjs +
    +on Thursday, August 02 +
    +
    +

    I've been developing a Scheme +interpreter in Haskell called +ElSchemo. +It started from Jonathan's excellent Haskell +tutorial +which I followed in order to learn both Haskell and Scheme. Basically +that means the code here is for me to get some feedback as much +as to show others how to do this kind of stuff. This may not be too +interesting if you haven't at least browsed the tutorial.

    + + +

    I'm going to cover 3 new special forms: and, or, and cond. I +promised to cover the let family of special forms this time around +but methinks this is long enough as it is. My sincere apologies if +you've been waiting for those.

    + + +

    Short-circuiting Boolean logic

    + + +

    Two functions from the tutorial which may irk you immediately are +and and or, defined in Scheme in the given standard library. If +your code is free of side-effects then it may not bother you so +much. It bothered me. The problem with the implementation in +stdlib.scm is that all the arguments are evaluated before control +enters the function. Besides being inefficient by doing unnecessary work, +if any of the arguments have side-effects you can make use of short-circuiting +by using and to sequence actions, bailing out if any fail (by returning nil), +and using or to define a set of alternative actions which will bail out when the first in the list succeeds (by returning anything but nil). Had we macros then we could implement them as +macros. We don't, so we'll write them as special forms in Haskell.

    + + +

    Unlike the special forms defined in the tutorial I'm going to +implement these as separate functions for clarity, rather than lump +them all in eval. However, they will be invoked directly from +eval so their type is easy; it's the same as eval's.

    + + +

    Code first, ask questions later. Haskell is a pretty clear and +concise language. My explanations may be redundant because of this.

    + + +

    lispAnd

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +
    lispAnd :: Env -> [LispVal] -> IOThrowsError LispVal
    +lispAnd env [] = return $ Bool True
    +lispAnd env [pred] = eval env pred
    +lispAnd env (pred:rest) = do
    +    result <- eval env pred
    +    case result of
    +      Bool False -> return result
    +      _ -> lispAnd env rest
    + + +

    Starting with the trivial case, and returns #t with zero +arguments.

    + + +

    With one argument, a single predicate, simply evaluate and +return that argument.

    + + +

    Given a list of predicates, evaluate the first and inspect its value. +If the argument evaluated to #f then our work is done and we return +#f, otherwise we keep plugging along by making a recursive call with +the first argument stripped off. Eventually we will reach our base +case with only one predicate.

    + + +

    It's possible to eliminate the case of one predicate. I think that +just complicates things but it's a viable solution.

    + + +

    lispOr

    + + +

    Predictably this is quite similar to lispAnd.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +
    lispOr :: Env -> [LispVal] -> IOThrowsError LispVal
    +lispOr env [] = return $ Bool False
    +lispOr env [pred] = eval env pred
    +lispOr env (pred:rest) = do
    +    result <- eval env pred
    +    case result of
    +        Bool False -> lispOr env rest
    +        _ -> return result
    + + +

    With no arguments lispOr returns #f, and with one argument it +evaluates and returns the result.

    + + +

    With 2 or more arguments the first is evaluated, but this time if the +result is #f then we continue looking for a truthy value. If the +result is anything else at all then it's returned and we are done.

    + + +

    A new branching construct

    + + +

    First let me define a convenience function that I have added to +ElSchemo. It maps a list of expressions to their values by evaluating +each one in the given environment.

    + + + + + +
    1
    +2
    +
    evalExprs :: Env -> [LispVal] -> IOThrowsError [LispVal]
    +evalExprs env exprs = mapM (eval env) exprs
    + + +

    lispCond

    + + +

    Again, lispCond has the same type as eval.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +
    lispCond :: Env -> [LispVal] -> IOThrowsError LispVal
    +lispCond env (List (pred:conseq) : rest) = do
    +    result <- eval env pred
    +    case result of
    +        Bool False -> if null rest then return result else lispCond env rest
    +        _ -> liftM last $ evalExprs env conseq
    + + +

    Unlike Lisp - which uses a predicate of T (true) - Scheme uses a +predicate of else to trigger the default branch. When the pattern +matching on Atom "else" succeeds, we evaluate the default +expressions and return the value of the last one. This is one +possible base case. Atom "else" could be defined to evaluate to +#t, but we don't want else to be evaluated as #t anywhere except +in a cond so I have chosen this solution.

    + + +

    If the first predicate is not else then we evaluate it and check the +resulting value. If we get #f then we look at the rest of the +statement, if it's empty then we return #f, otherwise we recurse on +the rest of the parameters. If the predicate evaluates to a truthy +value - that is, anything but #f - then we evaluate the consequent +expressions and return the value of the last one.

    + + +

    Plumbing

    + + +

    Now all that's left is to hook up the new functions in eval.

    + + + + + +
    1
    +2
    +3
    +
    eval env (List (Atom "and" : params)) = lispAnd env params
    +eval env (List (Atom "or" : params)) = lispOr env params
    +eval env (List (Atom "cond" : params)) = lispCond env params
    + + +

    You could, of course, throw the entire definitions in eval itself but eval is big +enough for me as it is. YMMV.

    + + +

    Done!

    + + +

    So, that's a wrap. It only took 20 lines of code for the 3 new +special forms, and it could easily be done with less code. Next time +I will show you how to implement the various let functions. Really!

    + + +

    Do you like me describing ElSchemo piece by piece as I have been? I +plan on posting the Haskell code and my stdlib.scm in their entirety +sometime, and I could do that before or after I finish writing about +the features I've developed beyond the tutorial. Just let me know in +the comments.

    + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Emacs tagify-region-or-insert-tag.html b/wayback/@done/sjs Emacs tagify-region-or-insert-tag.html new file mode 100644 index 0000000..27f75db --- /dev/null +++ b/wayback/@done/sjs Emacs tagify-region-or-insert-tag.html @@ -0,0 +1,623 @@ + + + + sjs: Emacs: tagify-region-or-insert-tag + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Emacs: tagify-region-or-insert-tag + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    After axing half of wrap-region.el I renamed it to tagify.el and improved it ever so slightly. It's leaner, and does more!

    + + +

    tagify-region-or-insert-tag does the same thing as wrap-region-with-tag except if there is no region it now inserts the opening and closing tags and sets point in between them. I have this bound to C-z t, as I use C-z as my personal command prefix.

    + + +

    < is bound to tagify-region-or-insert-self which really doesn't warrant an explanation.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Emacs for TextMate junkies.html b/wayback/@done/sjs Emacs for TextMate junkies.html new file mode 100644 index 0000000..bc2ef4b --- /dev/null +++ b/wayback/@done/sjs Emacs for TextMate junkies.html @@ -0,0 +1,773 @@ + + + + sjs: Emacs for TextMate junkies + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Emacs for TextMate junkies + + 6 + +

    +
    + Posted by sjs +
    +on Saturday, June 23 +
    +
    +

    Update #1: What I first posted will take out your < key by mistake (it's available via C-q <), it has since been revised to Do The Right Thing.

    + + +

    Update #2: Thanks to an anonymouse[sic] commenter this code is a little cleaner.

    + + +

    Update #3: I should read the Emacs manual sometime, especially since I have it in dead-tree form. Check out skeleton pairs in the Emacs manual.

    + + +

    Despite my current infatuation with Emacs there are many reasons I started using TextMate, especially little time-savers that are very addictive. I'll talk about one of those features tonight. When you have text selected in TextMate and you hit say the ' (single quote) then TextMate will surround the selected text with single quotes. The same goes for double quotes, parentheses, brackets, and braces. This little trick is one of my favourites so I had to come up with something similar in Emacs. It was easy since a mailing list post has a solution for surrounding the current region with tags, which served as a great starting point.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    (defun surround-region-with-tag (tag-name beg end)
    +      (interactive "sTag name: \nr")
    +      (save-excursion
    +        (goto-char beg)
    +        (insert "<" tag-name ">")
    +        (goto-char (+ end 2 (length tag-name)))
    +        (insert "</" tag-name ">")))
    + + +

    With a little modification I now have the following in my ~/.emacs file:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +
    ;; help out a TextMate junkie
    +
    +(defun wrap-region (left right beg end)
    +  "Wrap the region in arbitrary text, LEFT goes to the left and RIGHT goes to the right."
    +  (interactive)
    +  (save-excursion
    +    (goto-char beg)
    +    (insert left)
    +    (goto-char (+ end (length left)))
    +    (insert right)))
    +
    +(defmacro wrap-region-with-function (left right)
    +  "Returns a function which, when called, will interactively `wrap-region-or-insert' using LEFT and RIGHT."
    +  `(lambda () (interactive)
    +     (wrap-region-or-insert ,left ,right)))
    +
    +(defun wrap-region-with-tag-or-insert ()
    +  (interactive)
    +  (if (and mark-active transient-mark-mode)
    +      (call-interactively 'wrap-region-with-tag)
    +    (insert "<")))
    +
    +(defun wrap-region-with-tag (tag beg end)
    +  "Wrap the region in the given HTML/XML tag using `wrap-region'. If any
    +attributes are specified then they are only included in the opening tag."
    +  (interactive "*sTag (including attributes): \nr")
    +  (let* ((elems    (split-string tag " "))
    +         (tag-name (car elems))
    +         (right    (concat "</" tag-name ">")))
    +    (if (= 1 (length elems))
    +        (wrap-region (concat "<" tag-name ">") right beg end)
    +      (wrap-region (concat "<" tag ">") right beg end))))
    +
    +(defun wrap-region-or-insert (left right)
    +  "Wrap the region with `wrap-region' if an active region is marked, otherwise insert LEFT at point."
    +  (interactive)
    +  (if (and mark-active transient-mark-mode)
    +      (wrap-region left right (region-beginning) (region-end))
    +    (insert left)))
    +
    +(global-set-key "'"  (wrap-region-with-function "'" "'"))
    +(global-set-key "\"" (wrap-region-with-function "\"" "\""))
    +(global-set-key "`"  (wrap-region-with-function "`" "`"))
    +(global-set-key "("  (wrap-region-with-function "(" ")"))
    +(global-set-key "["  (wrap-region-with-function "[" "]"))
    +(global-set-key "{"  (wrap-region-with-function "{" "}"))
    +(global-set-key "<"  'wrap-region-with-tag-or-insert) ;; I opted not to have a wrap-with-angle-brackets
    + + +

    Download wrap-region.el

    + + +

    That more or less sums up why I like Emacs so much. I wanted that functionality so I implemented it (barely! It was basically done for me), debugged it by immediately evaluating sexps and then trying it out, and then once it worked I reloaded my config and used the wanted feature. That's just awesome, and shows one strength of open source.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + Ed Piman – + June 23, 2007 @ 02:36 PM +
      +
      +

      I just tried that out using Aquamacs, and it worked like a charm. Thanks for sharing.

      +
      +
    2. + +
    3. +
      + anonymouse@anonymouse.com – + June 24, 2007 @ 12:03 PM +
      +
      +

      Nice. But you can refactor it to avoid all that boilerplate at the end of the file (that you snipped from the blog post).

      + + +

      (defmacro wrap-region-with-function (left right) + "Returns a function which, when called, will interactively wrap-region-or-insert using left and right." + `(lambda () + (interactive) + (wrap-region-or-insert ,left ,right) + ))

      + + +

      When evaluated, this will macroexpand into wrap-region-with-parens-or-insert. Then define keys as follows:

      + + +

      (global-set-key "(" (wrap-region-with-function "(" ")" ) )

      +
      +
    4. + +
    5. +
      + sjs – + June 24, 2007 @ 04:44 PM +
      +
      +

      Ed: Glad that you like it! :)

      + + +

      anonymouse: Thanks for that! I wanted to do that but I don't know enough ELisp yet. I mostly need to read up on quasiquote & related stuff, and implement it in my scheme interpreter so I understand it well.

      +
      +
    6. + +
    7. +
      + MikeH – + June 25, 2007 @ 05:17 AM +
      +
      +

      I've been looking for this for a long time, and even tried it myself, but I didn't do it nearly as well as you did.

      + + +

      One thing that Textmate (and Eclipse, for that matter) does is that if you enter one of the wrapped characters without text selected, it will enter the ending character as well and put the cursor between the two.

      + + +

      IOW, if you are typing and enter "(" the screen will show "(_)", where _ is the cursor.

      + + +

      Anyway, I made a small change to wrap-region-or-insert to do just that.

      + + +

      (defun wrap-region-or-insert (left right) + "Wrap the region with `wrap-region' if an active region is marked, otherwise insert LEFT at point." + (interactive) + (if (and mark-active transient-mark-mode) + (wrap-region left right (region-beginning) (region-end)) + (insert left) (insert right) (backward-char) + ) +)

      +
      +
    8. + +
    9. +
      + foo – + June 25, 2007 @ 08:34 AM +
      +
      +

      Check out paredit.el

      + + +

      http://mumble.net/~campbell/emacs/paredit.el

      +
      +
    10. + +
    11. +
      + sjs – + June 25, 2007 @ 10:48 AM +
      +
      +

      Mike: Thanks for that. It'll take some getting used to without TextMate overwriting ending delimiters, but foo's link to paredit.el seems to hold the cure for that ailment.

      + + +

      When I have some time to go over paredit.el I'll probably have a nice update for the wrap-region family of functions.

      +
      +
    12. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Embrace the database.html b/wayback/@done/sjs Embrace the database.html new file mode 100644 index 0000000..2b528e3 --- /dev/null +++ b/wayback/@done/sjs Embrace the database.html @@ -0,0 +1,640 @@ + + + + sjs: Embrace the database + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Embrace the database + + 0 + +

    +
    + Posted by sjs +
    +on Friday, June 22 +
    +
    +

    If you drink the Rails koolaid you may have read the notorious single layer of cleverness post by DHH. [5th post on the archive page] In a nutshell he states that it's better to have a single point of cleverness when it comes to business logic. The reasons for this include staying agile, staying in Ruby all the time, and being able to switch the back-end DB at any time. Put the logic in ActiveRecord and use the DB as a dumb data store, that is the Rails way. It's simple. It works. You don't need to be a DBA to be a Rails developer.

    + + +

    Stephen created a Rails plugin called dependent-raise which imitates a foreign key constraint inside of Rails. I want to try this out because I believe that data integrity is fairly important, but it's really starting to make me think about this single point of cleverness idea.

    + + +

    Are we not reinventing the wheel by employing methods such as this in our code? Capable DBs already do this sort of thing for us. I don't necessarily think it's bad to implement this sort of thing, but I think it's a symptom of NIH syndrome. Instead of reinventing this kind of thing why don't we embrace the DB as a semi-intelligent data store? The work has been done all we have to do is exploit it via Rails.

    + + +

    There are a few reasons that the Rails folks choose not to do so but perhaps some of them could be worked around. Adapting your solution as you progress and realise that things aren't exactly as you thought they were... I believe the word for that sort of thing is agility.

    + + +

    Database agnosticism

    + + +

    From SQLite to Oracle, just configure the connection, migrate, and run your app on any database. One of the biggest Rails myths that is backed by the Rails team themselves. It takes a fair amount of work to ensure that any significant app is fully agnostic. Sure you can develop on SQLite and deploy on MySQL without much trouble but there are significant diffirences between RDBMSs that will manifest themselves if you create an app that's more than a toy. Oh, you used finder_sql? Sorry but chances are your app is no longer DB agnostic. FAIL.

    + + +

    Solution: Drop the lie. Tell people the truth. Theoretically, theory and practice are the same; in practice they are not. Be honest that it's possible to be DB-agnostic but can be a challenge. Under no circumstances should we shun something useful in the name of claiming to be DB-agnostic.

    + + +

    Staying agile

    + + +

    If we start making use of FK constraints then we'll have to make changes to both our DB and our code. This makes change more time-consuming and error-prone which means change is less likely to happen. This goes against the grain of an agile methodology. Or does it?

    + + +

    Solution: Rails should use the features of the DB to keep data intact and fall back on an AR-only solution only if the DB doesn't support the operation. There doesn't need to be any duplication in logic rules either. If Rails could recognise a FK constraint that cascades on delete it could set up the has_many :foos, :dependent => :destroy relation for us. In fact I only see our code becoming DRYer (maybe even too DRY[1]).

    + + +

    Staying in Ruby

    + + +

    Using the DB from within Ruby is a solved problem. I don't see why this couldn't be extended to handle more of the DB as well. Use Ruby, but use it intelligently by embracing outside tools to get the job done.

    + + +

    Many relationships could be derived from constraints as people have pointed out before. There are benefits to using the features of a decent RDBMS, and in some cases I think that we might be losing by not making use of them. I am not saying we should move everything to the DB, I am saying that we should exploit the implemented and debugged capabilities of our RDBMSs the best we can while practicing the agile methods we know and love, all from within Ruby.

    + + +

    [1] I make liberal use of annotate_models as it is.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Finnish court rules CSS ineffective at protecting DVDs.html b/wayback/@done/sjs Finnish court rules CSS ineffective at protecting DVDs.html new file mode 100644 index 0000000..6c4a883 --- /dev/null +++ b/wayback/@done/sjs Finnish court rules CSS ineffective at protecting DVDs.html @@ -0,0 +1,617 @@ + + + + sjs: Finnish court rules CSS ineffective at protecting DVDs + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Finnish court rules CSS ineffective at protecting DVDs + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, May 26 +
    +
    +

    It's nice to see people making sane calls on issues like this. Ars has a nice summary and there's also a press release.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Floating point in ElSchemo.html b/wayback/@done/sjs Floating point in ElSchemo.html new file mode 100644 index 0000000..fd53aed --- /dev/null +++ b/wayback/@done/sjs Floating point in ElSchemo.html @@ -0,0 +1,1006 @@ + + + + sjs: Floating point in ElSchemo + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Floating point in ElSchemo + + 0 + +

    +
    + Posted by sjs +
    +on Sunday, June 24 +
    +
    +

    Parsing floating point numbers

    + + +

    The first task is extending the LispVal type to grok floats.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    type LispInt = Integer
    +type LispFloat = Float
    +
    +-- numeric data types
    +data LispNum = Integer LispInt
    +             | Float LispFloat
    +
    +-- data types
    +data LispVal = Atom String
    +             | List [LispVal]
    +             | DottedList [LispVal] LispVal
    +             | Number LispNum
    +             | Char Char
    +             | String String
    +             | ...
    + + +

    The reason for using the new LispNum type and not just throwing a new Float Float constructor in there is so that functions can accept and operate on parameters of any supported numeric type. First the floating point numbers need to be parsed. For now I only parse floating point numbers in decimal because the effort to parse other bases is too great for the benefits gained (none, for me).

    + + +

    ElSchemo now parses negative numbers so I'll start with 2 helper functions that are used when parsing both integers and floats:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    parseSign :: Parser Char
    +parseSign = do try (char '-')
    +           <|> do optional (char '+')
    +                  return '+'
    +
    +applySign :: Char -> LispNum -> LispNum
    +applySign sign n = if sign == '-' then negate n else n
    + + +

    parseSign is straightforward as it follows the convention that a literal number is positive unless explicitly marked as negative with a leading minus sign. A leading plus sign is allowed but not required.

    + + +

    applySign takes a sign character and a LispNum and negates it if necessary, returning a LispNum.

    + + +

    Armed with these 2 functions we can now parse floating point numbers in decimal. Conforming to R5RS an optional #d prefix is allowed.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +
    parseFloat :: Parser LispVal
    +parseFloat = do optional (string "#d")
    +                sign <- parseSign
    +                whole <- many1 digit
    +                char '.'
    +                fract <- many1 digit
    +                return . Number $ applySign sign (makeFloat whole fract)
    +    where makeFloat whole fract = Float . fst . head . readFloat $ whole ++ "." ++ fract
    + + +

    The first 6 lines should be clear. Line 7 simply applies the parsed sign to the parsed number and returns it, delegating most of the work to makeFloat. makeFloat in turn delegates the work to the readFloat library function, extracts the result and constructs a LispNum for it.

    + + +

    The last step for parsing is to modify parseExpr to try and parse floats.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +
    -- Integers, floats, characters and atoms can all start with a # so wrap those with try.
    +-- (Left factor the grammar in the future)
    +parseExpr :: Parser LispVal
    +parseExpr = (try parseFloat)
    +        <|> (try parseInteger)
    +        <|> (try parseChar)
    +        <|> parseAtom
    +        <|> parseString
    +        <|> parseQuoted
    +        <|> do char '('
    +               x <- (try parseList) <|> parseDottedList
    +               char ')'
    +               return x
    +        <|> parseComment
    + + +

    Displaying the floats

    + + +

    That's it for parsing, now let's provide a way to display these suckers. LispVal is an instance of show, where show = showVal so showVal is our first stop. Remembering that LispVal now has a single Number constructor we modify it accordingly:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    showVal (Number n) = showNum n
    +
    +showNum :: LispNum -> String
    +showNum (Integer contents) = show contents
    +showNum (Float contents) = show contents
    +
    +instance Show LispNum where show = showNum
    + + +

    One last, and certainly not least, step is to modify eval so that numbers evaluate to themselves.

    + + +
    eval env val@(Number _) = return val
    + +

    There's a little more housekeeping to be done such as fixing integer?, number?, implementing float? but I will leave those as an exercise to the reader, or just wait until I share the full code. As it stands now floating point numbers can be parsed and displayed. If you fire up the interpreter and type 2.5 or -10.88 they will be understood. Now try adding them:

    + + +
    (+ 2.5 1.1)
    +Invalid type: expected integer, found 2.5
    + +

    Oops, we don't know how to operate on floats yet!

    + + +

    Operating on floats

    + + +

    Parsing was the easy part. Operating on the new floats is not necessarily difficult, but it was more work than I realized it would be. I don't claim that this is the best or the only way to operate on any LispNum, it's just the way I did it and it seems to work. There's a bunch of boilerplate necessary to make LispNum an instance of the required classes, Eq, Num, Real, and Ord. I don't think I have done this properly but for now it works. What is clearly necessary is the code that operates on different types of numbers. I think I've specified sane semantics for coercion. This will be very handy shortly.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +19
    +20
    +21
    +22
    +23
    +24
    +25
    +26
    +27
    +28
    +29
    +30
    +31
    +32
    +33
    +34
    +35
    +36
    +37
    +38
    +39
    +40
    +41
    +42
    +43
    +44
    +45
    +46
    +47
    +48
    +49
    +50
    +51
    +52
    +53
    +54
    +55
    +56
    +57
    +58
    +59
    +60
    +61
    +62
    +63
    +64
    +65
    +66
    +67
    +68
    +69
    +70
    +
    lispNumEq :: LispNum -> LispNum -> Bool
    +lispNumEq (Integer arg1) (Integer arg2) = arg1 == arg2
    +lispNumEq (Integer arg1) (Float arg2) = (fromInteger arg1) == arg2
    +lispNumEq (Float arg1) (Float arg2) = arg1 == arg2
    +lispNumEq (Float arg1) (Integer arg2) = arg1 == (fromInteger arg2)
    +
    +instance Eq LispNum where (==) = lispNumEq
    +
    +lispNumPlus :: LispNum -> LispNum -> LispNum
    +lispNumPlus (Integer x) (Integer y) = Integer $ x + y
    +lispNumPlus (Integer x) (Float y)   = Float $ (fromInteger x) + y
    +lispNumPlus (Float x)   (Float y)   = Float $ x + y
    +lispNumPlus (Float x)   (Integer y) = Float $ x + (fromInteger y)
    +
    +lispNumMinus :: LispNum -> LispNum -> LispNum
    +lispNumMinus (Integer x) (Integer y) = Integer $ x - y
    +lispNumMinus (Integer x) (Float y)   = Float $ (fromInteger x) - y
    +lispNumMinus (Float x)   (Float y)   = Float $ x - y
    +lispNumMinus (Float x)   (Integer y) = Float $ x - (fromInteger y)
    +
    +lispNumMult :: LispNum -> LispNum -> LispNum
    +lispNumMult (Integer x) (Integer y) = Integer $ x * y
    +lispNumMult (Integer x) (Float y)   = Float $ (fromInteger x) * y
    +lispNumMult (Float x)   (Float y)   = Float $ x * y
    +lispNumMult (Float x)   (Integer y) = Float $ x * (fromInteger y)
    +
    +lispNumDiv :: LispNum -> LispNum -> LispNum
    +lispNumDiv (Integer x) (Integer y) = Integer $ x `div` y
    +lispNumDiv (Integer x) (Float y)   = Float $ (fromInteger x) / y
    +lispNumDiv (Float x)   (Float y)   = Float $ x / y
    +lispNumDiv (Float x)   (Integer y) = Float $ x / (fromInteger y)
    +
    +lispNumAbs :: LispNum -> LispNum
    +lispNumAbs (Integer x) = Integer (abs x)
    +lispNumAbs (Float x) = Float (abs x)
    +
    +lispNumSignum :: LispNum -> LispNum
    +lispNumSignum (Integer x) = Integer (signum x)
    +lispNumSignum (Float x) = Float (signum x)
    +
    +instance Num LispNum where
    +    (+) = lispNumPlus
    +    (-) = lispNumMinus
    +    (*) = lispNumMult
    +    abs = lispNumAbs
    +    signum = lispNumSignum
    +    fromInteger x = Integer x
    +
    +
    +lispNumToRational :: LispNum -> Rational
    +lispNumToRational (Integer x) = toRational x
    +lispNumToRational (Float x) = toRational x
    +
    +instance Real LispNum where
    +    toRational = lispNumToRational
    +
    +
    +lispIntQuotRem :: LispInt -> LispInt -> (LispInt, LispInt)
    +lispIntQuotRem n d = quotRem n d
    +
    +lispIntToInteger :: LispInt -> Integer
    +lispIntToInteger x = x
    +
    +lispNumLessThanEq :: LispNum -> LispNum -> Bool
    +lispNumLessThanEq (Integer x) (Integer y) = x <= y
    +lispNumLessThanEq (Integer x) (Float y)   = (fromInteger x) <= y
    +lispNumLessThanEq (Float x)   (Integer y) = x <= (fromInteger y)
    +lispNumLessThanEq (Float x)   (Float y)   = x <= y
    +
    +instance Ord LispNum where (<=) = lispNumLessThanEq
    + + +

    Phew, ok with that out of the way now we can actually extend our operators to work with any type of LispNum. Our Scheme operators are defined using the functions numericBinop and numBoolBinop. First we'll slightly modify our definition of primitives:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
    +primitives = [("+", numericBinop (+)),
    +              ("-", subtractOp),
    +              ("*", numericBinop (*)),
    +              ("/", floatBinop (/)),
    +              ("mod", integralBinop mod),
    +              ("quotient", integralBinop quot),
    +              ("remainder", integralBinop rem),
    +              ("=", numBoolBinop (==)),
    +              ("<", numBoolBinop (<)),
    +              (">", numBoolBinop (>)),
    +              ("/=", numBoolBinop (/=)),
    +              (">=", numBoolBinop (>=)),
    +              ("<=", numBoolBinop (<=)),
    +              ...]
    + + +

    Note that mod, quotient, and remainder are only defined for integers and as such use integralBinop, while division (/) is only defined for floating point numbers using floatBinop. subtractOp is different to support unary usage, e.g. (- 4) => -4, but it uses numericBinop internally when more than 1 argument is given. On to the implementation! First extend unpackNum to work with any LispNum, and provide separate unpackInt and unpackFloat functions to handle both kinds of LispNum.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    unpackNum :: LispVal -> ThrowsError LispNum
    +unpackNum (Number (Integer n)) = return $ Integer n
    +unpackNum (Number (Float n)) = return $ Float n
    +unpackNum notNum = throwError $ TypeMismatch "number" notNum
    +
    +unpackInt :: LispVal -> ThrowsError Integer
    +unpackInt (Number (Integer n)) = return n
    +unpackInt (List [n]) = unpackInt n
    +unpackInt notInt = throwError $ TypeMismatch "integer" notInt
    +
    +unpackFloat :: LispVal -> ThrowsError Float
    +unpackFloat (Number (Float f)) = return f
    +unpackFloat (Number (Integer f)) = return $ fromInteger f
    +unpackFloat (List [f]) = unpackFloat f
    +unpackFloat notFloat = throwError $ TypeMismatch "float" notFloat
    + + +

    The initial work of separating integers and floats into the LispNum abstraction, and the code I said would be handy shortly, are going to be really handy here. There's relatively no change in numericBinop except for the type signature. integralBinop and floatBinop are just specific versions of the same function. I'm sure there's a nice Haskelly way of doing this with less repetition, and I welcome such corrections.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +16
    +17
    +18
    +
    numericBinop :: (LispNum -> LispNum -> LispNum) -> [LispVal] -> ThrowsError LispVal
    +numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
    +numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op
    +
    +integralBinop :: (LispInt -> LispInt -> LispInt) -> [LispVal] -> ThrowsError LispVal
    +integralBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
    +integralBinop op params = mapM unpackInt params >>= return . Number . Integer . foldl1 op
    +
    +floatBinop :: (LispFloat -> LispFloat -> LispFloat) -> [LispVal] -> ThrowsError LispVal
    +floatBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
    +floatBinop op params = mapM unpackFloat params >>= return . Number . Float . foldl1 op
    +
    +subtractOp :: [LispVal] -> ThrowsError LispVal
    +subtractOp num@[_] = unpackNum (head num) >>= return . Number . negate
    +subtractOp params = numericBinop (-) params
    +
    +numBoolBinop :: (LispNum -> LispNum -> Bool) -> [LispVal] -> ThrowsError LispVal
    +numBoolBinop op params = boolBinop unpackNum op params
    + + +

    That was a bit of work but now ElSchemo supports floating point numbers, and if you're following along then your Scheme might too if I haven't missed any important details!

    + + +

    Next time I'll go over some of the special forms I have added, including short-circuiting and and or forms and the full repetoire of let, let*, and letrec. Stay tuned!

    + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Gtkpod in Gutsy Got You Groaning .html b/wayback/@done/sjs Gtkpod in Gutsy Got You Groaning .html new file mode 100644 index 0000000..83ec36a --- /dev/null +++ b/wayback/@done/sjs Gtkpod in Gutsy Got You Groaning .html @@ -0,0 +1,686 @@ + + + + sjs: Gtkpod in Gutsy Got You Groaning? + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Gtkpod in Gutsy Got You Groaning? + + 3 + +

    +
    + Posted by sjs +
    +on Monday, October 29 +
    +
    +

    I recently upgraded the Ubuntu installation on my workstation from Feisty Fawn to Gutsy Gibbon and for the most part I am happy with the changes. One thing I don't care much for is the fact that gtkpod-aac is a sham. Ubuntu provides the gtkpod-aac package for one to transfer aac files, and thus mp4 files with aac audio tracks, to their iPod. The version in the Gutsy repos is broken. This shows a weakness in Ubuntu, and though it's rather small it is one that will piss off a lot of people who expect things to just work. The kind of people who would buy an iPod. The kind of people who use Linux. The kind of Linux users that use Ubuntu. The kicker is that it doesn't look like they will ship a working version of gtkpod-aac for Gutsy at all. I know it's only 6 months but that seems like an eternity when you have the same old crap to watch on your iPod for that long.

    + + +

    All is not lost. A kind soul left a helpful comment on the bug report explaining how he got it to work. It's a pretty simple fix. Just google for libmpeg4ip and find a Debian repo that has the following packages for your architecture:

    + + +
      +
    • libmpeg4ip-0
    • +
    • libmpeg4ip-dev
    • +
    • libmp4v2-0
    • +
    • libmp4v2-dev
    • +
    + + +

    Download those 4 .deb files and install them. You can ignore any advise to use an older version in the official repo. Once you have those installed, download and build the latest version of gtkpod from their Subversion repo.

    + + +

    Now that you know what to do I'll give you what you probably wanted at the beginning. As long as you have wget, subversion, and use a Bourne-like shell this should work for you.

    + + +

    gtkpod-aac-fix.sh

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +
    mkdir /tmp/gtkpod-fix
    +cd /tmp/gtkpod-fix
    +wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmp4v2-0_1.5.0.1-0.3_amd64.deb
    +wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmp4v2-dev_1.5.0.1-0.3_amd64.deb
    +wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmpeg4ip-0_1.5.0.1-0.3_amd64.deb
    +wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmpeg4ip-dev_1.5.0.1-0.3_amd64.deb
    +for f in *.deb; do sudo gdebi -n "$f"; done
    +svn co https://gtkpod.svn.sourceforge.net/svnroot/gtkpod/gtkpod/trunk gtkpod
    +cd gtkpod
    +./autogen.sh --with-mp4v2 && make && sudo make install
    +cd
    +rm -rf /tmp/gtkpod-fix
    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + Bascht – + November 07, 2007 @ 03:45 PM +
      +
      +

      Thank you. You saved my day! :)

      +
      +
    2. + +
    3. +
      + Martin Clausen – + November 22, 2007 @ 04:33 AM +
      +
      +

      Thanks a lot. I got it working based on above. You might want to mention that there is a lot of dependencies that needs to be fulfilled.

      + +

      /mac

      +
      +
    4. + +
    5. +
      + cicala – + November 23, 2007 @ 04:56 PM +
      +
      +

      thanks... works great ;)

      +
      +
    6. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Learning Lisp Read PCL.html b/wayback/@done/sjs Learning Lisp Read PCL.html new file mode 100644 index 0000000..096db07 --- /dev/null +++ b/wayback/@done/sjs Learning Lisp Read PCL.html @@ -0,0 +1,617 @@ + + + + sjs: Learning Lisp? Read PCL + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Learning Lisp? Read PCL + + 0 + +

    +
    + Posted by sjs +
    +on Tuesday, September 25 +
    +
    +

    Yes, it's a book. But it's so well written you should breeze through it as if it were a Lisp tutorial!

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs More Scheming with Haskell.html b/wayback/@done/sjs More Scheming with Haskell.html new file mode 100644 index 0000000..8726c9f --- /dev/null +++ b/wayback/@done/sjs More Scheming with Haskell.html @@ -0,0 +1,646 @@ + + + + sjs: More Scheming with Haskell + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + More Scheming with Haskell + + 2 + +

    +
    + Posted by sjs +
    +on Thursday, June 14 +
    +
    +

    It's been a little while since I wrote about Haskell and the Scheme interpreter I've been using to learn and play with both Haskell and Scheme. I finished the tutorial and got myself a working Scheme interpreter and indeed it has been fun to use it for trying out little things now and then. (Normally I would use Emacs or Dr. Scheme for that sort of thing.) There certainly are interesting things to try floating around da intranet. And also things to read and learn from, such as misp (via Moonbase).

    + + +

    I'm going to describe two new features of my Scheme in this post. The second one is more interesting and was more fun to implement (cond).

    + + +

    Pasing Scheme integers

    + + +

    Last time I left off at parsing R5RS compliant numbers, which is exercise 3.3.4 if you're following along the tutorial. Only integers in binary, octal, decimal, and hexadecimal are parsed right now. The syntaxes for those are #b101010, #o52, 42 (or #d42), and #x2a, respectively. To parse these we use the readOct, readDec, readHex, and readInt functions provided by the Numeric module, and import them thusly:

    + + +
    import Numeric (readOct, readDec, readHex, readInt)
    + +

    In order to parse binary digits we need to write a few short functions to help us out. For some reason I couldn't find binDigit, isBinDigit and readBin in their respective modules but luckily they're trivial to implement. The first two are self-explanatory, as is the third if you look at the implementation of its relatives for larger bases. In a nutshell readBin says to: "read an integer in base 2, validating digits with isBinDigit."

    + + +
    -- parse a binary digit, analagous to decDigit, octDigit, hexDigit
    +binDigit :: Parser Char
    +binDigit = oneOf "01" 
    +
    +-- analogous to isDigit, isOctdigit, isHexDigit
    +isBinDigit :: Char -> Bool
    +isBinDigit c = (c == '0' || c == '1')
    +
    +-- analogous to readDec, readOct, readHex
    +readBin :: (Integral a) => ReadS a
    +readBin = readInt 2 isBinDigit digitToInt
    + +

    The next step is to augment parseNumber so that it can handle R5RS numbers in addition to regular decimal numbers. To refresh, the tutorial's parseNumber function looks like this:

    + + +
    parseNumber :: Parser LispVal
    +parseNumber = liftM (Number . read) $ many1 digit
    + +

    Three more lines in this function will give us a decent starting point:

    + + +
    parseNumber = do char '#'
    +                 base <- oneOf "bdox" 
    +                 parseDigits base
    +           <|> (many1 digit >>= return . Number . read)
    + +

    Translation: First look for an R5RS style base, and if found call parseDigits with the given base to do the dirty work. If that fails then fall back to parsing a boring old string of decimal digits.

    + + +

    That brings us to actually parsing the numbers. parseDigits is simple, but there might be a more Haskell-y way of doing this.

    + + +
    -- Parse a string of digits in the given base.
    +parseDigits :: Char -> Parser LispVal
    +parseDigits base = do digits <- many1 d
    +                      return . Number . fst . head . f $ digits
    +                      where f = case base of
    +                                  'b' -> readBin
    +                                  'd' -> readDec
    +                                  'o' -> readOct
    +                                  'x' -> readHex
    +                            d = case base of
    +                                  'b' -> binDigit
    +                                  'd' -> digit
    +                                  'o' -> octDigit
    +                                  'x' -> hexDigit
    + +

    The trickiest part of all this was figuring out how to use the various readFoo functions properly. They return a list of pairs so head grabs the first pair and fst grabs the first element of the pair. Once I had that straight it was smooth sailing. Having done this, parsing R5RS characters (#\a, #\Z, #\?, ...) is a breeze so I won't bore you with that.

    + + +

    The cond function

    + + +

    It still takes me some time to knit together meaningful Haskell statements. Tonight I spent said time cobbling together an implementation of cond as a new special form. Have a look at the code. The explanation follows.

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +
    eval env (List (Atom "cond" : List (Atom "else" : exprs) : [])) =
    +    liftM last $ mapM (eval env) exprs
    +eval env (List (Atom "cond" : List (pred : conseq) : rest)) = 
    +    do result <- eval env $ pred
    +       case result of
    +         Bool False -> case rest of
    +                         [] -> return $ List []
    +                         _ -> eval env $ List (Atom "cond" : rest)
    +         _ -> liftM last $ mapM (eval env) conseq
    + + +
      +
    • Lines 1-2: Handle else clauses by evaluating the given expression(s), returning the last result. It must come first or it's overlapped by the next pattern.
    • +
    • Line 3: Evaluate a cond by splitting the first condition into predicate and consequence, tuck the remaining conditions into rest for later.
    • +
    • Line 4: Evaluate pred
    • +
    • Line 5: and if the result is:
    • +
    • Line 6: #f then look at the rest of the conditions.
    • +
    • Line 7: If there are no more conditions return the empty list.
    • +
    • Line 8: Otherwise call ourselves recursively with the remaining conditions.
    • +
    • Line 9: Anything other than #f is considered true and causes conseq to be evaluated and returned. Like else, conseq can be a sequence of expressions.
    • +
    + + +

    So far my Scheme weighs in at 621 lines, 200 more than the tutorial's final code listing. Hopefully I'll keep adding things on my TODO list and it will grow a little bit more. Now that I have cond it will be more fun to expand my stdlib.scm as well.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + whoopee – + June 14, 2007 @ 08:57 AM +
      +
      +

      thanks! just last night i was thinking - hmm, i have this haskell program that takes what i want to be an Integer from the command line - how do i enforce this? your post is relevant to these issues...thanks!

      +
      +
    2. + +
    3. +
      + sjs – + June 15, 2007 @ 09:39 AM +
      +
      +

      Sure, it's good to know that someone found something I said useful. :)

      +
      +
    4. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + diff --git a/wayback/@done/sjs Opera is pretty slick.html b/wayback/@done/sjs Opera is pretty slick.html new file mode 100644 index 0000000..5cb1123 --- /dev/null +++ b/wayback/@done/sjs Opera is pretty slick.html @@ -0,0 +1,629 @@ + + + + sjs: Opera is pretty slick + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Opera is pretty slick + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, August 11 +
    +
    +

    Though I usually prefer free software, I don't have any problems using proprietary stuff if I think it's good. I had Firefox open for a couple of days and noticed that it was using 700M of memory. That's not a problem at all since I have 4G but it's also a lot of RAM to be in use for just one window with one tab open. The fact that Firefox gets sluggish after some time and needs to be restarted tells me that this isn't expected behaviour and is likely not due to caching for quick back/forward or whatever they claim is taking up the leaked memory.

    + + +

    Konqueror is ok but I'm not a huge fan of it, partly due to its kitchen-sink browser/file manager hybrid design. IMO the KDE folks should break out the file manager part, but I digress. I can't really put my finger on anything specific I dislike about Konqueror, it's just not for me. To my dismay it seems to be the snappiest browser on Linux.

    + + +

    The only other decent browser I know of (for Linux) is Opera so I found some quick instructions on the Ubuntu forums and shoehorned the x86 build of it into my amd64 installation. Everything went well, Flash works and all that stuff. Opera is not nearly as snappy as I like but it is still fairly pleasant to use, once you find a skin that fits into your desktop. For the record Firefox isn't snappy enough either. Apart from AdBlock I don't miss many extensions for every day browsing.

    + + +

    I'm not sure if I'm going to stick with it yet but I've been using it for 2 days and haven't really missed Firefox at all. Of course as soon as I do any development I need Firefox for Firebug and the Web Developer extension and such. I've yet to investigate development tools on Opera. I'm comfortable developing in Firefox already so why switch?

    + + +

    Man am I glad we're not in a Netscape/IE world anymore! If I open up my MacBook I can choose from at least 2 other browsers for every day browsing (Camino, Safari).

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Project Euler code repo in Arc.html b/wayback/@done/sjs Project Euler code repo in Arc.html new file mode 100644 index 0000000..1ffa6bd --- /dev/null +++ b/wayback/@done/sjs Project Euler code repo in Arc.html @@ -0,0 +1,624 @@ + + + + sjs: Project Euler code repo in Arc + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Project Euler code repo in Arc + + 0 + +

    +
    + Posted by sjs +
    +on Monday, March 03 +
    +
    +

    Release early and often. This is a code repo web app for solutions to Project Euler problems. You can only see your own solutions so it's not that exciting yet (but it scratches my itch... once it highlights syntax). You can try it out or download the source. You'll need an up-to-date copy of Anarki to untar the source in. Just run arc.sh then enter this at the REPL:

    + + +
    arc> (load "euler.arc")
    +arc> (esv)
    +
    + +

    That will setup the web server on port 3141. If you want a different port then run (esv 25) (just to mess with ‘em).

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Propaganda makes me sick.html b/wayback/@done/sjs Propaganda makes me sick.html new file mode 100644 index 0000000..4759ff1 --- /dev/null +++ b/wayback/@done/sjs Propaganda makes me sick.html @@ -0,0 +1,650 @@ + + + + sjs: Propaganda makes me sick + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Propaganda makes me sick + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    Things like this in modern times are surprising. Can't people spot this phony crap for what it is?

    + + +

    First they put away the dealers, keep our kids safe and off the streets
    +Then they put away the prostitutes, keep married men cloistered at home
    +Then they shooed away the bums, and they beat and bashed the queers
    +Turned away asylum-seekers, fed us suspicions and fears
    +We didn't raise our voice, we didn't make a fuss
    +It´s funny there was no one left to notice, when they came for us
    +
    +Looks like witches are in season, you better fly your flag and be aware
    +Of anyone who might fit the description, diversity is now our biggest fear
    +Now with our conversations tapped, and our differences exposed
    +How ya supposed to love your neighbour, with our minds and curtains +closed?
    +We used to worry ‘bout big brother
    +Now we got a big father and an even bigger mother

    +
    +And still you believe, this aristocracy gives a fuck about you
    +They put the mock in democracy, and you swallowed every hook
    +The sad truth is, you'd rather follow the school into the net
    +‘Cause swimming alone at sea, is not the kind of freedom that you +actually want
    +So go back to your crib, and suck on a tit
    +Bask in the warmth of your diaper, you're sitting in shit
    +And piss, while sucking on a giant pacifier
    +A country of adult infants, a legion of mental midgets
    +A country of adult infants, a country of adult infants
    +All regaining their unconsciousness
    +
    +—from the song Regaining Unconsciousness, by NOFX

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Python and Ruby brain dump.html b/wayback/@done/sjs Python and Ruby brain dump.html new file mode 100644 index 0000000..471816c --- /dev/null +++ b/wayback/@done/sjs Python and Ruby brain dump.html @@ -0,0 +1,638 @@ + + + + sjs: Python and Ruby brain dump + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Python and Ruby brain dump + + 0 + +

    +
    + Posted by sjs +
    +on Wednesday, September 26 +
    +
    +

    It turns out that Python is the language of choice on the OLPC, both for implementing applications and exposing to the users. There is a view source key available. I think Python is a great choice.

    + + +

    I've been using Ruby almost exclusively for over a year but the last week I've been doing a personal project in Python using Storm (which is pretty nice btw) and urwid. I'm remembering why I liked Python when I first learned it a few years ago. It may not be as elegant as Ruby, conceptually, but it sure is fun to code in. It really is executable pseudo-code for the most part.

    + + +

    I'm tripping up by typing obj.setattr^W^Wsetattr(obj and def self.foo^W^Wfoo(self but other than that I haven't had trouble switching back into Python. I enjoy omitting end statements. I enjoy Python's lack of curly braces, apart from literal dicts. I hate the fact that in Emacs, in python-mode, indent-region only seems to piss me off (or indent-* really, anything except TAB). I really like list comprehensions.

    + + +

    The two languages are so similar that at a glance you may think there are only shallow differences between the languages. People are always busy arguing about the boring things that every language can do (web frameworks anyone?) while ignoring the interesting differences between the languages and their corresponding ecosystems.

    + + +

    Python has more libraries available as it's the more popular language. The nature of software written in the languages is different though as the languages themselves are quite different.

    + + +

    Ruby has some Perl-ish features that make it a good sysadmin scripting language, hence we see nice tools such as Capistrano and god written in Ruby and used by projects written in other languages.

    + + +

    Python is faster than Ruby so it is open to classes of software that would be cumbersome in Ruby. Source control, for example. You can write a slow SCM in Python though, as Bazaar demonstrates. You could probably write a passable one in Ruby as well. If it didn't quite perform well enough right now it should fare better in a year's time.

    + + +

    I still think that my overall joy is greater when using Ruby, but if Ruby isn't the right tool for the job I'll probably look to Python next (unless some feature of the problem indicates something else would be more appropriate). The reason I chose Python for my current project is because of libs like urwid and I needed an excuse to try out Storm and brush up on my Python. ;-)

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Quickly inserting millions of rows with MySQL InnoDB.html b/wayback/@done/sjs Quickly inserting millions of rows with MySQL InnoDB.html new file mode 100644 index 0000000..0e91486 --- /dev/null +++ b/wayback/@done/sjs Quickly inserting millions of rows with MySQL InnoDB.html @@ -0,0 +1,690 @@ + + + + sjs: Quickly inserting millions of rows with MySQL/InnoDB + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Quickly inserting millions of rows with MySQL/InnoDB + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, April 26 +
    +
    +

    The absolute first thing you should do is check your MySQL configuration to make sure it’s sane for the system you’re using. I kept getting a ‘The table is too large’ error on my Gentoo box after inserting several million rows because the default config limits the InnoDB tablespace size to 128M. It was also tuned for a box with as little as 64M of RAM. That’s cool for a small VPS or your old Pentium in the corner collecting dust. For a modern server, workstation, or even notebook with gigs of RAM you’ll likely want to make some changes.

    + + +

    Tweaking my.cnf

    + + +

    Here are the relevant settings you can tweak in order to work with large datasets efficiently. These are set in your my.cnf file, which varies in location.

    + + +

    On Gentoo it resides at /etc/mysql/my.cnf.

    + + +

    When MySQL 5.x is installed via DarwinPorts on Mac OS X you need to copy one of the defaults from /opt/local/share/mysql5/mysql/ to /opt/local/etc/mysql5/my.cnf and then modify it accordingly.

    + + +

    If you use another system you’re on your own. If you can’t figure it out, please put down the text editor and leave the poor config file alone! Jokes aside this really is not difficult if you’re used to configuring *nix programs.

    + + +

    innodb_buffer_pool_size

    + + +

    This determines how much memory MySQL uses for table indexes and data. You can set it as low as 8-10M, or high as 50-80% of your memory on a dedicated MySQL server. I have RAM to burn1 in my workstation so I set this to 200M, 20% of my 1GB.

    + + +

    [1] I run Fluxbox on Gentoo, I use 200-300M of my 1GB on average and with 200M for MySQL 409M are in use at this moment. Gotta love those lightweight window managers!

    + + +

    innodb_additional_mem_pool_size

    + + +

    According to a post1 on a MySQL mailing list, modern OSs have fast enough mallocs and this variable has little effect on performance. I set mine to 16M before reading that post, so I’ll just leave it at that.

    + + +

    [1] http://lists.mysql.com/mysql/129247

    + + +

    innodb_data_file_path

    + + +

    On Gentoo this one bit me right in the ass, and I mentioned it above. It specifies how large the files used to store your data can be, and how many of them there are. The default setting is almost sane: ibdata1:10M:autoextend:max:128M. Limiting the total size to 128M caused my test to fail after inserting several million rows.

    + + +

    Simply removing max:128M solves the problem. The resulting setting tells the InnoDB engine to use one file, named ibdata1 which is initially 10M in size and grows as required.

    + + +

    innodb_log_file_size

    + + +

    The default Gentoo config says they (whoever they are) keep this at 25% of innodb_buffer_pool_size so I did just that. 50M in my case.

    + + +

    innodb_log_buffer_size

    + + +

    Again I only went as far as the Gentoo config to learn about this setting. They had it at 8M and recommend increasing it if you have large transactions. I can’t think of any particularly large transactions I currently use but I doubled it to 16M anyway.

    + + +

    Save my.cnf and restart mysqld

    + + +

    That’s it for the MySQL config. Restart mysqld however you do that on your platform. sudo /etc/init.d/mysql restart should look familiar to many *nix users.

    + + +

    Now you should be able to insert dozens and indeed hundreds of millions of rows into your InnoDB tables. Sadly this brought little performance gains to the table. MySQL wraps single queries in implicit transactions. Wrapping everything in a transaction may work, but inevitably something will go wrong and you may want the ability to resume inserting the rows instead of starting all over.

    + + +

    The solution now is to execute SET AUTOCOMMIT=0 before inserting the data, and then issuing a COMMIT when you’re done. With all that in place I’m inserting 14,000,000 rows into both MyISAM and InnoDB tables in 30 minutes. MyISAM is still ~ 2 min faster, but as I said earlier this is adequate for now. Prior to all this it took several hours to insert 14,000,000 rows so I am happy.

    + + +

    Now you can enjoy the speed MyISAM is known for with your InnoDB tables. Consider the data integrity a bonus! ;-)

    + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs RTFM!.html b/wayback/@done/sjs RTFM!.html new file mode 100644 index 0000000..c65dad4 --- /dev/null +++ b/wayback/@done/sjs RTFM!.html @@ -0,0 +1,608 @@ + + + + sjs: RTFM! + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + RTFM! + + 0 + +

    +
    + Posted by sjs +
    +on Monday, June 25 +
    +
    +

    I should read the Emacs manual sometime, especially since I have it in dead-tree form. Check out skeleton pairs in the Emacs manual, or better yet C-h f skeleton-pair-insert-maybe. skeleton-pair has already been massaged to do what you most likely want if you set the correct options. Cool. I like Emacs more every day.

    + + +

    This renders wrap-region useless, which is great! I like a trim .emacs and .emacs.d.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Random pet peeve of the day.html b/wayback/@done/sjs Random pet peeve of the day.html new file mode 100644 index 0000000..9a5eea4 --- /dev/null +++ b/wayback/@done/sjs Random pet peeve of the day.html @@ -0,0 +1,632 @@ + + + + sjs: Random pet peeve of the day + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Random pet peeve of the day + + 1 + +

    +
    + Posted by sjs +
    +on Monday, January 07 +
    +
    +

    So long since my last post, and all I'm going to do is complain. ;-) Seriously though, if you have a website and the content on said site is dated then please - for the love of our almighty saviour, the Flying Spaghetti Monster - put the date at the top of the page. Don't make me scroll down to the end of the article just to see how relevant it is or just to give me some context. Not to mention that I always end up doing a "Where is the end? Oh crap, I passed it and now I'm in the comments, blargh!"

    + + +

    I'm looking at Lifehacker since they're the most recent offender I've come across, but they are definitely not the only ones guilty of this.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + cassandra – + January 07, 2008 @ 07:17 PM +
      +
      +

      How nice to see you posting again... even if it is to complain rolling eyes ! At least I was able to become educated about a new religion?!?!?!

      + +

      When are you going to talk about your trip? Great pictures, by the way! Thanks for sending the link!

      +
      +
    2. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Recent Ruby and Rails Regales.html b/wayback/@done/sjs Recent Ruby and Rails Regales.html new file mode 100644 index 0000000..d3300c6 --- /dev/null +++ b/wayback/@done/sjs Recent Ruby and Rails Regales.html @@ -0,0 +1,638 @@ + + + + sjs: Recent Ruby and Rails Regales + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Recent Ruby and Rails Regales + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, June 28 +
    +
    +

    Some cool Ruby and [the former on] Rails things are springing up and I haven't written much about the two Rs lately, though I work with them daily.

    + + +

    Rails on Rules

    + + +

    My friend Jim Roepcke is researching and implementing a plugin/framework designed to work with Rails called Rails on Rules. His inspiration is the rule system from WebObjects' Direct to Web. He posted a good example for me, but this baby isn't just for template/view logic. If some of the Rails conventions were specified in a default set of rules which the developer could further customize then you basically have a nice way of doing things that you would otherwise code by hand. I think it would be a boon for the ActiveScaffold project. We're meeting up to talk about this soon and I'll have more to say after then, but it sounds pretty cool.

    + + +

    Sake Bomb!

    + + +

    I've noticed a trend among some recent posts about Rake: the authors keep talking about booze. Are we nothing but a bunch of booze hounds?! Well one can hope. There's some motivation to learn more about a tool, having more time to drink after work. This week Chris Wanstrath dropped a Sake Bomb on the Ruby community. Like piston, sake is something you can just pick up and use instantly. Interestingly the different pronunciations of rake and sake help me from confusing the two on the command line... so far.

    + + +

    Secure Associations (for Rails)

    + + +

    Jordan McKible released the secure_associations plugin. It lets you protect your models' *_id attributes from mass-assignment via belongs_to_protected and has_many_protected. It's a mild enhancement, but an enhancement nonetheless. This is useful to enough people that it should be in Rails proper.

    + + +

    Regular expressions and strings with embedded objects

    + + +

    taw taught me a new technique for simplifying regular expressions by transforming the text in a reversible manner. In one example he replaced literal strings in SQL - which are easily parsed via a regex - with what he calls embedded objects. They're just tokens to identify the temporarily removed strings, but the important thing is that they don't interfere with the regexes that operate on the other parts of the SQL, which would have been very difficult to get right with the strings inside it. If I made it sound complicated just read the post, he explains it well.

    + + +

    If you believe anything Steve Yegge says then that last regex trick may come in handy for Q&D parsing in any language, be it Ruby, NBL, or whataver.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Reinventing the wheel.html b/wayback/@done/sjs Reinventing the wheel.html new file mode 100644 index 0000000..9110f8d --- /dev/null +++ b/wayback/@done/sjs Reinventing the wheel.html @@ -0,0 +1,634 @@ + + + + sjs: Reinventing the wheel + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Reinventing the wheel + + 0 + +

    +
    + Posted by sjs +
    +on Wednesday, June 20 +
    +
    +

    Emacs is very impressive. I only felt lost and unproductive for minutes and now it seems natural to use and get around in. I've got ElSchemo set as the default scheme, and running inferior processes interactively is an absolute dream. My scheme doesn't have readline support (which bothers me to the point where I've thought about adding it just so I can use the thing) but when running it under Emacs there's absoutely no need for anything like that since I have the power of my editor when interacting with any program.

    + + +

    There has been a considerable amount of work done to aide in Rails development which makes Emacs especially comfortable for me. I now know why people have Emacs windows maximized on their screens. Because of its age Emacs is a handy window manager that basically eliminates the need for anything like GNU screen or a window manager such as Rat poison (which is great if you like screen), just maximize that Emacs "frame" or open one for each display and get to it. If you need a shell you just split the window and run your shell, when you're done you can easily switch back to your editing and your shell will wait in the background until you need it again. With rails-mode on I can run script/console (or switch back to it) with C-c C-c s c. My zsh alias for script/console is sc and I have other similarly succint ones for other stuff, so I took right to the shortcuts for all the handy things that I no longer have to switch applications to do:

    + + +
      +
    • C-c C-c . - Run the tests for this file. If I'm in a unit test it runs it, if I'm in the model it runs the corresponding unit tests.
    • +
    • C-c C-c w s - Run the web server (script/server).
    • +
    • C-c C-c t - Run tests. The last value entered is the default choice, and the options are analogous to the rake test:* tasks.
    • +
    • and so on...
    • +
    + + +

    The Rails integration is simply stunning and I could go on all day about the mature indentation support, the Speedbar and what not, but I won't. I'm fairly sure that Emacs has taken the place of TextMate as my weapon of choice now, on all platforms. And after only 2 days!

    + + +

    Anyway, the point of all this was to mention the one thing that's missing: support for intelligent snippets which insert text at more than one point in the document (well, they appear to do so). I don't have any E-Lisp-fu to break out and solve the deficiency but if it ever bugs me enough I might try implementing it for Emacs one day. If they were useful to me outside of writing migrations I might have more incentive to do so, but I guess they aren't useful in normal editing situations (maybe I just haven't recognised the need).

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs RushCheck QuickCheck for Ruby.html b/wayback/@done/sjs RushCheck QuickCheck for Ruby.html new file mode 100644 index 0000000..7bb48da --- /dev/null +++ b/wayback/@done/sjs RushCheck QuickCheck for Ruby.html @@ -0,0 +1,617 @@ + + + + sjs: RushCheck: QuickCheck for Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + RushCheck: QuickCheck for Ruby + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, July 05 +
    +
    +

    I cannot wait to try out RushCheck. It is QuickCheck for Ruby. I don't have experience with QuickCheck or anything but it's clear to see how this helps you make certain your code is robust.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs See your regular expressions in Emacs.html b/wayback/@done/sjs See your regular expressions in Emacs.html new file mode 100644 index 0000000..2ebf08d --- /dev/null +++ b/wayback/@done/sjs See your regular expressions in Emacs.html @@ -0,0 +1,623 @@ + + + + sjs: See your regular expressions in Emacs + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + See your regular expressions in Emacs + + 0 + +

    +
    + Posted by sjs +
    +on Friday, July 06 +
    +
    +

    First, if you are an Emacs newbie then be sure to read (at least) the introduction of Being Productive with Emacs. For some reason the PDF and HTML versions are slightly similar.

    + + +

    Anyway, it mentions re-builder which is an awesome little gem if you use regular expressions at all1. What this baby does is open a small window at the bottom of your screen in which you can type a regex. It is parsed as you type it and matches are highlighted in the other window. Genius.

    + + +

    [1] If you don't use them I encourage you to "learn them"http://regex.info/. Don't pay any attention to Jamie Zawinsky and his lack of appreciation for a fantastic tool.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Snap, crunchle, pop.html b/wayback/@done/sjs Snap, crunchle, pop.html new file mode 100644 index 0000000..6f3ad40 --- /dev/null +++ b/wayback/@done/sjs Snap, crunchle, pop.html @@ -0,0 +1,638 @@ + + + + sjs: Snap, crunchle, pop + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Snap, crunchle, pop + + 1 + +

    +
    + Posted by sjs +
    +on Thursday, August 09 +
    +
    +

    I think that every now and then we need to be reminded of the frail nature of our human bodies. Yesterday morning as I walked to my kitchen I was turning right by pivoting on my right foot when my 24 years of walking experience suddenly failed me. I clearly did something wrong, as I heard a crunching pop or two in my right ankle and went down. Luckily it's just a sprain but my foot is fairly bruised and still sore today. I'm trying to follow the RICE method for recuperating but one can only lay down for so long before having to eat, work, use the bathroom, etc. Thank goodness I don't work on my feet or I'd be out of commission. If it still hurts next week I'm going to see a doctor but till then I'm trying not to leave my house. The idea of hopping and hobbling to a bus to go to a doctor does not thrill me in the slightest.

    + + +

    Oh, if you find yourself in a bind an upside down hockey stick is a decent makeshift crutch. You'll need 2 hands to operate the thing though.

    + + +

    At the opposite end of the spectrum there are times when we seem to be amazingly resilient creatures. Check out a documentary called "101 Things Removed from the Human Head" if you can find it anywhere. One of those things was a boat anchor, I kid you not.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    1. +
      + Kathy – + August 09, 2007 @ 10:28 PM +
      +
      +

      A few years ago I also twisted and sprained my ankle. I didn't know about the RICE method, but instinctively self-prescribed something similar. For the first 72 hours I laid on the sofa, with my ankle elevated. I only got up for necessary trips to bathroom or kitchen, hopping on my good foot. Someone lent me a pair of crutches, but I found them very awkward and painful to use, and after a day or so gave them up. I put ice on my swollen ankle but could only tolerate the cold for 10 minutes at most. For 3 days I stayed on the sofa to 'rest' (luckily it was the weekend and I didn't have to work or go anywhere). Then I gradually began to be more mobile, still babying my injured ankle for many weeks. I wore an ankle bandage daily for 3-4 months, and elevated my foot as much as possible during the day and at night. I think I also took painkillers during the first two or three days. +After a week or so, I remember rotating and stretching my ankle, slowly at first and more as it healed and became stronger. I babied it as much as possible the first week and then began using it more, exercising it and moving it cautiously, but continuously.

      + +

      I never did go to a doctor, which I don't necessarily recommend, just mention, and have not had any problems since.

      + +

      Hope you can rest, ice, compress and elevate, as I know they work. I just didn't know that what I thought seemed wise to do was called RICE and already known and used by others.

      +
      +
    2. + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Thoughts on Arc.html b/wayback/@done/sjs Thoughts on Arc.html new file mode 100644 index 0000000..6182692 --- /dev/null +++ b/wayback/@done/sjs Thoughts on Arc.html @@ -0,0 +1,653 @@ + + + + sjs: Thoughts on Arc + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Thoughts on Arc + + 0 + +

    +
    + Posted by sjs +
    +on Tuesday, February 19 +
    +
    +

    NB: This is just a braindump. There's nothing profound or particularly insightful in this post.

    + +

    You may have heard that Paul Graham recently released his pet dialect of Lisp: Arc. It's a relatively small language consisting of just 4500 lines of code. In just under 1200 lines of PLT Scheme the core of Arc is defined. The rest of the language is written in Arc itself. The heart of that is a file arc.arc, weighing in at 1500 lines. The remaining 1000-1300 lines are spread between libraries, mainly for writing web apps: html.arc, srv.arc, app.arc, and a few others.

    + +

    I'm not going to go into great detail, but Arc is a fun language. You can read all the code in one or two sittings and start hacking on it in no time. The code is simple where simple gets the job done and if you can follow SICP then you should understand it with relative ease (assuming you're somewhat familiar with Lisp).

    + +

    Parsing, Markdown

    + +

    I'm writing a simple parser combinators library (loosely modeled on Parsec) in order to write a nice Markdown implementation. Overkill? Indeed. Parsec is a wonderful library and it is written beautifully. If I end up with something 1/2 as powerful and 1/10th as beautiful I'll be pleased. This was all in order to beef up the version of Markdown bundled with Arc so I could write a basic wiki. I've been beaten to the punch, twice! Perhaps I'll retrofit Markdown onto jgc's wiki once I get something decent finished.

    + +

    Brevity and Innovation

    + +

    The brevity of Arc is both a blessing and a curse. On the one hand it makes for a very hacking-friendly language. It's easy/fun to try things in the REPL and write throwaway code for learning purposes. Paul's wanton removal of extraneous parentheses is a great boon. On the flip side Arc code can be a little cryptic at a first glance. While reading code there's a small period of time where you have to figure out what the short names are and what they do, but because the language is so small it's utterly trivial to grep or read the source and find out exactly how everything fits together and get the context you need. Once you're familiar with the domain then the terse names not only make sense, but they make the interesting parts of the code stand out more. I want to emphasize the pleasure of using Arc to learn. I think that Paul is on to something with the general brevity and simple nature of Arc.

    + +

    Some interesting ways that Paul has reduced code is by introducing new intra-symbol operators. Besides the usual backquote/quasiquote and comma/unquote translations, several other special characters are translated when they appear within/around symbols.

    + +

    There is the colon/compose operator that reduces code such as: (sym (string "pre-" something "-suffix")) to (sym:string "pre-" something "-suffix"). It can help with car/cdr chains without defining monstrosities such as cadadr, though whether (cadadr ...) is better than (cadr:cadr ...) is better than (car (cdr (car (cdr ...)))) is up to you.

    + +

    My favourite is the tilde to mean logical negation: no in Arc, not in most other languages. It doesn't shorten code much but it helps with parens. (if (no (empty str)) ...) becomes (if (~empty str) ...). Not much to be said about it, but it reads very nicely in code.

    + +

    Some newer ones are the dot and exclamation point to aide in the composition of functions requiring arguments. I won't go into detail as their use is trivial. If you're interested read Paul's explanation of them.

    + +

    Web programming

    + +

    Paul has touted Arc as a good web programming language, most notably in his Arc Challenge that caused a minor stir in a few blogs and on Reddit. I'm writing a small web app for myself in Arc. I may host it somewhere public when it's useable. It's a somewhat pastie-like app specifically for storing/sharing solutions to problems over at Project Euler, which I recently started tackling. "What's wrong with saving the code on your hard disk without a web app?", you ask? It doesn't give me an excuse to try Arc as a web language. ;-)

    + +

    So far I find that Arc is quite a nice web language. With the handy HTML tag library you can generate 90s-style, quirks-mode-compliant tag soup in a blink. I haven't had trouble producing HTML 4.01 (strict) that validates. There's no need for a template language or partials (à la Rails), you just compose tags-as-sexps using Arc itself. This turns out to be quite elegant, even if somewhat reminiscent of my first forays into web programming with PHP. I don't feel as if I'm writing a web app so much as I'm writing an app that happens to present its UI in HTML. (I'm reminded a little of web.py, which I enjoy as the antithesis of Rails.) I suppose it takes some discipline to separate your logic & design when everything's mixed in the same file, but there's nothing stopping you from separating the logic and views into their own files if you really prefer to do it that way.

    + +

    There's no distinction between GET and POST params. This surprised me, but then I thought about it and it's not a big deal for most apps, imo.

    + +

    The app I'm writing is standard CRUD stuff so I haven't done anything cool using continuations yet. I plan to use call/cc for backtracking in my parser, but I'm still a ways from implementing that kind of functionality!

    + +

    Non-conclusion

    + +

    I feel as though I should have a conclusion, but I don't. I've only been using Arc for a short time. It feels nice. I think Paul is doing a good job on the design by keeping it small, compact, and simple. Seeing as it's still in its infancy it's just a toy for me, but a toy with some decent potential. And hopefully an impact on other Lisps. Common Lisp may have industrial implementations and a 1500 page spec, but Arc is more fun and hackable. More so than Scheme, too. I think Arc has out-Schemed Scheme.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs Typo and I are friends again.html b/wayback/@done/sjs Typo and I are friends again.html new file mode 100644 index 0000000..dc5e0a5 --- /dev/null +++ b/wayback/@done/sjs Typo and I are friends again.html @@ -0,0 +1,597 @@ + + + + sjs: Typo and I are friends again + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Typo and I are friends again + +

    +
    + Posted by sjs +
    +on Wednesday, May 02 +
    +
    +

    I’ve been really frustrated with Typo recently. For some reason changing my last post would cause MySQL to timeout and I’d have to kill the rogue ruby process manually before any other changes to the DB would work, instead of hanging for a minute or two then timing out. Luckily I was able to disable the post using the command line client, the bug only manifested itself when issuing an UPDATE with all the fields present. Presumably the body was tripping things up because most other fields are simple booleans, numbers, or very short strings.

    + + +

    Add to that the random HTTP 500 errors which were very noticeable while I was trying to fix that post and I was about to write my own blog or switch to WordPress.

    + + +

    I don’t love WP so I decided to just upgrade Typo instead. I was using Typo 2.6, and the current stable version is 4.1. They skipped version 3 to preclude any confusion that may have ensued between Typo v3 and the CMS Typo3. So it really isn’t a big upgrade and it went perfectly. I checked out a new copy of the repo because I had some difficulty getting svn switch --relocate to work, configured the database settings and issued a rake db:migrate, copied my theme over and it all just worked. Bravo Typo team, that’s how an upgrade should work.

    + + +

    No more random 500 errors, things seem faster (better caching perhaps), and that troublesome post is troublesome no more. I am happy with Typo again.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs people.html b/wayback/@done/sjs people.html new file mode 100644 index 0000000..c0b6599 --- /dev/null +++ b/wayback/@done/sjs people.html @@ -0,0 +1,629 @@ + + + + sjs: people + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + people + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, July 12 +
    +
    +

    Sometimes this is difficult to remember for someone who (likes to think that he) thinks somewhat logically.

    + + +
    +

    When dealing with people, let us remember that we are not dealing with creatures of logic. We are dealing with creatures of emotion, creatures bristling with prejudices and motivated by pride and vanity.

    +
    + + +

    Dale Carnegie, How to Win Friends and Influence People

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs so long typo (and thanks for all the timeouts).html b/wayback/@done/sjs so long typo (and thanks for all the timeouts).html new file mode 100644 index 0000000..f3a6ff3 --- /dev/null +++ b/wayback/@done/sjs so long typo (and thanks for all the timeouts).html @@ -0,0 +1,634 @@ + + + + sjs: so long typo (and thanks for all the timeouts) + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + so long typo (and thanks for all the timeouts) + + 0 + +

    +
    + Posted by sjs +
    +on Saturday, June 09 +
    +
    +

    Well for just over a year Typo ran the show. I thought I had worked out most of the kinks with Typo and Dreamhost but the latest problem I ran into was pretty major. I couldn't post new articles. If the stars aligned perfectly and I sacrificed baby animals and virgins, every now and then I could get it to work. Ok, all I really had to do was refresh several dozen times, waiting 1 minute for it to timeout every time, but it sucked nonetheless.

    + + +

    Recently I had looked at converting Typo to Mephisto and it seemed pretty painless. I installed Mephisto and followed whatever instructions I found via Google and it all just worked, with one caveat. The Typo converter for Mephisto only supports Typo's schema version 56, while my Typo schema was at version 61. Rather than migrate backwards I brought Mephisto's Typo converter up to date instead. If you're interested, download the patch. The patch is relative to vendor/plugins, so patch accordingly.

    + + +

    After running that code snippet to fix my tags, I decided to completely ditch categories in favour of tags. I tagged each new Mephisto article with a tag for each Typo category it had previously belonged to. I fired up RAILS_ENV=production script/console and typed something similar to the following:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +
    require 'converters/base'
    +require 'converters/typo'
    +articles = Typo::Article.find(:all).map {|a| [a, Article.find_by_permalink(a.permalink)] }
    +articles.each do |ta, ma|
    +  next if ma.nil?
    +  ma.tags << Tag.find_or_create(ta.categories.map(&:name))
    +end
    + + +

    When I say something similar I mean exactly that. I just typed that from memory so it may not work, or even be syntactically correct. If any permalinks changed then you'll have to manually add new tags corresponding to old Typo categories. The only case where this bit me was when I had edited the title of an article, in which case the new Mephisto permalink matched the new title while the Typo permalink matched the initial title, whatever it was.

    + + +

    I really dig Mephisto so far. It's snappier than Typo and the admin interface is slick. I followed the herd and went with the scribbish theme. Perhaps I'll get around to customizing it sometime, but who knows maybe I'll like a white background for a change.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/sjs test spec on rails declared awesome, just one catch.html b/wayback/@done/sjs test spec on rails declared awesome, just one catch.html new file mode 100644 index 0000000..39027e2 --- /dev/null +++ b/wayback/@done/sjs test spec on rails declared awesome, just one catch.html @@ -0,0 +1,679 @@ + + + + sjs: test/spec on rails declared awesome, just one catch + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + test/spec on rails declared awesome, just one catch + +

    +
    + Posted by sjs +
    +on Thursday, June 14 +
    +
    +

    This last week I've been getting to know test/spec via err's test/spec on rails plugin. I have to say that I really dig this method of testing my code and I look forward to trying out some actual BDD in the future.

    + + +

    I did hit a little snag with functional testing though. The method of declaring which controller to use takes the form:

    + + + + + +
    
    +
    use_controller :foo
    + + +

    and can be placed in the setup method, like so:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +14
    +15
    +
    # in test/functional/sessions_controller_test.rb
    +
    +context "A guest" do
    +  fixtures :users
    +
    +  setup do
    +    use_controller :sessions
    +  end
    +
    +  specify "can login" do
    +    post :create, :username => 'sjs', :password => 'blah'
    +    response.should.redirect_to user_url(users(:sjs))
    +    ...
    +  end
    +end
    + + +

    This is great and the test will work. But let's say that I have another controller that guests can access:

    + + + + + +
    1
    +2
    +3
    +4
    +5
    +6
    +7
    +8
    +9
    +10
    +11
    +12
    +13
    +
    # in test/functional/foo_controller_test.rb
    +
    +context "A guest" do
    +  setup do
    +    use_controller :foo
    +  end
    +
    +  specify "can do foo stuff" do
    +    get :fooriffic
    +    status.should.be :success
    +    ...
    +  end
    +end
    + + +

    This test will pass on its own as well, which is what really tripped me up. When I ran my tests individually as I wrote them, they passed. When I ran rake test:functionals this morning and saw over a dozen failures and errors I was pretty alarmed. Then I looked at the errors and was thoroughly confused. Of course the action fooriffic can't be found in SessionsController, it lives in FooController and that's the controller I said to use! What gives?!

    + + +

    The problem is that test/spec only creates one context with a specific name, and re-uses that context on subsequent tests using the same context name. The various setup methods are all added to a list and each one is executed, not just the one in the same context block as the specs. I can see how that's useful, but for me right now it's just a hinderance as I'd have to uniquely name each context. "Another guest" just looks strange in a file by itself, and I want my tests to work with my brain not against it.

    + + +

    My solution was to just create a new context each time and re-use nothing. Only 2 lines in test/spec need to be changed to achieve this, but I'm not sure if what I'm doing is a bad idea. My tests pass and right now that's basically all I care about though.

    + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/@done/zsh terminal goodness on OS X - samhuri.net.html b/wayback/@done/zsh terminal goodness on OS X - samhuri.net.html new file mode 100644 index 0000000..d36d7ec --- /dev/null +++ b/wayback/@done/zsh terminal goodness on OS X - samhuri.net.html @@ -0,0 +1,508 @@ + + + + zsh terminal goodness on OS X - samhuri.net + + + + + + + + + + + + + + + + +
    +
    + + + + +
    + Wayback Machine + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + May + + JUN + + DEC + +
    + + Previous capture + + 14 + + Next capture + +
    + + 2005 + + 2006 + + 2007 + +
    +
    + 4 captures +
    14 Jun 06 - 5 Aug 07
    +
    + +
    + sparklines + + +
    +
    + +
    +
    + Close + Help +
    + +
    +
    + + + + + + + + + + + + + +
    + +
    + + +
    + +

    zsh terminal goodness on OS X

    +

    + on Tuesday, April 04, 2006

    +

    Apple released the OS X 10.4.6 update which fixed a really annoying bug for me. Terminal (and iTerm) would fail to open a new window/tab when your shell is zsh. iTerm would just open then immediately close the window, while Terminal would display the message: [Command completed] in a now-useless window.

    + + +

    Rebooting twice to get the fix was reminiscent of Windows, but well worth it.

    +
    +

    + Posted in ,  | Tags , ,  | no comments | no trackbacks +

    + +

    Comments

    + +
      + + + +
    + +

    Trackbacks

    +

    + Use the following link to trackback from your own site:
    + http://sami.samhuri.net/articles/trackback/48 +

    + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    (leave url/email »)

    + +
    +    + Preview comment + +
    +
    +
    + + +
    + +
    + +
    + + + +
    + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wayback/mephisto/sjs A triple-booting, schizophrenic MacBook.html b/wayback/mephisto/sjs A triple-booting, schizophrenic MacBook.html new file mode 100644 index 0000000..6247467 --- /dev/null +++ b/wayback/mephisto/sjs A triple-booting, schizophrenic MacBook.html @@ -0,0 +1,660 @@ + + + + sjs: A triple-booting, schizophrenic MacBook + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + A triple-booting, schizophrenic MacBook + + 0 + +

    +
    + Posted by sjs +
    +on Thursday, April 05 +
    +
    + The steps are well documented so I won’t get into detail here but if you have a backup and can wipe your disk all you do is: +
      +
    • Install OS X to a single partition filling your disk (optionally use your existing OS X intall)
    • +
    • Install rEFIt (no need to reboot just yet)
    • +
    • Re-partition your disk into 3 partitions with diskutil resizeVolume, reboot and confirm it all works
    • +
    • Boot the Vista install DVD and install to disk0s4 aka Partition 4
    • +
    • Install Gentoo (or other distro) to disk0s3 aka /dev/sda3
    • +
    + + +

    With MacPorts and Gentoo/MacOSX the Gentoo install is superfluous but I’ll spare 12G just to see Gentoo run on this fine machine. Setting up the hardware should be fun. Right now I’m compiling X, (package 77 of 94) and the Core Duo is crunching code very nicely with 2G to work with, without any swap. I fully intend to put off creating a swap file unless I have to. Needless to say I’ll be running fluxbox or Xfce, none of that Gnome or KDE stuff. If I ever need a swap file I will eat my keyboard.

    + + +

    [edit: 25 minutes to compile X.org, not too shabby!]

    + + +

    My initial experience with Vista is quite good. Sadly the same old registry hack is required to swap Caps lock and Control but I was just glad it worked. I really like the new Start menu and the eye-candy is fairly pleasant for the most part. Till now I’d only used RC2 on a machine incapable of running Aero Glass and it looked terrible. I switched to Windows Classic just like I do with XP. Not so with Aero at its finest though. Without thinking about the price Vista is a nice upgrade to Windows. But because of the price and uncertainty of running Aero Glass I still hesitate to urge non-geeks to upgrade.

    + + +

    OS X is OS X. It’s my favourite desktop OS right now because of apps like LaunchBar/Quicksilver and TextMate, a generally excellent UI, good old *nix stability, zsh out of the box! When I need WireShark or the GIMP X11 is there waiting. Mac notebooks are great and tight integration with the hardware is a clear advantage for OS X.

    + + +

    Oh yeah, I also have a Parallels VM for Windows 3.11. It boots in about second to the C:\> prompt and then another second to type win and Windows to start. Without TCP/IP there’s not much to do though (I’m not going to write a driver for Parallels’ ethernet adapter).

    + + +
      +
    1. +
        +
      • Dual head setups are more work than plugging in a 2nd monitor, which is too much work.
      • +
      • X requires a restart to enable or disable a 2nd display.
      • +
      • Overall clunkiness such as displaying the houndstooth background before the WM starts,
      • +
      • and/or going through a screwed up mode with a black & white scrambled screen for a seconds before getting to the houndstooth.
      • +
      + back up ↑ +
    2. +
    + +

    Like I said the X.org boys are doing amazing work. Hopefully soon after the current eye-candy craze is over they’ll get to more important work that needs to be done.

    + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/mephisto/sjs Funny how code can be beautiful.html b/wayback/mephisto/sjs Funny how code can be beautiful.html new file mode 100644 index 0000000..5a75293 --- /dev/null +++ b/wayback/mephisto/sjs Funny how code can be beautiful.html @@ -0,0 +1,645 @@ + + + + sjs: Funny how code can be beautiful + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Funny how code can be beautiful + + 0 + +

    +
    + Posted by sjs +
    +on Monday, April 30 +
    +
    +

    While reading a Haskell tutorial I came across the following code for defining the Fibonacci numbers:

    + + +
    fib = 1 : 1 : [ a + b | (a, b) <- zip fib (tail fib) ]
    + +

    After reading it a few times and understanding how it works I couldn’t help but think how beautiful it is. I don’t mean that it’s aesthetically pleasing to me; the beautiful part is the meaning and simplicity. Lazy evaluation is sweet.

    + + +

    Haskell is the most challenging real language I have tried to wrap my head around. I haven’t done much with any functional languages yet but they are truly fascinating. I’m beginning to understand monads1 but I’m quite sure I don’t see the whole picture yet.

    + + +

    Erlang looks like it may be more suited to real world apps so I would like to learn that some time. The pragmatic guys have a book on Erlang in the works, and I love every book of theirs which I have read.

    + + +

    Going deeper down the functional rabbit-hole you’ll find things like this polyglot quine, which absolutely blows my mind. I used to be impressed by the JAPH sigs or some of the various obfuscated contest winners but that first one definitely cleans the rest up with a perfect 10 in geekiness.

    + + +

    [1] The following links have all been helpful while trying to wrap my head around monads.

    + + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/mephisto/sjs Getting to know Vista.html b/wayback/mephisto/sjs Getting to know Vista.html new file mode 100644 index 0000000..08cdc07 --- /dev/null +++ b/wayback/mephisto/sjs Getting to know Vista.html @@ -0,0 +1,700 @@ + + + + sjs: Getting to know Vista + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + + + +
    +

    + Getting to know Vista + + 0 + +

    +
    + Posted by sjs +
    +on Monday, April 16 +
    +
    +

    It looks pretty good!

    + + +

    After figuring out how to minimise the translucency of the window decorations I think Aero looks ok. Window titles, on both windows and the taskbar, can be difficult to read at a glance which is really stupid if you ask me. But it’s better than Luna! They really lay the effects on thick but overall I find it pretty pleasant and it runs well on my MacBook’s Intel 945 video chip.

    + + +

    Ah yes, the Sidebar is nowhere to be seen on my desktop. It’s a nice-looking waste of space.

    + + +

    But it’s not all useful

    + + +

    Sadly The new task switcher (Win-tab) is terrible. Before using it I wondered why they didn’t replace Alt-tab completely. Now I know and I am grateful to MS for not replacing it. Alt-tab easily wins. Especially since it displays thumbnails of windows.

    + + +Three gripes with Win-tab fancy-shmanciness: +
      +
    • It’s too slow
    • +
    • It responds even when I just tap Win-tab to quickly switch, then I’m stuck until I hit the Windows key to choose a window
    • +
    • Windows from all my monitors are gathered onto the main one, which is just lame
    • +
    + + +

    It’s stable (so far)

    + + +

    Besides the fact it is aesthetically pleasing [subjective] it also has just worked for me so far. Nothing has crashed or broken which is almost miraculous. Not that I had a terrible time with XP, but it was still frail old Windows at times. I’m equally pleased with Apple’s drivers for Windows which probably adds to the experience. I’ve used XP machines with proper drivers, and those without and the differenc is night & day. I’ve had uptimes in months on a stable XP notebook.

    + + +

    Never thought this day would come…

    + + +

    But I actually like the Start menu. Really, I do. You hit the Windows key, type a few letters and boom you launch your app or search your computer, or the web (Google in Firefox, my default search). It’s not QuickSilver or LaunchBar; it’s not supposed to be. For the average Joe this is cool, and for the average power user it’s very useful. For the casual Windows user it’s great. It even learns.

    + + +

    I don’t love it though. I knew before using it that the new method of navigating through the All Programs menu would be weird. It is, but I guess it may be better than the previous fly-out scheme (which I don’t care for either). I guess the All Programs menu is more or less legacy now though and I don’t see myself using it often.

    + + +

    I’m a command line junkie

    + + +

    They fixed at least one glaring bug. I used the cmd.exe shell a little bit even though I hate it. I was happy to find that Tab completion works for more than the current directory now. Before Vista it would complete the same entries from PWD no matter how deep you tried to drill down into the filesystem. Other than that it seems to be the same crummy shell. [edit—apparently this is fixed in XP as well, my mistake]

    + + +

    I installed the Windows PowerShell (PoSH) but haven’t really put an effort to learn it yet. The syntax is unorthodox coming from *nix shells (zsh), but it’s sort of refreshing and it lives up to the Power part of its name. I really like the fact that collections of (say) files can be passed around and iterated over, filtered, etc. not as filenames but as real objects with corresponding methods and metadata. Built-in support for XML is pretty nifty too.

    + + +

    I’ve often longed for a shell which acted like a normal shell for the most part, but allowed irb-like interpretation of arbitrary Ruby code as well. The PowerShell seems like it could be something similar to what I’ve wanted. Too bad it’s proprietary and only runs on Windows. If I use Vista a lot this summer I could end up getting into it more though. It’s quite interesting.

    + + +

    Random

    + + +The good: +
      +
    • Slideshow button in Explorer
    • +
    • Doesn’t look like a Fisher-Price design
    • +
    • Restarts when I click Restart (after 3 clicks it damn well better)
    • +
    • Seems stable, at least initially which means the installation & driver situation really has improved
    • +
    • I don’t want to kill anyone while using it
    • +
    + + +The bad: +
      +
    • Flicker while changing video modes, displaying UAC prompts, etc. (not so bad really, but stands out on an otherwise smooth desktop)
    • +
    • Long black screen on boot after installing updates
    • +
    • Disappearing / magical menu bar debacle
    • +
    • The shell still sucks
    • +
    • It tries to be too fancy, with the dynamic Start menu icon and the like
    • +
    + + +

    My conclusion

    + + +

    Perhaps the scores of talented developers at Microsoft can save them despite their obvious shortcomings in management. .NET seems like a decent platform, but we’ll have to see how I like it once I actually use it. So far I don’t hate Vista and considering the previous versions of Windows that’s a pretty good review coming from me. I’m still recommending Macs to my family and friends, but who knows what the future holds. I don’t hate Vista and by the end of the summer I may even [gasp] like it, and/or .NET. I haven’t used an IDE since VB6 and MS has always had a decent IDE (albeit with a crummy text editor). I’m expecting to enjoy it. If there’s one thing MS knows it’s the value of good dev tools and developers.

    + + + +
    + +
    + +
    Comments
    +

    Leave a response

    +
    +
      + +
    +
    + +
    +
    + Comment +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +

    +
    + +

    +
    + +
    +
    +
    + + + +
    + + +
    + +
    + + + +
    + + + + + + + + + + + + + diff --git a/wayback/scrape-mephisto-page.js b/wayback/scrape-mephisto-page.js new file mode 100755 index 0000000..702de47 --- /dev/null +++ b/wayback/scrape-mephisto-page.js @@ -0,0 +1,57 @@ +#!/usr/bin/env node + +var fs = require('fs') + , jsdom = require('jsdom') + , strftime = require('strftime').strftime + +fs.readFile(process.argv[2] || 'sjs 301 moved permanently.html', 'utf8', function(err, html) { + jsdom.env({ html: html + , scripts: [ 'http://code.jquery.com/jquery-1.6.min.js' ] + }, onLoad) +}) + +function onLoad(err, window) { + var $ = window.jQuery + $('div.hentry').each(function() { + console.log('title: ' + $('.entry-title a', this).text()) + console.log('url: ' + $('.entry-title a', this).attr('href').replace(/^http:\/\/web.archive.org\/web\/\d+\//, '')) + console.log('iso date: ' + $('abbr.published', this).attr('title')) + var tags = $('ul.meta li:first-child a', this).map(function(){ return $(this).text() }).get() + console.log('tags: ' + tags) + // console.log('body: ' + $('.entry-content', this).html().trim()) + var post = { + title: $('.entry-title a', this).text() + , url: $('.entry-title a', this).attr('href').replace(/^http:\/\/web.archive.org\/web\/\d+\//, '') + , ISODate: $('abbr.published', this).attr('title') + , body: $('.entry-content', this).html().trim() + , tags: tags + } + , s = [ 'Title: ' + post.title + , 'Date: ' + strftime('%B %e, %Y', new Date(post.ISODate)) + , 'Timestamp: ' + strftime('%s', new Date(post.ISODate)) + , 'Author: sjs' + , 'Tags: ' + post.tags.join(', ') + , '----' + , '' + , post.body + , '' + ].join('\n') + , slug = strftime('%Y-%m-%d_' + post.title + .toLowerCase() + .replace(/[^\sa-z0-9_-]/g, '') + .replace(/\s+/g, '-'), new Date(post.ISODate)) + console.log('slug: ' + slug) + , filename = '../recovered/' + slug + '.html' + try { + fs.statSync(filename) + console.log('skipped, exists -> ' + post.title + ' (' + slug + '.html)') + console.log() + } + catch (e) { + // fs.writeFileSync(filename, s, 'utf8') + console.log(post.title + ' (' + slug + '.html)') + console.log() + } + // console.log(s) + }) +} diff --git a/wayback/scrape-mephisto.js b/wayback/scrape-mephisto.js new file mode 100755 index 0000000..8c28819 --- /dev/null +++ b/wayback/scrape-mephisto.js @@ -0,0 +1,60 @@ +#!/usr/bin/env node + +var fs = require('fs') + , jsdom = require('jsdom') + , strftime = require('strftime').strftime + +fs.readFile(process.argv[2] || 'sjs 301 moved permanently.html', 'utf8', function(err, html) { + jsdom.env({ html: html + , scripts: [ 'http://code.jquery.com/jquery-1.6.min.js' ] + }, onLoad) +}) + +function onLoad(err, window) { + var $ = window.jQuery + console.log('title: ' + $('.entry-title a').text()) + console.log('url: ' + $('.entry-title a').attr('href').replace(/^http:\/\/web.archive.org\/web\/\d+\//, '')) + console.log('iso date: ' + $('abbr.published').attr('title')) + var tags = $('ul.meta li:first-child a').map(function(){ return $(this).text() }).get() + console.log('tags: ' + tags) + // console.log('body: ' + $('.entry-content').html().trim()) + var comments = [] + , $comments = $('li.comment') + $.each($comments, function(i, x) { + var author = $('div.author > cite > span.author > *', x) + comments.push({ + author: author.text() + , url: author.attr('href').replace(/^http:\/\/web.archive.org\/web\/\d+\//, '') + , date: $('div.author > abbr', x).attr('title') + , body: $('div.content', x).text().trim() + }) + }) + // console.log('comments: ' + comments.length) + var post = { + title: $('.entry-title a').text() + , url: $('.entry-title a').attr('href').replace(/^http:\/\/web.archive.org\/web\/\d+\//, '') + , ISODate: $('abbr.published').attr('title') + , body: $('.entry-content').html().trim() + , tags: tags + , comments: comments + } + , s = [ 'Title: ' + post.title + , 'Date: ' + strftime('%B %e, %Y', new Date(post.ISODate)) + , 'Timestamp: ' + strftime('%s', new Date(post.ISODate)) + , 'Author: sjs' + , 'Tags: ' + post.tags.join(', ') + , '----' + , '' + , post.body + , '' + ].join('\n') + , slug = strftime('%Y.%m.%d-' + post.title + .toLowerCase() + .replace(/[^\sa-z0-9._-]/g, '') + .replace(/\s+/g, '-'), new Date(post.ISODate)) + console.log('slug: ' + slug) + fs.writeFileSync('../recovered/' + slug + '.html', s, 'utf8') + console.log(post.title + ' (' + slug + '.html)') + console.log() + // console.log(s) +} diff --git a/wayback/scrape-typo.js b/wayback/scrape-typo.js new file mode 100755 index 0000000..258dcf8 --- /dev/null +++ b/wayback/scrape-typo.js @@ -0,0 +1,59 @@ +#!/usr/bin/env node + +var fs = require('fs') + , jsdom = require('jsdom') + , strftime = require('strftime').strftime + +fs.readFile(process.argv[2] || 'Full-screen Cover Flow - samhuri.net.html', 'utf8', function(err, html) { + jsdom.env({ html: html + , scripts: [ 'http://code.jquery.com/jquery-1.6.min.js' ] + }, onLoad) +}) + +function onLoad(err, window) { + var $ = window.jQuery + , tags = [] + , $tags = $('a[rel="tag"]') + $.each($tags, function(i, x) { tags.push($(x).text()) }) + var post = { + title: window.document.title.replace(' - samhuri.net', '') + , url: $('#wmtbURL').val() + , ISODate: $('.typo_date').attr('title') + , body: $('.post').html() + , tags: tags + , comments: $('#commentList li').map(function() { + var author = $('cite a', this) + , url + if (author.length === 0) { + author = $('cite', this) + } + else { + url = author.attr('href').replace(/^http:\/\/web.archive.org\/web\/\d+\//, '') + } + return { + author: author + , url: url + , body: $(this).text() + } + }) + } + var s = [ 'Title: ' + post.title + , 'Date: ' + strftime('%B %e, %Y', new Date(post.ISODate)) + , 'Timestamp: ' + strftime('%s', new Date(post.ISODate)) + , 'Author: sjs' + , 'Tags: ' + post.tags.join(', ') + , '----' + , '' + , post.body + , '' + ].join('\n') + + var slug = strftime('%Y.%m.%d-' + post.title + .toLowerCase() + .replace(/[^\sa-z0-9._-]/g, '') + .replace(/\s+/g, '-'), new Date(post.ISODate)) + + fs.writeFileSync('../recovered/' + slug + '.html', s, 'utf8') + console.log(post.title + ' (' + slug + '.html)') +// console.log(s) +}