JUN | AUG | OCT
| 11 |
2006 | 2007 | 2009

23 captures 3 Mar 06 - 31 May 09 |

Close Help

# 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.

- Sections: Emacs
- Tags: cheat emacs
- Meta: 4 comments, permalink

## 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.

- Tags: humans injury life
- Meta: 1 comment, permalink

## 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.

Continue reading...

- Tags: elschemo haskell scheme
- Meta: 0 comments, permalink

## 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

- Tags: life people
- Meta: 0 comments, permalink

## 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.

- Tags: emacs regex
- Meta: 0 comments, permalink

## 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.

- Tags: quickcheck ruby rushcheck
- Meta: 0 comments, permalink

## 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.

- Tags: emacs keyboard shortcuts textmate
- Meta: 0 comments, permalink

## 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.

- Tags: alsa linux ruby volume
- Meta: 0 comments, permalink

## 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.

- Tags: rails rails on rules regular expressions ruby sake secure associations
- Meta: 0 comments, permalink

## 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.

- Tags: emacs tagify
- Meta: 1 comment, permalink

## 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.

- Tags: emacs rtfm
- Meta: 0 comments, permalink

## 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

- Tags: propaganda
- Meta: 0 comments, permalink

## 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.

Continue reading...

- Tags: elschemo haskell scheme
- Meta: 0 comments, permalink

## 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.

- Tags: emacs textmate
- Meta: 6 comments, permalink

## 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.

- Tags: activerecord rails ruby
- Meta: 0 comments, permalink