Xah’s Challenge (Part 2)

Yesterday, I wrote about Xah Lee’s programming challenge and gave a solution similar to Lee’s own. Today I will give another, possibly simpler, solution. We start with some constants and a couple of helper functions:

(defconst brackets '((?( . ?))
                     (?{ . ?})
                     (?[ . ?])
                     (?“ . ?”)
                     (?‹ . ?›)
                     (?« . ?»)
                     (?【 . ?】)
                     (?〈 . ?〉)
                     (?《 . ?》)
                     (?「 . ?」)
                     (?『 . ?』)))

(defconst not-brackets "^(){}[]“”‹›«»【】〈〉《》「」『』")

(defvar filen nil)

(defun brkt-closes-p (brkt obrkt)
  "Predicate to test if brkt closes obrkt."
  (let ((bpair (assoc obrkt brackets)))
    (and bpair (char-equal brkt (cdr bpair)))))

(defun brkt-open-p (brkt)
  "Predicate to test if brkt is an opening bracket."
  (assoc brkt brackets))

As before, we have a list of the beginning and ending brackets but this time they are given as characters rather than strings. The not-brackets constant will be used in a call to skip-chars-forward. The ^ at the beginning of the string specifies all characters except the brackets.

The brkt-closes-p function is a predicate that tests whether its first argument is the closing bracket for the second argument. It just uses the brackets constant as an alist.

The brkt-open-p function is even simpler. It’s a predicate that tests whether its first argument is an opening bracket. That will be true if it’s found in a key position of the brackets alist.

As in the first solution, check-file-for-mismatches gets called to check a single file but all the work is done in brkt-match. The check-file-for-mismatches function merely sets up the temporary buffer for the file and calls brkt-match.

(defun check-file-for-mismatches (fpath)
  "Check a file for mismatched brackets."
  (let ((fb (get-buffer-create "*Temp*")))
    (set-buffer fb)
    (insert-file-contents fpath nil nil nil t)
    (goto-char 1)
    (setq filen fpath)
    (brkt-match ?\f)
    (kill-buffer fb)))

The real checking is done in brkt-match:

 1:  (defun brkt-match (obrkt)
 2:    "Match OBRKT with its closing bracket."
 3:    (let ((open-pos (1- (point))))
 4:      (catch 'exit
 5:        (while t
 6:          (skip-chars-forward not-brackets)
 7:          (if (not (eobp))
 8:              (forward-char))
 9:          (cond
10:           ((eobp) (if (not (char-equal ?\f obrkt))
11:                       (print (format "Unclosed %c in %s at %d"
12:                                      obrkt filen open-pos)))
13:            (throw 'exit t))
14:           ((brkt-closes-p (char-before) obrkt) (throw 'exit t))
15:           ((brkt-open-p (char-before)) (brkt-match (char-before)))
16:           (t (print (format "Mismatch in %s at %d" filen (1- (point))))))))))
17:  

The idea is that brkt-match is passed an opening bracket and searches for the closing bracket (the ?\f passed in by check-file-for-mismatches is a special marker indicating the beginning of file—it matches end-of-buffer). Rather than locate the brackets with a regular expression, we find them by skipping over everything else with skip-chars-forward on line 6.

The processing is done in the while loop on lines 5–16. The catch on line 4 is so that we can exit the while if we match the input or reach end-of-buffer. The cond on lines 9–16 makes the checks:

  1. Lines 10–13
    If we are at end-of-buffer and the input was not ?\f then output an error message about an unclosed bracket. In any case, exit the loop and therefore the function.
  2. Line 14
    If the current character closes the input character, exit the loop and function.
  3. Line 15
    If this is an opening bracket, recursively call brkt-match to try to match it.
  4. Line 16
    If the other tests fail then this is a mismatched bracket. Output an error message and keep looking for the closing bracket matching the input.

We can use the exact same do-files from the first solution to drive check-file-for-mismatches so I won’t repeat it here.

This solution appears radically different from the first but it isn’t really; only the details differ. We use characters instead of strings, skip-chars-forward instead of regular expressions, and recursion instead of an explicit stack but the strategy is the same:

  • Search for the match to an opening bracket
  • If we find another open bracket, save what we’ve done so far and start over with the new opening bracket
  • When we match an opening bracket, pick up where we left off.

It’s an interesting question as to which method is faster. I haven’t tested that aspect but I’m pretty sure the second method is faster. It can do simple character compares instead of the more complex string compares and regular expressions have to do at least as much work as skip-chars-forward.

Update: test → tests. Fixed line numbers in text.

Posted in Programming | Tagged | 3 Comments

Xah’s Challenge

A couple of days ago Xah Lee posed a programming challenge. The problem was to write a miniparser in your favorite language to detect mismatched bracketing characters in a set of text files. The set of brackets to be checked were: () {} [] “” ‹› «» 【】 〈〉 《》 「」 『』. His solution is here.

I solved this problem in two “different” ways, both in Emacs lisp. This post is my first solution. I’ll post the second solution tomorrow.

This solution is similar to Lee’s but written in a more functional style. The strategy is to hunt down the brackets with search-forward-regexp, push the opening brackets onto a stack, and check that each closing bracket matches the top of the stack. If it does, we pop the stack and keep going. If it doesn’t, we record the error and write it to an error buffer. If there is anything left on the stack when we finish, that’s also an error because there is an unmatched opening bracket.

The main function, check-file-for-mismatches uses a complicated regular expression to locate the brackets and an alist to type the brackets and identify the matching bracket. In a production system, these would be computed before run time to save on execution time. As Paul Graham has said, the nice thing about Lisp is that all of Lisp is available all the time. That means that we can use Lisp as we are writing the code to compute the regexp and alist. In this example, I compute them at run time so that you can see how I did it.

We start with the list of brackets:

(defvar brackets '(("(" . ")")
                   ("{" . "}")
                   ("[" . "]")
                   ("“" . "”")
                   ("‹" . "›")
                   ("«" . "»")
                   ("【" . "】")
                   ("〈" . "〉")
                   ("《" . "》")
                   ("「" . "」")
                   ("『" . "』")))

and then compute the regexp with:

(defun make-br-regexp ()
  "Make a regexp to check for any of the delimiters in brackets"
  (mapconcat (lambda (bp)
               (concat (regexp-quote (car bp)) "\\|" (regexp-quote (cdr bp))))
             brackets "\\|"))

and the alist with:

(defun make-br-alist ()
  "Make an alist of the brackets. Each entry is of the form:
\(bracket open-or-close matching-bracket\)"
  (reduce #'append (mapcar (lambda (bp)
                             (list (list (car bp) 'open (cdr bp))
                                   (list (cdr bp) 'close (car bp))))
                           brackets)))

Each entry in the alist has the form (bracket type matching-bracket) where type is either open or close and indicates whether the bracket is an opening or closing bracket.

As I said, all of this could be done at coding time and the results made into constants. Instead we define a couple of constants on the fly:

(defconst br-regexp (make-br-regexp))
(defconst br-alist (make-br-alist))

All the work is done in check-file-for-mismatches.

 1:  (defun check-file-for-mismatches (fpath)
 2:    "Check a file for mismatched brackets."
 3:    (let ((fb (get-buffer-create "*Temp*"))
 4:          (stack nil)
 5:          (mismatches nil))
 6:      (set-buffer fb)
 7:      (insert-file-contents fpath nil nil nil t)
 8:      (goto-char 1)
 9:      (while (search-forward-regexp br-regexp nil t)
10:        (let* ((bpos (point))
11:               (brk (buffer-substring-no-properties (1- bpos) bpos))
12:               (blist (assoc brk br-alist))
13:               (btype (cadr blist)))
14:          (cond
15:           ((eq btype 'open)  (push (cons brk (1- bpos)) stack))
16:           ((eq btype 'close) (if (or (null stack)
17:                                      (not (string= (caar stack) (caddr blist))))
18:                                  (push (1- bpos) mismatches)
19:                                (pop stack)))
20:           (t (error "FAIL--found %s instead of bracket" brk)))))
21:      (if mismatches
22:          (mapc (lambda (e)
23:                  (print (format "Mismatch in %s at position %d"
24:                                 fpath e)))
25:                (reverse mismatches)))
26:      (if stack
27:          (mapc (lambda (e)
28:                  (print (format "%s has an unclosed %s at position %d"
29:                                 fpath (car e) (cdr e))))
30:                (reverse stack)))
31:      (kill-buffer fb)))
32:  

The actual checking occurs in the while loop on lines 9–20. We find a bracket with the regexp search, record its position and type and then check to see if it’s an opening or closing bracket. For opening brackets, we just push it on the stack. For closing brackets we check for the matching opening bracket on the stack and record an error if it’s not a match.

On lines 21–25, we print any mismatches that we found in the file. On lines 26–30 we print an error message for any open brackets still on the stack. Almost half of check-file-for-mismatches is concerned with error reporting. It’s worth noting that after the first error the parsing tends to get out of sync and you can get cascading errors but the error report tells you what happened so that you can fix the real errors and rerun the program as a final check.

To run check-file-for-mismatches we need a function to feed it the files and establish the error buffer. The sample function, do-files that I show below checks files with the extension txt in the ~/elisp directory. What you actually do depends on how you are selecting your files.

(defun do-files ()
  "Check a list of files for bracket mismatches"
  (interactive)
  (with-output-to-temp-buffer "*Mismatch Report*"
    (mapc #'check-file-for-mismatches (directory-files "~/elisp" t "\.txt$"))))

Many of the ideas for these functions come from Lee’s Emacs Lisp Tutorial. This page, in particular, has several useful templates for handling files and buffers in a way similar to what we’ve done here.

Posted in Programming | Tagged | Leave a comment

Common iPhone Pins

I’ve written several (1, 2, 3) posts about the analysis of passwords divulged by groups like LulzSec. The results were terrifyingly consistent: 123456 and password were almost always the most frequently used passwords. Now Daniel Amitay author of the Big Brother Camera Security App for the iPhone has some interesting results for iPhone pins.

Because his app has a lock screen nearly identical to the iPhone phone lock screen, he collected (anonymized) statistics on what codes were being used for his app in the hopes that it could tell us something about what how users are selecting their iPhone lock codes. He collected 204,508 codes and calculated their frequencies. Among other things, Amitay found that the top ten most common pins accounted for 15% of all passcodes.

Without reading further, try to guess the top four most popular pins. Hint: It’s not hard. The number one pin is, of course, 1234 followed by 0000. The next two are 2580 (going down the middle column) and 1111. The next 6 aren’t much harder to guess. Another common scheme is to use the user’s birth year.

Amity also looks at the most common digit for each of the four positions. The most common first digit is 1 by a large margin. If you squint a bit, it almost looks as if the pins obey Benford’s law. The second, third, and fourth digits are more uniform.

The post is an interesting, if depressing, read. As Amitay points out, for a random iPhone a cracker has a 15% chance of unlocking the phone before the automatic data wipe feature is activated. Considering that smartphones like the iPhone often contain confidential data or access to confidential data this is bad news.

In a sad endnote, Amitay has had his app removed from the App Store for his trouble. Apparently Apple was concerned that he was harvesting the Apple lock codes or something. Amitay is discussing the matter with Apple and we can hope that he will have the whole thing straightened out soon.

Posted in General | Tagged | Leave a comment

Goodbye Borders

Although it’s a little outside of our usual subject matter, I sadly note the passing of Borders. Yesterday Borders announced that it was canceling its upcoming bankruptcy auction and liquidating the company instead. Although some creditors are objecting, it’s almost certain that Borders will close its 399 remaining stores and sell off its assets.

The story of how Borders arrived at this end is well known. They didn’t take Internet sales seriously and failed to appreciate how ebooks would change their industry. I’ve written before about the challenges facing the publishing industry and my hope that they would avoid the same mistakes that the music industry made. So far, they appear to be oblivious to the new reality. Perhaps Borders can serve as a wakeup call. No matter how much you want your business to stay the way it was, circumstances and customers move on. You either move with them or you end up like Borders.

Like most folks, I mainly get my books on-line and tend to prefer ebooks over the dead tree variety. Still, I have fond memories of browsing at Borders and enjoying a comfortable chair and cup of coffee while I skimmed through a book. I’ll miss the opportunity to do so in the future.

Posted in General | Leave a comment

The 25 Most Dangerous Software Errors

Each year the SANS Institute and the MITRE Corporation team up to survey the year’s most dangerous programming errors. This year’s list, the 2011 Common Weakness Enumeration, was published at the end of June. This is a great resource and anyone writing software for the Web should read it carefully. The document is a long and thorough analysis of the errors that led to exploits in the last year.

The report begins with some guidance for different types of users—programmers new to security, programmers experienced in security, project managers, testers, customers, and educators—on how to use the list. Next there is a brief listing of the errors sorted in various ways, and finally a detailed explanation and sample code for each type of error. Finally there is a list of “Monster Mitigations” that establish some general principles for writing secure code.

The tops 5 errors were:

  1. SQL Injection
  2. OS Command Injection
  3. Buffer Overflow
  4. Cross-site Scripting
  5. Missing Authentication for Critical Function

I find OS Command Injection in second place surprising, but sadly all of the others are as expected. It beggars belief that SQL injection is still such a common exploit today. The same could be said of buffer overflow. Of course, as LulzSec has shown us, there is every reason to expect that SQL injection will be a major attack vector for the foreseeable future.

Again, if you are writing code for the Web, you really need to read and study this report.

Posted in Programming | Tagged | Leave a comment

An Interesting Talk On Guile

I just ran across an interesting talk on Guile Scheme by Andy Wingo. The talk is from 2009, shortly before Guile 2.0 came out. Wingo discusses the new Guile architecture and plans for a native compiler. One of the most interesting parts for me was the discussion of his plans for Guile to replace the Emacs Lisp engine. That’s still in the future but there’s already an implementation of Elisp that runs on the Scheme VM. Wingo claims that it will make Emacs much faster than it is now and will allow Lispaphobes to customize Emacs in any of the supported languages—Javascript, for example.

It’s a fairly long talk (about an hour and 15 minutes) but it’s pretty meaty and worth the time if you want to know about the future of Guile. Wingo is a pretty impressive guy so, again, I recommend this talk if you haven’t already seen it. You might also want to check out his blog.

Posted in Programming | Tagged | 1 Comment

Marking Up Key Sequences For HTML

The other day, I wrote about Xah Lee’s post on aliases. One of his aliases was for htmlize-keyboard-shortcut-notation. I realized that this was probably the function he used to markup the key sequences in his posts and I had (yet another) face-palm moment. As you may recall, when I decided to steal borrow his notation I implemented it with Org mode macros. There are a couple of problems with that. First, it’s a pain to type. To get the sequence 【⌘ Cmd+Tab】 I have to type

【{{{key(⌘ Cmd)}}}+{{{key(Tab)}}}】

I have to lookup the unicode value of the ⌘ symbol and enter it with the 【Ctrl+x 8】 key sequence. The same thing applies to the lenticular brackets that frame the key sequence.

Second, I have to include a file that contains the macro definition for every post I make that includes a marked up key sequence. Both of these problems are a result of my initial decision to use Org mode macros to enter the <span> tags that CSS uses to produce the fancy key representations.

When I saw Lee’s alias, I realized that the right way to do this is to enter Cmd+Tab when I want to have the sequence 【⌘ Cmd+Tab】 and then run some elsip code on it. That turns out to be reasonably easy to do.

The idea is to do repeated applications of replace-regexp-in-string with regular expressions and replacement strings such as

"Cmd""@<span class="key"> ⌘ Cmd@</span>"

It’s a pain to keep writing out all that <span> notation so we start with a helper macro

(defmacro key (k)
  "Convenience macro to generate a key sequence map entry
for \\[prettify-key-sequence]."
  `'(,k . ,(concat "@<span class=\"key\">" k "@</span>")))

With this macro, we can transform a key into a Lisp cons

(key "Tab") → ("Tab" . "@<span class=\"key\">Tab@</span>")

With the key macro, it’s pretty easy to write the function to do the markup:

 1:  (defun prettify-key-sequence (&optional omit-brackets)
 2:    "Markup a key sequence for pretty display in HTML.
 3:  If OMIT-BRACKETS is non-null then don't include the key sequence brackets."
 4:    (interactive "P")
 5:    (let* ((seq (region-or-thing 'symbol))
 6:           (key-seq (elt seq 0))
 7:           (beg (elt seq 1))
 8:           (end (elt seq 2))
 9:           (key-seq-map (list (key "Ctrl") (key "Meta") (key "Shift")
10:                              (key "Tab") (key "Alt") (key "Esc")
11:                              (key "Enter") (key "Return") (key "Backspace")
12:                              (key "Delete") (key "F10") (key "F11")
13:                              (key "F12") (key "F2") (key "F3")
14:                              (key "F4") (key "F5") (key "F6") (key "F7")
15:                              (key "F8") (key "F9")
16:                              ;; Disambiguate F1
17:                              '("\\`F1" . "@<span class=\"key\">F1@</span>")
18:                              '("\\([^>]\\)F1" .
19:                                "\\1@<span class=\"key\">F1@</span>")
20:                              ;; Symbol on key
21:                              '("Opt" . "@<span class=\"key\">⌥ Opt@</span>")
22:                              '("Cmd" . "@<span class=\"key\">⌘ Cmd@</span>")
23:                              ;; Combining rules
24:                              '("\+\\(.\\) \\(.\\)\\'" .
25:                                "+@<span class=\"key\">\\1@</span> @<span class=\"key\">\\2@</span>")
26:                              '("\+\\(.\\) \\(.\\) " .
27:                                "+@<span class=\"key\">\\1@</span> @<span class=\"key\">\\2@</span> ")
28:                              '("\+\\(.\\) " .
29:                                "+@<span class=\"key\">\\1@</span> ")
30:                              '("\+\\(.\\)\\'" .
31:                                "+@<span class=\"key\">\\1@</span>"))))
32:      (mapc (lambda (m) (setq key-seq (replace-regexp-in-string
33:                                       (car m) (cdr m) key-seq t)))
34:            key-seq-map)
35:      ;; Single key
36:      (if (= (length key-seq) 1)
37:          (setq key-seq (concat "@<span class=\"key\">" key-seq "@</span>")))
38:      (delete-region beg end)
39:      (if omit-brackets
40:          (insert key-seq)
41:        (insert (concat "【" key-seq "】")))))
42:  

The heart of the function is the key-sequence-map on lines 9–31. Most of the entries are generated with the key macro but some are more complicated and were hand generated. The entries on lines 17–19 take care of preventing F10 (for example) from being mistaken for F1. The two lines at 21 and 22 have a symbol attached so the key macro wouldn’t work. Finally, lines 24–31 take care of combining single letters with the more complex keys.

First, we get the symbol at the point or the region—if there is one—using the region-or-thing function that I wrote about earlier. Then the mapc at line 32 applies replace-regexp-in-string to the raw key sequence repeatedly using the substitution strings in key-squence-map. The code at lines 36 and 37 take care of the special case of a single key. Finally, the original raw key sequence is deleted and replaced with the marked up string. Unless omit-brackets is non-nil, the lenticular brackets are also added.

I don’t need to markup key sequences often enough to bind prettify-key-sequence to a special key sequence so I just made a simpler name for it with an alias:

(defalias 'pks 'prettify-key-sequence)

There are probably some weird key sequences that prettify-key-sequence won’t handle, but those can be done in pieces; that’s why the omit-brackets option is there. The key sequences in the last two posts were done using this function and so far I’m happy with it. One thing for sure: it’s a lot easier than using the Org mode macro as I did before.

Posted in Programming | Tagged | 6 Comments

Emacs Aliases

Xah Lee has a nice post on using Emacs aliases to increase productivity. He uses aliases for two purposes:

  1. To change the behavior of Emacs
    For example, he has the alias
    (defalias 'yes-or-no-p 'y-or-n-p)
    
    

    This gets rid of the annoying “Please answer yes or no” silliness that Emacs insists on for some questions. This was one of the first things I did when setting up my .emacs file and I’ve never been sorry.

  2. As shortcuts for longer, harder-to-remember commands
    For example he has
    (defalias 'dtw 'delete-trailing-whitespace)
    
    

    In this vein, I have long used

    (defalias 'qrr 'query-replace-regexp)
    
    

    because I can never remember if it’s query-regexp-replace or query-replace-regexp. Besides, it’s a lot shorter and easier to type. Another example of this sort that Lee uses is to make alias shortcuts for the different modes that he uses. Thus, he has such shortcuts as

    (defalias 'hm 'html-mode)
    (defalias 'tm 'text-mode)
    (defalias 'wsm 'whitespace-mode)
    
    

    and so on.

You might think that the mode changing aliases aren’t that useful given that they are usually invoked automatically by the file name extension of the file you are editing but sometimes you want to temporarily turn off a mode. For example, as I’ve mentioned previously, it’s sometimes convenient to turn off paredit mode if you have some major restructuring to do. It’s a major pain to have to type 【Meta+xparedit-mode to turn it off and then again to turn it back on. It’s much easier and faster to just type 【Meta +xpm.

Lee keeps all his aliases in a separate file, which makes them easy to find and maintain. I like to keep mine in my init.el file near whatever they are redefining as that makes more sense to me but I can see the advantages to a separate file. What do you like to do?

Posted in General | Tagged | 10 Comments

More Dired Features

On my old blog I wrote about calling FTP from Dired under Emacs and Xah Lee has written several posts about Dired capabilities and how to use them (search for dired at the above link). Now Bart Lantz over at Denver Droid has a nice post on Cool Things to do in Emacs’ Dired Mode. Many of these are the usual things such as deleting or renaming files but he also writes about less well known commands such as 【~】 to mark all backup files for deletion and the 【O】, 【M】, and 【G】 commands to change a file’s owner, mode, and group. He also writes about using dired to clean up your Downloads directory.

There are other ideas in the comments such as using the 【Q】 command to do a regexp search and replace on the marked files or using 【Ctrl+x Ctrl+q】 to enable editing in the dired buffer.

This is a great post and well worth spending a few minutes on. There’s a lot of capability in dired and learning about some of it can help your work flow a lot.

Posted in General | Tagged | Leave a comment

Guile 2.0.2

By now, all you Guile users out there are aware that Guile 2.0.2 has been released. Andy Wingo over at Wingolog has a nice post that explains some of improvements and gives a road map for where Guile is headed. If you want to know exactly what’s changed, the NEWS file has all the details.

I’m also happy to report that unlike last time, the build for OS X was as simple as

./configure
make
sudo make install

so there’s no need to delay. If you’re a Guile user, download the source and build it.

Update: 2.02 → 2.0.2

Posted in Programming | Tagged | Leave a comment