diff --git a/files/IntelligentMigrationSnippets-0.1.dmg b/files/IntelligentMigrationSnippets-0.1.dmg new file mode 100644 index 0000000..a8597fc Binary files /dev/null and b/files/IntelligentMigrationSnippets-0.1.dmg differ diff --git a/files/SJRailsBundle-0.2.dmg b/files/SJRailsBundle-0.2.dmg new file mode 100644 index 0000000..b324194 Binary files /dev/null and b/files/SJRailsBundle-0.2.dmg differ diff --git a/files/download.png b/files/download.png new file mode 100644 index 0000000..3987548 Binary files /dev/null and b/files/download.png differ diff --git a/files/feed-icon-48x48.png b/files/feed-icon-48x48.png new file mode 100644 index 0000000..12ba523 Binary files /dev/null and b/files/feed-icon-48x48.png differ diff --git a/files/feed-icon32x32.png b/files/feed-icon32x32.png new file mode 100644 index 0000000..b08f650 --- /dev/null +++ b/files/feed-icon32x32.png @@ -0,0 +1,256 @@ + + +samhuri.net + + + + + + + + + + + + + + + + +

samhuri.net + + + + + + + + diff --git a/files/gtkpod-aac-fix.sh b/files/gtkpod-aac-fix.sh new file mode 100644 index 0000000..36ea9d7 --- /dev/null +++ b/files/gtkpod-aac-fix.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +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/files/ims-demo.mov b/files/ims-demo.mov new file mode 100644 index 0000000..b12ed37 Binary files /dev/null and b/files/ims-demo.mov differ diff --git a/files/island.css b/files/island.css new file mode 100644 index 0000000..e964827 --- /dev/null +++ b/files/island.css @@ -0,0 +1,451 @@ + + + + + +/* + FILE ARCHIVED ON 4:12:09 Mar 21, 2006 AND RETRIEVED FROM THE + INTERNET ARCHIVE ON 2:38:27 Aug 21, 2011. + JAVASCRIPT APPENDED BY WAYBACK MACHINE, COPYRIGHT INTERNET ARCHIVE. + + ALL OTHER CONTENT MAY ALSO BE PROTECTED BY COPYRIGHT (17 U.S.C. + SECTION 108(a)(3)). +*/ +/* Island screen styles */ + +body { + font: 1em/1.15em "Hoefler Text", Georgia, "Adobe Garamond Pro", Palatino, "Times New Roman", serif; + color: #eee; + background: #000; + margin: 5px; +} + +#leftcolumn { + width: 23%; + float: right; + margin: 0 10px 0 20px; + text-align: right; +} + +#header { +/* text-align: center;*/ +} + +#content { +/* padding-top: 50px;*/ + width: 72%; + float: left; +} + +#main { +} + +#search { + padding: 3px; +} + +#sidebar { +} + +#footer { + text-align: center; +/* background: #333;*/ + border-top: 1px solid #666; + padding-bottom: 5px; + clear: both; +} + +#footer a { border: none; } +#footer img { border: none; } + +/*+-------------------------------------------+ +| LINKS | ++-------------------------------------------+*/ + +a { + color: #5189ea; + text-decoration: none; + border-bottom: 1px dotted #3179ca; + padding-top: 2px; +} + +a:hover { + background: #ffa; + color: #000; +} + +/*+-------------------------------------------+ +| UTILITY | ++-------------------------------------------+*/ + +h1, h2, h3, h4, h5, h6 { + margin: 0; + padding: 0; +} + +form, div { padding: 0; margin: 0; } +p { margin: 0 0 1em 0; padding: 0; } +img { + border: 0; + padding: 5px; +} + +/*+-------------------------------------------+ +| HEADER | ++-------------------------------------------+*/ + +#header h1 { + margin-top: 30px; + font-size: 5em; +} + +#header h1 a { + color: #ffa; + background: inherit; + text-decoration: none; + border-bottom: none; +} + +#header h1 a:hover { + background: #000; +} + +#header h2 { + color: #555; + padding-top: .2em; + font-size: 1.2em; + letter-spacing: 2px; +} + +/*+-------------------------------------------+ +| SEARCH | ++-------------------------------------------+*/ + +#sform { + padding-top: 15px; +} + +#search-results { + text-align: left; + padding-bottom: 5px; + border-bottom: 1px dotted #666; +} + +/*+-------------------------------------------+ +| POST | ++-------------------------------------------+*/ + +.post { + padding: 10px 0 10px 0; + margin: 5px 0 15px 5px; +/* clear: left;*/ +} + +.post h2 { + font-size: 140%; + line-height: 1.4em; + margin: 5px 0; +/* padding-top: 15px;*/ +} + +.post h3 { + margin: 5px 0; +} + +.post h2 a { + color: #fff; + text-decoration: none; + border: none; +} + +.post h2 a:before { + content: '# '; +} + +.post h2 a:hover { + color: #ffa; + background: #000; +} + +.post p { + margin-left: 5px; +} + +p.meta { + font-size: 75%; + text-align: right; + margin-right: 15px; +/* border-right: 1px solid #999;*/ +/* float: left;*/ +/* width: 75px;*/ +} + +p.auth { + font-size: 85%; + font-weight: bold; + color: #999; +} + +/*+-------------------------------------------+ +| COMMENTS | ++-------------------------------------------+*/ + +.comment-list li, #preview { + background: #666; + padding: 5px; + margin-bottom: 8px; + color: #eee; + /*border-right: 20px solid #d3e0ea;*/ + min-height: 60px; +} + +.gravatar { + float: right; + padding: 0 5px; +} + +/*+-------------------------------------------+ +| SIDEBAR | ++-------------------------------------------+*/ + +#sidebar h3 { + font-size: 110%; + line-height: 1.5em; + color: #ff9d47; + margin-top: 15px; + margin-bottom: 2px; + text-transform: lowercase; +} + +#sidebar h3:before { + content: "<< "; + font-size: small; +} +#sidebar h3:after { + content: " >>"; + font-size: small; +} + +#sidebar h3 a { + color: #ff9d47; + border-bottom: 1px dotted #ff9d47; +} + +#sidebar h3 a:hover { + color: #000; + background: #ffa; +} + +#sidebar ul { + text-align: right; + margin: 0; + padding: 0; + list-style-type: none; +} + +#sidebar ul li { +/* background: url(http://web.archive.org/web/20060321041209/http://sami.samhuri.net/images/theme/small_arrow.png) 45% no-repeat;*/ +/* padding-left: 12px;*/ +} + +#sidebar a.feed, +#sidebar a.feed:link, +#sidebar a.feed:hover { + display: inline; + border: none; + background: #000; +} + +/*+-------------------------------------------+ +| FOOTER | ++-------------------------------------------+*/ + +#footer ul { + margin: 0; + padding: 10px 0 0 0; + list-style: none; +} + +#footer ul li { + display: inline; + margin: 0; + padding: 0 5px 0 0; + font-size: 100%; +} + +/*+-------------------------------------------+ +| FORMS | ++-------------------------------------------+*/ + +input, textarea, select { + border: 1px solid #8ab3d1; + background: #f9f9f9; +} + +.frm-tbl td { vertical-align: top; padding: 5px; } +td#frm-btns { text-align: right; } + +#comment_body { height: 220px; } +#form-submit-button { background: #d3e0ea; } + +/*+-------------------------------------------+ +| MISC | ++-------------------------------------------+*/ + +.powered { border: none; } +.powered img { margin-top: 20px; } +.pullquote { + width: 30%; + float:right; + font: 150%/1.5em Times, Helvetica, "Times New Roman", serif; + color: #666; + margin:10px; + background: url(http://web.archive.org/web/20060321041209/http://sami.samhuri.net/images/theme/q-close.gif) no-repeat 70% 100% !important; + background /**/:url(); /* removing quote graphic in IE5+ */ + padding: 0 25px 5px 0; +} +.pullquote:first-letter { + background: url(http://web.archive.org/web/20060321041209/http://sami.samhuri.net/images/theme/q-open.gif) no-repeat left top !important; + padding:5px 2px 10px 35px!important; + padding /**/:0px; /* resetting padding in IE5+ */ + background /**/: url(); /* removing quote graphic in IE5+ */ +} + +.light-bg { background: #666; padding: 2px; } +.clearfix:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} + +#errors { + color: red; +} + +.admintools { + float: right; + background-color: #fff; + font-size: smaller; + padding: 0 2px; + margin: 0 1px; + color: #ccc; + border: 1px solid #ccc; +} + +.admintools:hover { + color: #c00; + border: 1px solid #c00; +} + +a[name] { border: none; } + +/* Hides from IE-mac \*/ +* html .clearfix {height: 1%;} +/* End hide from IE-mac */ + +#categories li em, #archives li em +{ + color: #98B4D1; + font-size: smaller; +} + +/* Syntax highlighting */ +.typocode_ruby .normal {} +.typocode_ruby .comment { color: #005; font-style: italic; } +.typocode_ruby .keyword { color: #A00; font-weight: bold; } +.typocode_ruby .method { color: #077; } +.typocode_ruby .class { color: #074; } +.typocode_ruby .module { color: #050; } +.typocode_ruby .punct { color: #447; font-weight: bold; } +.typocode_ruby .symbol { color: #099; } +.typocode_ruby .string { color: #944; background: #FFE; } +.typocode_ruby .char { color: #F07; } +.typocode_ruby .ident { color: #004; } +.typocode_ruby .constant { color: #07F; } +.typocode_ruby .regex { color: #B66; background: #FEF; } +.typocode_ruby .number { color: #F99; } +.typocode_ruby .attribute { color: #7BB; } +.typocode_ruby .global { color: #7FB; } +.typocode_ruby .expr { color: #227; } +.typocode_ruby .escape { color: #277; } +.typocode_xml .normal {} +.typocode_xml .namespace { color: #B66; font-weight: bold; } +.typocode_xml .tag { color: #F88; } +.typocode_xml .comment { color: #005; font-style: italic; } +.typocode_xml .punct { color: #447; font-weight: bold; } +.typocode_xml .string { color: #944; } +.typocode_xml .number { color: #F99; } +.typocode_xml .attribute { color: #BB7; } +.typocode_yaml .normal {} +.typocode_yaml .document { font-weight: bold; color: #07F; } +.typocode_yaml .type { font-weight: bold; color: #05C; } +.typocode_yaml .key { color: #F88; } +.typocode_yaml .comment { color: #005; font-style: italic; } +.typocode_yaml .punct { color: #447; font-weight: bold; } +.typocode_yaml .string { color: #944; } +.typocode_yaml .number { color: #F99; } +.typocode_yaml .time { color: #F99; } +.typocode_yaml .date { color: #F99; } +.typocode_yaml .ref { color: #944; } +.typocode_yaml .anchor { color: #944; } + +.typocode { + background-color:#eee; + padding:2px; + margin:5px; + margin-left:1em; + margin-bottom:1em; +} + +.typocode pre { + padding: 0px; + margin: 0px; + border: none; + background: transparent; + font-family: monospace; + overflow:auto; +} + + +.typocode .lineno { + text-align: right; + /* color: #B00;*/ + font-family: monospace; + padding-right: 1em; +} + +code { + font-family: "Andale Mono", "Lucida Typewriter", "Bitstream Vera Sans Mono", fixed-width, monospace; +/* font-size: 120%;*/ +} + +pre { + background: #555; + border: 1px dashed #5189ea; + margin-bottom: 30px; + margin-top: -10px; + padding: 5px; +} + +/*+-------------------------------------------+ +| TAGLIST | ++-------------------------------------------+*/ + +ul#taglist li { + display: inline; + line-height: 3em; +} + +.tags .tags0 { font-size: 1.0em; } +.tags .tags1 { font-size: 1.2em; } +.tags .tags2 { font-size: 1.4em; } +.tags .tags3 { font-size: 1.6em; } +.tags .tags4 { font-size: 1.8em; } +.tags .tags5 { font-size: 2.0em; } +.tags .tags6 { font-size: 2.2em; } +.tags .tags7 { font-size: 2.4em; } +.tags .tags8 { font-size: 2.6em; } +.tags .tags9 { font-size: 2.8em; } +.tags .tags10 { font-size: 3.0em; } diff --git a/files/menu.png b/files/menu.png new file mode 100644 index 0000000..637fda6 Binary files /dev/null and b/files/menu.png differ diff --git a/files/spinner-blue.gif b/files/spinner-blue.gif new file mode 100644 index 0000000..409de02 Binary files /dev/null and b/files/spinner-blue.gif differ diff --git a/files/spinner.gif b/files/spinner.gif new file mode 100644 index 0000000..1ed786f Binary files /dev/null and b/files/spinner.gif differ diff --git a/files/volume.rb b/files/volume.rb new file mode 100644 index 0000000..081fca0 --- /dev/null +++ b/files/volume.rb @@ -0,0 +1,21 @@ +#!/usr/bin/env ruby + +Ops = { + :+ => [lambda { |x| x + 5 > 100 ? 100 : x + 5 }, "increased"], + :- => [lambda { |x| x - 5 < 0 ? 0 : x - 5 } , "decreased"] +} + +def vol_op id, vol + [Ops[id].first.call(vol), Ops[id].last] +end + +op = ARGV.shift.to_sym +unless Ops.keys.include?(op) + raise "#{op} is not a valid argument. Expected one of: #{Ops.keys.join(', ')}." +else + `amixer get Master`.split("\n").grep(/%/).first =~ /\[(\d+)/ + vol = $1.to_i + new_vol, action = *vol_op(op, vol) + system("amixer set Master #{new_vol}%") + system("notify-send --urgency=low --icon=~/.icons/audio-volume-medium.gif --expire-time=500 \"Volume #{action}\" \"#{new_vol}%\"") +end diff --git a/files/wrap-region.el b/files/wrap-region.el new file mode 100644 index 0000000..a5a7b34 --- /dev/null +++ b/files/wrap-region.el @@ -0,0 +1,49 @@ +;; 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 ""))) + (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 + +(provide 'wrap-region) diff --git a/rails/@done/2007.05.20-sjs - samhuri.net.html b/rails/@done/2007.05.20-sjs - samhuri.net.html new file mode 100644 index 0000000..4bebd5e --- /dev/null +++ b/rails/@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.

+ + +
+ + +

+Watch the talk on Google’s site +

+
+ +

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/rails/@done/2007.05.28-sjs - samhuri.net.html b/rails/@done/2007.05.28-sjs - samhuri.net.html new file mode 100644 index 0000000..ac80c02 --- /dev/null +++ b/rails/@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.

+ + +
+ + +

+Watch the talk on Google’s site +

+
+ +

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/rails/@done/2007.06.29-sjs - geeky ramblings.html b/rails/@done/2007.06.29-sjs - geeky ramblings.html new file mode 100644 index 0000000..be21821 --- /dev/null +++ b/rails/@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/rails/@done/2007.08.11-sjs - geeky ramblings.html b/rails/@done/2007.08.11-sjs - geeky ramblings.html new file mode 100644 index 0000000..9c25be4 --- /dev/null +++ b/rails/@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/rails/@done/2007.09.10-sjs - geeky ramblings.html b/rails/@done/2007.09.10-sjs - geeky ramblings.html new file mode 100644 index 0000000..388f9bc --- /dev/null +++ b/rails/@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/rails/@done/@first 3.html b/rails/@done/@first 3.html new file mode 100644 index 0000000..73291c5 --- /dev/null +++ b/rails/@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/rails/@done/Coping with Windows XP activiation on a Mac - samhuri.net.html b/rails/@done/Coping with Windows XP activiation on a Mac - samhuri.net.html new file mode 100644 index 0000000..dfcea21 --- /dev/null +++ b/rails/@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/rails/@done/Full-screen Cover Flow - samhuri.net.html b/rails/@done/Full-screen Cover Flow - samhuri.net.html new file mode 100644 index 0000000..ecb6e2e --- /dev/null +++ b/rails/@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/rails/@done/Generate self.down in your Rails migrations - samhuri.net.html b/rails/@done/Generate self.down in your Rails migrations - samhuri.net.html new file mode 100644 index 0000000..72eaaf8 --- /dev/null +++ b/rails/@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/rails/@done/Girlfriend X.html b/rails/@done/Girlfriend X.html new file mode 100644 index 0000000..b0e20ae --- /dev/null +++ b/rails/@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/rails/@done/Ich bin Ausländer und spreche nicht gut Deutsch - samhuri.net.html b/rails/@done/Ich bin Ausländer und spreche nicht gut Deutsch - samhuri.net.html new file mode 100644 index 0000000..ab28e3e --- /dev/null +++ b/rails/@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/rails/@done/Intelligent Migration Snippets 0.1 for TextMate - samhuri.net.html b/rails/@done/Intelligent Migration Snippets 0.1 for TextMate - samhuri.net.html new file mode 100644 index 0000000..d7db913 --- /dev/null +++ b/rails/@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/rails/@done/Jump to view controller in TextMate - samhuri.net.html b/rails/@done/Jump to view controller in TextMate - samhuri.net.html new file mode 100644 index 0000000..bc74e03 --- /dev/null +++ b/rails/@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/rails/@done/Never buy a German keyboard! - samhuri.net.html b/rails/@done/Never buy a German keyboard! - samhuri.net.html new file mode 100644 index 0000000..f3bfab7 --- /dev/null +++ b/rails/@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/rails/@done/Obligatory Post about Ruby on Rails - samhuri.net.html b/rails/@done/Obligatory Post about Ruby on Rails - samhuri.net.html new file mode 100644 index 0000000..043d3bf --- /dev/null +++ b/rails/@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/rails/@done/Some TextMate snippets for Rails Migrations - samhuri.net.html b/rails/@done/Some TextMate snippets for Rails Migrations - samhuri.net.html new file mode 100644 index 0000000..b454b85 --- /dev/null +++ b/rails/@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/rails/@done/Some features you might have missed in iTunes 7 - samhuri.net.html b/rails/@done/Some features you might have missed in iTunes 7 - samhuri.net.html new file mode 100644 index 0000000..628f681 --- /dev/null +++ b/rails/@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/rails/@done/TextMate Insert text into self.down - samhuri.net.html b/rails/@done/TextMate Insert text into self.down - samhuri.net.html new file mode 100644 index 0000000..316809d --- /dev/null +++ b/rails/@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/rails/@done/TextMate Move selection to self.down - samhuri.net.html b/rails/@done/TextMate Move selection to self.down - samhuri.net.html new file mode 100644 index 0000000..1f10b78 --- /dev/null +++ b/rails/@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/rails/@done/TextMate Snippets for Rails Assertions - samhuri.net.html b/rails/@done/TextMate Snippets for Rails Assertions - samhuri.net.html new file mode 100644 index 0000000..1363e09 --- /dev/null +++ b/rails/@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/rails/@done/There's nothing regular about regular expressions - samhuri.net.html b/rails/@done/There's nothing regular about regular expressions - samhuri.net.html new file mode 100644 index 0000000..8df9002 --- /dev/null +++ b/rails/@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/rails/@done/Ubuntu Linux for Linux users please - samhuri.net.html b/rails/@done/Ubuntu Linux for Linux users please - samhuri.net.html new file mode 100644 index 0000000..25a145d --- /dev/null +++ b/rails/@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/rails/@done/Working with the Zend Framework - samhuri.net.html b/rails/@done/Working with the Zend Framework - samhuri.net.html new file mode 100644 index 0000000..0312ebd --- /dev/null +++ b/rails/@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/rails/@done/sjs 301 moved permanently.html b/rails/@done/sjs 301 moved permanently.html new file mode 100644 index 0000000..af6d1c8 --- /dev/null +++ b/rails/@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/rails/@done/sjs 5 ways to avoid looking like a jerk on the Internet.html b/rails/@done/sjs 5 ways to avoid looking like a jerk on the Internet.html new file mode 100644 index 0000000..0b6dbaf --- /dev/null +++ b/rails/@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/rails/@done/sjs A TextMate tip for Emacs users.html b/rails/@done/sjs A TextMate tip for Emacs users.html new file mode 100644 index 0000000..0821213 --- /dev/null +++ b/rails/@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/rails/@done/sjs ActiveRecord Base.find_or_create and find_or_initialize.html b/rails/@done/sjs ActiveRecord Base.find_or_create and find_or_initialize.html new file mode 100644 index 0000000..8974eb3 --- /dev/null +++ b/rails/@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/rails/@done/sjs Back on Gentoo, trying new things.html b/rails/@done/sjs Back on Gentoo, trying new things.html new file mode 100644 index 0000000..5f15d5d --- /dev/null +++ b/rails/@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/rails/@done/sjs Begging the question.html b/rails/@done/sjs Begging the question.html new file mode 100644 index 0000000..59cee52 --- /dev/null +++ b/rails/@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/rails/@done/sjs Captivating little creatures.html b/rails/@done/sjs Captivating little creatures.html new file mode 100644 index 0000000..8e34f48 --- /dev/null +++ b/rails/@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/rails/@done/sjs Catch compiler errors at runtime.html b/rails/@done/sjs Catch compiler errors at runtime.html new file mode 100644 index 0000000..5fe2afe --- /dev/null +++ b/rails/@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/rails/@done/sjs Cheat from Emacs.html b/rails/@done/sjs Cheat from Emacs.html new file mode 100644 index 0000000..6ae004a --- /dev/null +++ b/rails/@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/rails/@done/sjs Cheat productively in Emacs.html b/rails/@done/sjs Cheat productively in Emacs.html new file mode 100644 index 0000000..d5568e1 --- /dev/null +++ b/rails/@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/rails/@done/sjs Controlling volume via the keyboard on Linux.html b/rails/@done/sjs Controlling volume via the keyboard on Linux.html new file mode 100644 index 0000000..2ede49e --- /dev/null +++ b/rails/@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/rails/@done/sjs Digg v4 Reply to replies (Greasemonkey script).html b/rails/@done/sjs Digg v4 Reply to replies (Greasemonkey script).html new file mode 100644 index 0000000..4a79917 --- /dev/null +++ b/rails/@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/rails/@done/sjs Diggscuss 0.9.html b/rails/@done/sjs Diggscuss 0.9.html new file mode 100644 index 0000000..62f635b --- /dev/null +++ b/rails/@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/rails/@done/sjs ElSchemo Boolean logic and branching.html b/rails/@done/sjs ElSchemo Boolean logic and branching.html new file mode 100644 index 0000000..24227ed --- /dev/null +++ b/rails/@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/rails/@done/sjs Emacs tagify-region-or-insert-tag.html b/rails/@done/sjs Emacs tagify-region-or-insert-tag.html new file mode 100644 index 0000000..0e10a8f --- /dev/null +++ b/rails/@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/rails/@done/sjs Emacs for TextMate junkies.html b/rails/@done/sjs Emacs for TextMate junkies.html new file mode 100644 index 0000000..67f60b0 --- /dev/null +++ b/rails/@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/rails/@done/sjs Embrace the database.html b/rails/@done/sjs Embrace the database.html new file mode 100644 index 0000000..b0869a3 --- /dev/null +++ b/rails/@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/rails/@done/sjs Finnish court rules CSS ineffective at protecting DVDs.html b/rails/@done/sjs Finnish court rules CSS ineffective at protecting DVDs.html new file mode 100644 index 0000000..c99cc19 --- /dev/null +++ b/rails/@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/rails/@done/sjs Floating point in ElSchemo.html b/rails/@done/sjs Floating point in ElSchemo.html new file mode 100644 index 0000000..4de41d0 --- /dev/null +++ b/rails/@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/rails/@done/sjs Gtkpod in Gutsy Got You Groaning .html b/rails/@done/sjs Gtkpod in Gutsy Got You Groaning .html new file mode 100644 index 0000000..8bb7301 --- /dev/null +++ b/rails/@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/rails/@done/sjs Learning Lisp Read PCL.html b/rails/@done/sjs Learning Lisp Read PCL.html new file mode 100644 index 0000000..191b686 --- /dev/null +++ b/rails/@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/rails/@done/sjs More Scheming with Haskell.html b/rails/@done/sjs More Scheming with Haskell.html new file mode 100644 index 0000000..975bfcf --- /dev/null +++ b/rails/@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/rails/@done/sjs Opera is pretty slick.html b/rails/@done/sjs Opera is pretty slick.html new file mode 100644 index 0000000..baaf3ce --- /dev/null +++ b/rails/@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/rails/@done/sjs Project Euler code repo in Arc.html b/rails/@done/sjs Project Euler code repo in Arc.html new file mode 100644 index 0000000..fd5b035 --- /dev/null +++ b/rails/@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/rails/@done/sjs Propaganda makes me sick.html b/rails/@done/sjs Propaganda makes me sick.html new file mode 100644 index 0000000..05d77cf --- /dev/null +++ b/rails/@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/rails/@done/sjs Python and Ruby brain dump.html b/rails/@done/sjs Python and Ruby brain dump.html new file mode 100644 index 0000000..a7027cc --- /dev/null +++ b/rails/@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/rails/@done/sjs RTFM!.html b/rails/@done/sjs RTFM!.html new file mode 100644 index 0000000..01a2223 --- /dev/null +++ b/rails/@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/rails/@done/sjs Random pet peeve of the day.html b/rails/@done/sjs Random pet peeve of the day.html new file mode 100644 index 0000000..a557d13 --- /dev/null +++ b/rails/@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 Monsterput 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/rails/@done/sjs Recent Ruby and Rails Regales.html b/rails/@done/sjs Recent Ruby and Rails Regales.html new file mode 100644 index 0000000..2f74553 --- /dev/null +++ b/rails/@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/rails/@done/sjs Reinventing the wheel.html b/rails/@done/sjs Reinventing the wheel.html new file mode 100644 index 0000000..430a269 --- /dev/null +++ b/rails/@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/rails/@done/sjs RushCheck QuickCheck for Ruby.html b/rails/@done/sjs RushCheck QuickCheck for Ruby.html new file mode 100644 index 0000000..c284321 --- /dev/null +++ b/rails/@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/rails/@done/sjs See your regular expressions in Emacs.html b/rails/@done/sjs See your regular expressions in Emacs.html new file mode 100644 index 0000000..971ec6e --- /dev/null +++ b/rails/@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/rails/@done/sjs Snap, crunchle, pop.html b/rails/@done/sjs Snap, crunchle, pop.html new file mode 100644 index 0000000..03950c6 --- /dev/null +++ b/rails/@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/rails/@done/sjs Thoughts on Arc.html b/rails/@done/sjs Thoughts on Arc.html new file mode 100644 index 0000000..bd9e159 --- /dev/null +++ b/rails/@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/rails/@done/sjs people.html b/rails/@done/sjs people.html new file mode 100644 index 0000000..ebd3926 --- /dev/null +++ b/rails/@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/rails/@done/sjs so long typo (and thanks for all the timeouts).html b/rails/@done/sjs so long typo (and thanks for all the timeouts).html new file mode 100644 index 0000000..4080284 --- /dev/null +++ b/rails/@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/rails/@done/sjs test spec on rails declared awesome, just one catch.html b/rails/@done/sjs test spec on rails declared awesome, just one catch.html new file mode 100644 index 0000000..23ba3c5 --- /dev/null +++ b/rails/@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/rails/@done/zsh terminal goodness on OS X - samhuri.net.html b/rails/@done/zsh terminal goodness on OS X - samhuri.net.html new file mode 100644 index 0000000..ad89174 --- /dev/null +++ b/rails/@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/rails/node_modules/jquery/node-jquery.js b/rails/node_modules/jquery/node-jquery.js new file mode 100644 index 0000000..6bb0793 --- /dev/null +++ b/rails/node_modules/jquery/node-jquery.js @@ -0,0 +1,9068 @@ +(function () { +function create(window) { + var location, navigator, XMLHttpRequest; + + window = window || require('jsdom').jsdom().createWindow(); + location = window.location || require('location'); + navigator = window.navigator || require('navigator'); + + if (!window.XMLHttpRequest && 'function' !== typeof window.ActiveXObject) { + window.XMLHttpRequest = require('xmlhttprequest'); // require('XMLHttpRequest'); + // TODO repackage XMLHttpRequest + } + + // end npm / ender header + +/*! + * jQuery JavaScript Library v1.6.3 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Thu Sep 1 11:40:27 2011 -0400 + */ +(function( window, undefined ) { + +// Use the correct document accordingly with window argument (sandbox) +var document = window.document, + navigator = window.navigator, + location = window.location; +var jQuery = (function() { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Check for digits + rdigit = /\d/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Matches dashed string for camelizing + rdashAlpha = /-([a-z]|[0-9])/ig, + rmsPrefix = /^-ms-/, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // The deferred used on DOM ready + readyList, + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = quickExpr.exec( selector ); + } + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = (context ? context.ownerDocument || context : document); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return (context || rootjQuery).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if (selector.selector !== undefined) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.6.3", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + (this.selector ? " " : "") + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.done( fn ); + + return this; + }, + + eq: function( i ) { + return i === -1 ? + this.slice( i ) : + this.slice( i, +i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + // Either a released hold or an DOMready/load event and not yet ready + if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).unbind( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyList ) { + return; + } + + readyList = jQuery._Deferred(); + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNaN: function( obj ) { + return obj == null || !rdigit.test( obj ) || isNaN( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw msg; + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return (new Function( "return " + data ))(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction( object ); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + break; + } + } + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // The extra typeof function check is to prevent crashes + // in Safari 2 (See: #3039) + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type( array ); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array ) { + if ( !array ) { + return -1; + } + + if ( indexOf ) { + return indexOf.call( array, elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + if ( typeof context === "string" ) { + var tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + var args = slice.call( arguments, 2 ), + proxy = function() { + return fn.apply( context, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can optionally be executed if it's a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return (new Date()).getTime(); + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; + }, + + browser: {} +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +return jQuery; + +})(); + + +var // Promise methods + promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), + // Static reference to slice + sliceDeferred = [].slice; + +jQuery.extend({ + // Create a simple deferred (one callbacks list) + _Deferred: function() { + var // callbacks list + callbacks = [], + // stored [ context , args ] + fired, + // to avoid firing when already doing so + firing, + // flag to know if the deferred has been cancelled + cancelled, + // the deferred itself + deferred = { + + // done( f1, f2, ...) + done: function() { + if ( !cancelled ) { + var args = arguments, + i, + length, + elem, + type, + _fired; + if ( fired ) { + _fired = fired; + fired = 0; + } + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + deferred.done.apply( deferred, elem ); + } else if ( type === "function" ) { + callbacks.push( elem ); + } + } + if ( _fired ) { + deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); + } + } + return this; + }, + + // resolve with given context and args + resolveWith: function( context, args ) { + if ( !cancelled && !fired && !firing ) { + // make sure args are available (#8421) + args = args || []; + firing = 1; + try { + while( callbacks[ 0 ] ) { + callbacks.shift().apply( context, args ); + } + } + finally { + fired = [ context, args ]; + firing = 0; + } + } + return this; + }, + + // resolve with this as context and given arguments + resolve: function() { + deferred.resolveWith( this, arguments ); + return this; + }, + + // Has this deferred been resolved? + isResolved: function() { + return !!( firing || fired ); + }, + + // Cancel + cancel: function() { + cancelled = 1; + callbacks = []; + return this; + } + }; + + return deferred; + }, + + // Full fledged deferred (two callbacks list) + Deferred: function( func ) { + var deferred = jQuery._Deferred(), + failDeferred = jQuery._Deferred(), + promise; + // Add errorDeferred methods, then and promise + jQuery.extend( deferred, { + then: function( doneCallbacks, failCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ); + return this; + }, + always: function() { + return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); + }, + fail: failDeferred.done, + rejectWith: failDeferred.resolveWith, + reject: failDeferred.resolve, + isRejected: failDeferred.isResolved, + pipe: function( fnDone, fnFail ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ] + }, function( handler, data ) { + var fn = data[ 0 ], + action = data[ 1 ], + returned; + if ( jQuery.isFunction( fn ) ) { + deferred[ handler ](function() { + returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise().then( newDefer.resolve, newDefer.reject ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + }); + } else { + deferred[ handler ]( newDefer[ action ] ); + } + }); + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + if ( obj == null ) { + if ( promise ) { + return promise; + } + promise = obj = {}; + } + var i = promiseMethods.length; + while( i-- ) { + obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; + } + return obj; + } + }); + // Make sure only one callback list will be used + deferred.done( failDeferred.cancel ).fail( deferred.cancel ); + // Unexpose cancel + delete deferred.cancel; + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + return deferred; + }, + + // Deferred helper + when: function( firstParam ) { + var args = arguments, + i = 0, + length = args.length, + count = length, + deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? + firstParam : + jQuery.Deferred(); + function resolveFunc( i ) { + return function( value ) { + args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + // Strange bug in FF4: + // Values changed onto the arguments object sometimes end up as undefined values + // outside the $.when method. Cloning the object into a fresh array solves the issue + deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); + } + }; + } + if ( length > 1 ) { + for( ; i < length; i++ ) { + if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( deferred, args ); + } + } else if ( deferred !== firstParam ) { + deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); + } + return deferred.promise(); + } +}); + + + +jQuery.support = (function() { + + var div = document.createElement( "div" ), + documentElement = document.documentElement, + all, + a, + select, + opt, + input, + marginDiv, + support, + fragment, + body, + testElementParent, + testElement, + testElementStyle, + tds, + events, + eventName, + i, + isSupported; + + // Preliminary tests + div.setAttribute("className", "t"); + div.innerHTML = "
a"; + + + all = div.getElementsByTagName( "*" ); + a = div.getElementsByTagName( "a" )[ 0 ]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement( "select" ); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName( "input" )[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName( "tbody" ).length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName( "link" ).length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55$/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent( "onclick" ); + } + + // Check if a radio maintains it's value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute("type", "radio"); + support.radioValue = input.value === "t"; + + input.setAttribute("checked", "checked"); + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.firstChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + div.innerHTML = ""; + + // Figure out if the W3C box model works as expected + div.style.width = div.style.paddingLeft = "1px"; + + body = document.getElementsByTagName( "body" )[ 0 ]; + // We use our own, invisible, body unless the body is already present + // in which case we use a div (#9239) + testElement = document.createElement( body ? "div" : "body" ); + testElementStyle = { + visibility: "hidden", + width: 0, + height: 0, + border: 0, + margin: 0, + background: "none" + }; + if ( body ) { + jQuery.extend( testElementStyle, { + position: "absolute", + left: "-1000px", + top: "-1000px" + }); + } + for ( i in testElementStyle ) { + testElement.style[ i ] = testElementStyle[ i ]; + } + testElement.appendChild( div ); + testElementParent = body || documentElement; + testElementParent.insertBefore( testElement, testElementParent.firstChild ); + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + support.boxModel = div.offsetWidth === 2; + + if ( "zoom" in div.style ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "
"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); + } + + div.innerHTML = "
t
"; + tds = div.getElementsByTagName( "td" ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE < 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + div.innerHTML = ""; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + if ( document.defaultView && document.defaultView.getComputedStyle ) { + marginDiv = document.createElement( "div" ); + marginDiv.style.width = "0"; + marginDiv.style.marginRight = "0"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; + } + + // Remove the body element we added + testElement.innerHTML = ""; + testElementParent.removeChild( testElement ); + + // Technique from Juriy Zaytsev + // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for( i in { + submit: 1, + change: 1, + focusin: 1 + } ) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + // Null connected elements to avoid leaks in IE + testElement = fragment = select = opt = body = marginDiv = div = input = null; + + return support; +})(); + +// Keep track of boxModel +jQuery.boxModel = jQuery.support.boxModel; + + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([a-z])([A-Z])/g; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || (pvt && id && (cache[ id ] && !cache[ id ][ internalKey ]))) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ jQuery.expando ] = id = ++jQuery.uuid; + } else { + id = jQuery.expando; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery + // metadata on plain JS objects when the object is serialized using + // JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); + } else { + cache[ id ] = jQuery.extend(cache[ id ], name); + } + } + + thisCache = cache[ id ]; + + // Internal jQuery data is stored in a separate object inside the object's data + // cache in order to avoid key collisions between internal data and user-defined + // data + if ( pvt ) { + if ( !thisCache[ internalKey ] ) { + thisCache[ internalKey ] = {}; + } + + thisCache = thisCache[ internalKey ]; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should + // not attempt to inspect the internal events object using jQuery.data, as this + // internal data object is undocumented and subject to change. + if ( name === "events" && !thisCache[name] ) { + return thisCache[ internalKey ] && thisCache[ internalKey ].events; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, + + // Reference to internal data cache key + internalKey = jQuery.expando, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; + + if ( thisCache ) { + + // Support interoperable removal of hyphenated or camelcased keys + if ( !thisCache[ name ] ) { + name = jQuery.camelCase( name ); + } + + delete thisCache[ name ]; + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !isEmptyDataObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( pvt ) { + delete cache[ id ][ internalKey ]; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject(cache[ id ]) ) { + return; + } + } + + var internalCache = cache[ id ][ internalKey ]; + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + // Ensure that `cache` is not a window object #10080 + if ( jQuery.support.deleteExpando || !cache.setInterval ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the entire user cache at once because it's faster than + // iterating through each key, but we need to continue to persist internal + // data if it existed + if ( internalCache ) { + cache[ id ] = {}; + // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery + // metadata on plain JS objects when the object is serialized using + // JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + + cache[ id ][ internalKey ] = internalCache; + + // Otherwise, we need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + } else if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ jQuery.expando ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( jQuery.expando ); + } else { + elem[ jQuery.expando ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 ) { + var attr = this[0].attributes, name; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( this[0], name, data[ name ] ); + } + } + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + var parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var $this = jQuery( this ), + args = [ parts[0], value ]; + + $this.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + $this.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + !jQuery.isNaN( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON +// property to be considered empty objects; this property always exists in +// order to make sure JSON.stringify does not expose internal metadata +function isEmptyDataObject( obj ) { + for ( var name in obj ) { + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + + + + +function handleQueueMarkDefer( elem, type, src ) { + var deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + defer = jQuery.data( elem, deferDataKey, undefined, true ); + if ( defer && + ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && + ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { + // Give room for hard-coded callbacks to fire first + // and eventually mark/queue something else on the element + setTimeout( function() { + if ( !jQuery.data( elem, queueDataKey, undefined, true ) && + !jQuery.data( elem, markDataKey, undefined, true ) ) { + jQuery.removeData( elem, deferDataKey, true ); + defer.resolve(); + } + }, 0 ); + } +} + +jQuery.extend({ + + _mark: function( elem, type ) { + if ( elem ) { + type = (type || "fx") + "mark"; + jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); + } + }, + + _unmark: function( force, elem, type ) { + if ( force !== true ) { + type = elem; + elem = force; + force = false; + } + if ( elem ) { + type = type || "fx"; + var key = type + "mark", + count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); + if ( count ) { + jQuery.data( elem, key, count, true ); + } else { + jQuery.removeData( elem, key, true ); + handleQueueMarkDefer( elem, type, "mark" ); + } + } + }, + + queue: function( elem, type, data ) { + if ( elem ) { + type = (type || "fx") + "queue"; + var q = jQuery.data( elem, type, undefined, true ); + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !q || jQuery.isArray(data) ) { + q = jQuery.data( elem, type, jQuery.makeArray(data), true ); + } else { + q.push( data ); + } + } + return q || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(), + defer; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift("inprogress"); + } + + fn.call(elem, function() { + jQuery.dequeue(elem, type); + }); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue", true ); + handleQueueMarkDefer( elem, type, "queue" ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function() { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; + type = type || "fx"; + + return this.queue( type, function() { + var elem = this; + setTimeout(function() { + jQuery.dequeue( elem, type ); + }, time ); + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, object ) { + if ( typeof type !== "string" ) { + object = type; + type = undefined; + } + type = type || "fx"; + var defer = jQuery.Deferred(), + elements = this, + i = elements.length, + count = 1, + deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + tmp; + function resolve() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + } + while( i-- ) { + if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || + ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || + jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && + jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { + count++; + tmp.done( resolve ); + } + } + resolve(); + return defer.promise(); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspace = /\s+/, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + nodeHook, boolHook; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.prop ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + classNames = (value || "").split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[ c ] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " "; + for ( var i = 0, l = this.length; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return undefined; + } + + var isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var self = jQuery(this), val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attrFix: { + // Always normalize to ensure hook usage + tabindex: "tabIndex" + }, + + attr: function( elem, name, value, pass ) { + var nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return undefined; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( !("getAttribute" in elem) ) { + return jQuery.prop( elem, name, value ); + } + + var ret, hooks, + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // Normalize the name if needed + if ( notxml ) { + name = jQuery.attrFix[ name ] || name; + + hooks = jQuery.attrHooks[ name ]; + + if ( !hooks ) { + // Use boolHook for boolean attributes + if ( rboolean.test( name ) ) { + hooks = boolHook; + + // Use nodeHook if available( IE6/7 ) + } else if ( nodeHook ) { + hooks = nodeHook; + } + } + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return undefined; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, name ) { + var propName; + if ( elem.nodeType === 1 ) { + name = jQuery.attrFix[ name ] || name; + + jQuery.attr( elem, name, "" ); + elem.removeAttribute( name ); + + // Set corresponding property to false for boolean attributes + if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { + elem[ propName ] = false; + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return undefined; + } + + var ret, hooks, + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return (elem[ name ] = value); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Add the tabindex propHook to attrHooks for back-compat +jQuery.attrHooks.tabIndex = jQuery.propHooks.tabIndex; + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode; + return jQuery.prop( elem, name ) === true || ( attrNode = elem.getAttributeNode( name ) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !jQuery.support.getSetAttribute ) { + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + // Return undefined if nodeValue is empty string + return ret && ret.nodeValue !== "" ? + ret.nodeValue : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return (ret.nodeValue = value + ""); + } + }; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return (elem.style.cssText = "" + value); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); + } + } + }); +}); + + + + +var rnamespaces = /\.(.*)$/, + rformElems = /^(?:textarea|input|select)$/i, + rperiod = /\./g, + rspaces = / /g, + rescape = /[^\w\s.|`]/g, + fcleanup = function( nm ) { + return nm.replace(rescape, "\\$&"); + }; + +/* + * A number of helper functions used for managing events. + * Many of the ideas behind this code originated from + * Dean Edwards' addEvent library. + */ +jQuery.event = { + + // Bind an event to an element + // Original by Dean Edwards + add: function( elem, types, handler, data ) { + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + if ( handler === false ) { + handler = returnFalse; + } else if ( !handler ) { + // Fixes bug #7229. Fix recommended by jdalton + return; + } + + var handleObjIn, handleObj; + + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the function being executed has a unique ID + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure + var elemData = jQuery._data( elem ); + + // If no elemData is found then we must be trying to bind to one of the + // banned noData elements + if ( !elemData ) { + return; + } + + var events = elemData.events, + eventHandle = elemData.handle; + + if ( !events ) { + elemData.events = events = {}; + } + + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.handle.apply( eventHandle.elem, arguments ) : + undefined; + }; + } + + // Add elem as a property of the handle function + // This is to prevent a memory leak with non-native events in IE. + eventHandle.elem = elem; + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = types.split(" "); + + var type, i = 0, namespaces; + + while ( (type = types[ i++ ]) ) { + handleObj = handleObjIn ? + jQuery.extend({}, handleObjIn) : + { handler: handler, data: data }; + + // Namespaced event handlers + if ( type.indexOf(".") > -1 ) { + namespaces = type.split("."); + type = namespaces.shift(); + handleObj.namespace = namespaces.slice(0).sort().join("."); + + } else { + namespaces = []; + handleObj.namespace = ""; + } + + handleObj.type = type; + if ( !handleObj.guid ) { + handleObj.guid = handler.guid; + } + + // Get the current list of functions bound to this event + var handlers = events[ type ], + special = jQuery.event.special[ type ] || {}; + + // Init the event handler queue + if ( !handlers ) { + handlers = events[ type ] = []; + + // Check for a special event handler + // Only use addEventListener/attachEvent if the special + // events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add the function to the element's handler list + handlers.push( handleObj ); + + // Keep track of which events have been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, pos ) { + // don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + if ( handler === false ) { + handler = returnFalse; + } + + var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + events = elemData && elemData.events; + + if ( !elemData || !events ) { + return; + } + + // types is actually an event object here + if ( types && types.type ) { + handler = types.handler; + types = types.type; + } + + // Unbind all events for the element + if ( !types || typeof types === "string" && types.charAt(0) === "." ) { + types = types || ""; + + for ( type in events ) { + jQuery.event.remove( elem, type + types ); + } + + return; + } + + // Handle multiple events separated by a space + // jQuery(...).unbind("mouseover mouseout", fn); + types = types.split(" "); + + while ( (type = types[ i++ ]) ) { + origType = type; + handleObj = null; + all = type.indexOf(".") < 0; + namespaces = []; + + if ( !all ) { + // Namespaced event handlers + namespaces = type.split("."); + type = namespaces.shift(); + + namespace = new RegExp("(^|\\.)" + + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + eventType = events[ type ]; + + if ( !eventType ) { + continue; + } + + if ( !handler ) { + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( all || namespace.test( handleObj.namespace ) ) { + jQuery.event.remove( elem, origType, handleObj.handler, j ); + eventType.splice( j--, 1 ); + } + } + + continue; + } + + special = jQuery.event.special[ type ] || {}; + + for ( j = pos || 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( handler.guid === handleObj.guid ) { + // remove the given handler for the given type + if ( all || namespace.test( handleObj.namespace ) ) { + if ( pos == null ) { + eventType.splice( j--, 1 ); + } + + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + + if ( pos != null ) { + break; + } + } + } + + // remove generic event handler if no more handlers exist + if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + ret = null; + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + var handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + delete elemData.events; + delete elemData.handle; + + if ( jQuery.isEmptyObject( elemData ) ) { + jQuery.removeData( elem, undefined, true ); + } + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Event object or event type + var type = event.type || event, + namespaces = [], + exclusive; + + if ( type.indexOf("!") >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.exclusive = exclusive; + event.namespace = namespaces.join("."); + event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); + + // triggerHandler() and global events don't bubble or run the default action + if ( onlyHandlers || !elem ) { + event.preventDefault(); + event.stopPropagation(); + } + + // Handle a global trigger + if ( !elem ) { + // TODO: Stop taunting the data cache; remove global events and always attach to document + jQuery.each( jQuery.cache, function() { + // internalKey variable is just used to make it easier to find + // and potentially change this stuff later; currently it just + // points to jQuery.expando + var internalKey = jQuery.expando, + internalCache = this[ internalKey ]; + if ( internalCache && internalCache.events && internalCache.events[ type ] ) { + jQuery.event.trigger( event, data, internalCache.handle.elem ); + } + }); + return; + } + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + event.target = elem; + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + var cur = elem, + // IE doesn't like method names with a colon (#3533, #8272) + ontype = type.indexOf(":") < 0 ? "on" + type : ""; + + // Fire event on the current element, then bubble up the DOM tree + do { + var handle = jQuery._data( cur, "handle" ); + + event.currentTarget = cur; + if ( handle ) { + handle.apply( cur, data ); + } + + // Trigger an inline bound script + if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { + event.result = false; + event.preventDefault(); + } + + // Bubble up to document, then to window + cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; + } while ( cur && !event.isPropagationStopped() ); + + // If nobody prevented the default action, do it now + if ( !event.isDefaultPrevented() ) { + var old, + special = jQuery.event.special[ type ] || {}; + + if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction)() check here because IE6/7 fails that test. + // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. + try { + if ( ontype && elem[ type ] ) { + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + jQuery.event.triggered = type; + elem[ type ](); + } + } catch ( ieError ) {} + + if ( old ) { + elem[ ontype ] = old; + } + + jQuery.event.triggered = undefined; + } + } + + return event.result; + }, + + handle: function( event ) { + event = jQuery.event.fix( event || window.event ); + // Snapshot the handlers list since a called handler may add/remove events. + var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), + run_all = !event.exclusive && !event.namespace, + args = Array.prototype.slice.call( arguments, 0 ); + + // Use the fix-ed Event rather than the (read-only) native event + args[0] = event; + event.currentTarget = this; + + for ( var j = 0, l = handlers.length; j < l; j++ ) { + var handleObj = handlers[ j ]; + + // Triggered event must 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event. + if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { + // Pass in a reference to the handler function itself + // So that we can later remove it + event.handler = handleObj.handler; + event.data = handleObj.data; + event.handleObj = handleObj; + + var ret = handleObj.handler.apply( this, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + + if ( event.isImmediatePropagationStopped() ) { + break; + } + } + } + return event.result; + }, + + props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // store a copy of the original event object + // and "clone" to set read-only properties + var originalEvent = event; + event = jQuery.Event( originalEvent ); + + for ( var i = this.props.length, prop; i; ) { + prop = this.props[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary + if ( !event.target ) { + // Fixes #1925 where srcElement might not be defined either + event.target = event.srcElement || document; + } + + // check if target is a textnode (safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && event.fromElement ) { + event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; + } + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && event.clientX != null ) { + var eventDocument = event.target.ownerDocument || document, + doc = eventDocument.documentElement, + body = eventDocument.body; + + event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); + event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); + } + + // Add which for key events + if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { + event.which = event.charCode != null ? event.charCode : event.keyCode; + } + + // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) + if ( !event.metaKey && event.ctrlKey ) { + event.metaKey = event.ctrlKey; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && event.button !== undefined ) { + event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); + } + + return event; + }, + + // Deprecated, use jQuery.guid instead + guid: 1E8, + + // Deprecated, use jQuery.proxy instead + proxy: jQuery.proxy, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady, + teardown: jQuery.noop + }, + + live: { + add: function( handleObj ) { + jQuery.event.add( this, + liveConvert( handleObj.origType, handleObj.selector ), + jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); + }, + + remove: function( handleObj ) { + jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); + } + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !this.preventDefault ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // timeStamp is buggy for some events on Firefox(#3843) + // So we won't rely on the native value + this.timeStamp = jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Checks if an event happened on an element within another element +// Used in jQuery.event.special.mouseenter and mouseleave handlers +var withinElement = function( event ) { + + // Check if mouse(over|out) are still within the same parent element + var related = event.relatedTarget, + inside = false, + eventType = event.type; + + event.type = event.data; + + if ( related !== this ) { + + if ( related ) { + inside = jQuery.contains( this, related ); + } + + if ( !inside ) { + + jQuery.event.handle.apply( this, arguments ); + + event.type = eventType; + } + } +}, + +// In case of event delegation, we only need to rename the event.type, +// liveHandler will take care of the rest. +delegate = function( event ) { + event.type = event.data; + jQuery.event.handle.apply( this, arguments ); +}; + +// Create mouseenter and mouseleave events +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + setup: function( data ) { + jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); + }, + teardown: function( data ) { + jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); + } + }; +}); + +// submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function( data, namespaces ) { + if ( !jQuery.nodeName( this, "form" ) ) { + jQuery.event.add(this, "click.specialSubmit", function( e ) { + var elem = e.target, + type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; + + if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { + trigger( "submit", this, arguments ); + } + }); + + jQuery.event.add(this, "keypress.specialSubmit", function( e ) { + var elem = e.target, + type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; + + if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { + trigger( "submit", this, arguments ); + } + }); + + } else { + return false; + } + }, + + teardown: function( namespaces ) { + jQuery.event.remove( this, ".specialSubmit" ); + } + }; + +} + +// change delegation, happens here so we have bind. +if ( !jQuery.support.changeBubbles ) { + + var changeFilters, + + getVal = function( elem ) { + var type = jQuery.nodeName( elem, "input" ) ? elem.type : "", + val = elem.value; + + if ( type === "radio" || type === "checkbox" ) { + val = elem.checked; + + } else if ( type === "select-multiple" ) { + val = elem.selectedIndex > -1 ? + jQuery.map( elem.options, function( elem ) { + return elem.selected; + }).join("-") : + ""; + + } else if ( jQuery.nodeName( elem, "select" ) ) { + val = elem.selectedIndex; + } + + return val; + }, + + testChange = function testChange( e ) { + var elem = e.target, data, val; + + if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { + return; + } + + data = jQuery._data( elem, "_change_data" ); + val = getVal(elem); + + // the current data will be also retrieved by beforeactivate + if ( e.type !== "focusout" || elem.type !== "radio" ) { + jQuery._data( elem, "_change_data", val ); + } + + if ( data === undefined || val === data ) { + return; + } + + if ( data != null || val ) { + e.type = "change"; + e.liveFired = undefined; + jQuery.event.trigger( e, arguments[1], elem ); + } + }; + + jQuery.event.special.change = { + filters: { + focusout: testChange, + + beforedeactivate: testChange, + + click: function( e ) { + var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; + + if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { + testChange.call( this, e ); + } + }, + + // Change has to be called before submit + // Keydown will be called before keypress, which is used in submit-event delegation + keydown: function( e ) { + var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; + + if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || + (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || + type === "select-multiple" ) { + testChange.call( this, e ); + } + }, + + // Beforeactivate happens also before the previous element is blurred + // with this event you can't trigger a change event, but you can store + // information + beforeactivate: function( e ) { + var elem = e.target; + jQuery._data( elem, "_change_data", getVal(elem) ); + } + }, + + setup: function( data, namespaces ) { + if ( this.type === "file" ) { + return false; + } + + for ( var type in changeFilters ) { + jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); + } + + return rformElems.test( this.nodeName ); + }, + + teardown: function( namespaces ) { + jQuery.event.remove( this, ".specialChange" ); + + return rformElems.test( this.nodeName ); + } + }; + + changeFilters = jQuery.event.special.change.filters; + + // Handle when the input is .focus()'d + changeFilters.focus = changeFilters.beforeactivate; +} + +function trigger( type, elem, args ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + // Don't pass args or remember liveFired; they apply to the donor event. + var event = jQuery.extend( {}, args[ 0 ] ); + event.type = type; + event.originalEvent = {}; + event.liveFired = undefined; + jQuery.event.handle.call( elem, event ); + if ( event.isDefaultPrevented() ) { + args[ 0 ].preventDefault(); + } +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + + function handler( donor ) { + // Donor event is always a native one; fix it and switch its type. + // Let focusin/out handler cancel the donor focus/blur event. + var e = jQuery.event.fix( donor ); + e.type = fix; + e.originalEvent = {}; + jQuery.event.trigger( e, null, e.target ); + if ( e.isDefaultPrevented() ) { + donor.preventDefault(); + } + } + }); +} + +jQuery.each(["bind", "one"], function( i, name ) { + jQuery.fn[ name ] = function( type, data, fn ) { + var handler; + + // Handle object literals + if ( typeof type === "object" ) { + for ( var key in type ) { + this[ name ](key, data, type[key], fn); + } + return this; + } + + if ( arguments.length === 2 || data === false ) { + fn = data; + data = undefined; + } + + if ( name === "one" ) { + handler = function( event ) { + jQuery( this ).unbind( event, handler ); + return fn.apply( this, arguments ); + }; + handler.guid = fn.guid || jQuery.guid++; + } else { + handler = fn; + } + + if ( type === "unload" && name !== "one" ) { + this.one( type, data, fn ); + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + jQuery.event.add( this[i], type, handler, data ); + } + } + + return this; + }; +}); + +jQuery.fn.extend({ + unbind: function( type, fn ) { + // Handle object literals + if ( typeof type === "object" && !type.preventDefault ) { + for ( var key in type ) { + this.unbind(key, type[key]); + } + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + jQuery.event.remove( this[i], type, fn ); + } + } + + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.live( types, data, fn, selector ); + }, + + undelegate: function( selector, types, fn ) { + if ( arguments.length === 0 ) { + return this.unbind( "live" ); + + } else { + return this.die( types, null, fn, selector ); + } + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +var liveMap = { + focus: "focusin", + blur: "focusout", + mouseenter: "mouseover", + mouseleave: "mouseout" +}; + +jQuery.each(["live", "die"], function( i, name ) { + jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { + var type, i = 0, match, namespaces, preType, + selector = origSelector || this.selector, + context = origSelector ? this : jQuery( this.context ); + + if ( typeof types === "object" && !types.preventDefault ) { + for ( var key in types ) { + context[ name ]( key, data, types[key], selector ); + } + + return this; + } + + if ( name === "die" && !types && + origSelector && origSelector.charAt(0) === "." ) { + + context.unbind( origSelector ); + + return this; + } + + if ( data === false || jQuery.isFunction( data ) ) { + fn = data || returnFalse; + data = undefined; + } + + types = (types || "").split(" "); + + while ( (type = types[ i++ ]) != null ) { + match = rnamespaces.exec( type ); + namespaces = ""; + + if ( match ) { + namespaces = match[0]; + type = type.replace( rnamespaces, "" ); + } + + if ( type === "hover" ) { + types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); + continue; + } + + preType = type; + + if ( liveMap[ type ] ) { + types.push( liveMap[ type ] + namespaces ); + type = type + namespaces; + + } else { + type = (liveMap[ type ] || type) + namespaces; + } + + if ( name === "live" ) { + // bind live handler + for ( var j = 0, l = context.length; j < l; j++ ) { + jQuery.event.add( context[j], "live." + liveConvert( type, selector ), + { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); + } + + } else { + // unbind live handler + context.unbind( "live." + liveConvert( type, selector ), fn ); + } + } + + return this; + }; +}); + +function liveHandler( event ) { + var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, + elems = [], + selectors = [], + events = jQuery._data( this, "events" ); + + // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) + if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { + return; + } + + if ( event.namespace ) { + namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + event.liveFired = this; + + var live = events.live.slice(0); + + for ( j = 0; j < live.length; j++ ) { + handleObj = live[j]; + + if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { + selectors.push( handleObj.selector ); + + } else { + live.splice( j--, 1 ); + } + } + + match = jQuery( event.target ).closest( selectors, event.currentTarget ); + + for ( i = 0, l = match.length; i < l; i++ ) { + close = match[i]; + + for ( j = 0; j < live.length; j++ ) { + handleObj = live[j]; + + if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { + elem = close.elem; + related = null; + + // Those two events require additional checking + if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { + event.type = handleObj.preType; + related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; + + // Make sure not to accidentally match a child element with the same selector + if ( related && jQuery.contains( elem, related ) ) { + related = elem; + } + } + + if ( !related || related !== elem ) { + elems.push({ elem: elem, handleObj: handleObj, level: close.level }); + } + } + } + } + + for ( i = 0, l = elems.length; i < l; i++ ) { + match = elems[i]; + + if ( maxLevel && match.level > maxLevel ) { + break; + } + + event.currentTarget = match.elem; + event.data = match.handleObj.data; + event.handleObj = match.handleObj; + + ret = match.handleObj.origHandler.apply( match.elem, arguments ); + + if ( ret === false || event.isPropagationStopped() ) { + maxLevel = match.level; + + if ( ret === false ) { + stop = false; + } + if ( event.isImmediatePropagationStopped() ) { + break; + } + } + } + + return stop; +} + +function liveConvert( type, selector ) { + return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); +} + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.bind( name, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } +}); + + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rNonWord = /\W/; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set; + + if ( !expr ) { + return []; + } + + for ( var i = 0, l = Expr.order.length; i < l; i++ ) { + var match, + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + var left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( var type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + var found, item, + filter = Expr.filter[ type ], + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( var i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + var pass = not ^ !!found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw "Syntax error, unrecognized expression: " + msg; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + }, + type: function( elem ) { + return elem.getAttribute( "type" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace( rBackslash, "" ); + }, + + TAG: function( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + var attr = elem.getAttribute( "type" ), type = elem.type; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); + }, + + radio: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; + }, + + checkbox: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; + }, + + file: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; + }, + + password: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; + }, + + submit: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "submit" === elem.type; + }, + + image: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; + }, + + reset: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "reset" === elem.type; + }, + + button: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && "button" === elem.type || name === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + }, + + focus: function( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + var first = match[2], + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + var doneName = match[0], + parent = elem.parentNode; + + if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { + var count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent.sizcache = doneName; + } + + var diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Utility function for retreiving the text value of an array of DOM nodes +Sizzle.getText = function( elems ) { + var ret = "", elem; + + for ( var i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += Sizzle.getText( elem.childNodes ); + } + } + + return ret; +}; + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = ""; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "

"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; + + if ( matches ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9 fails this) + var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + var ret = matches.call( node, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || !disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9, so check for that + node.document && node.document.nodeType !== 11 ) { + return ret; + } + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "
"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var self = this, + i, l; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + var ret = this.pushStack( "", "find", selector ), + length, n, r; + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( typeof selector === "string" ? + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + // Array + if ( jQuery.isArray( selectors ) ) { + var match, selector, + matches = {}, + level = 1; + + if ( cur && selectors.length ) { + for ( i = 0, l = selectors.length; i < l; i++ ) { + selector = selectors[i]; + + if ( !matches[ selector ] ) { + matches[ selector ] = POS.test( selector ) ? + jQuery( selector, context || this.context ) : + selector; + } + } + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( selector in matches ) { + match = matches[ selector ]; + + if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { + ret.push({ selector: selector, elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + } + + return ret; + } + + // String + var pos = POS.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ), + // The variable 'args' was introduced in + // https://github.com/jquery/jquery/commit/52a0238 + // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. + // http://code.google.com/p/v8/issues/detail?id=1050 + args = slice.call(arguments); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, args.join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return (elem === qualifier) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return (jQuery.inArray( elem, qualifier ) >= 0) === keep; + }); +} + + + + +var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /", "" ], + legend: [ 1, "
", "
" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + col: [ 2, "", "
" ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }; + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize and + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/rails/node_modules/jquery/node_modules/htmlparser/.tmp_runtests.min.html.92328~ b/rails/node_modules/jquery/node_modules/htmlparser/.tmp_runtests.min.html.92328~ new file mode 100644 index 0000000..8be48ac --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/.tmp_runtests.min.html.92328~ @@ -0,0 +1,108 @@ + + + + + Node.js HTML Parser + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/rails/node_modules/jquery/node_modules/htmlparser/CHANGELOG b/rails/node_modules/jquery/node_modules/htmlparser/CHANGELOG new file mode 100644 index 0000000..7195f26 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/CHANGELOG @@ -0,0 +1,33 @@ + +v1.7.2 + * Document position feature fixed to work correctly with chunked parsing + +v1.7.1 + * Document position feature disabled until it works correctly with chunked parsing + +v1.7.0 + * Empty tag checking switch to being case insensitive [fgnass] + * Added feature to include document position (row, col) in element data [fgnass] + * Added parser option "includeLocation" to enable document position data + +v1.6.4 + * Fixed 'prevElement' error [Swizec] + +v1.6.3 + * Updated to support being an npm package + * Fixed DomUtils.testElement() + +v1.6.1 + * Optimized DomUtils by up to 2-3x + +v1.6.0 + * Added support for RSS/Atom feeds + +v1.5.0 + * Added DefaultHandler option "enforceEmptyTags" so that XML can be parsed correctly + +v1.4.2 + * Added tests for parsing XML with namespaces + +v1.4.1 + * Added minified version diff --git a/rails/node_modules/jquery/node_modules/htmlparser/LICENSE b/rails/node_modules/jquery/node_modules/htmlparser/LICENSE new file mode 100644 index 0000000..3196dba --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/LICENSE @@ -0,0 +1,18 @@ +Copyright 2010, Chris Winberry . All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. \ No newline at end of file diff --git a/rails/node_modules/jquery/node_modules/htmlparser/README.md b/rails/node_modules/jquery/node_modules/htmlparser/README.md new file mode 100644 index 0000000..e81ceb3 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/README.md @@ -0,0 +1,186 @@ +#NodeHtmlParser +A forgiving HTML/XML/RSS parser written in JS for both the browser and NodeJS (yes, despite the name it works just fine in any modern browser). The parser can handle streams (chunked data) and supports custom handlers for writing custom DOMs/output. + +##Installing + + npm install htmlparser + +##Running Tests + +###Run tests under node: + node runtests.js + +###Run tests in browser: +View runtests.html in any browser + +##Usage In Node + var htmlparser = require("node-htmlparser"); + var rawHtml = "Xyz + , Style: "style" //Special tag + , Tag: "tag" //Any tag that isn't special +} + +function Parser (handler, options) { + this._options = options ? options : { }; + if (this._options.includeLocation == undefined) { + this._options.includeLocation = false; //Do not track element position in document by default + } + + this.validateHandler(handler); + this._handler = handler; + this.reset(); +} + + //**"Static"**// + //Regular expressions used for cleaning up and parsing (stateless) + Parser._reTrim = /(^\s+|\s+$)/g; //Trim leading/trailing whitespace + Parser._reTrimComment = /(^\!--|--$)/g; //Remove comment tag markup from comment contents + Parser._reWhitespace = /\s/g; //Used to find any whitespace to split on + Parser._reTagName = /^\s*(\/?)\s*([^\s\/]+)/; //Used to find the tag name for an element + + //Regular expressions used for parsing (stateful) + Parser._reAttrib = //Find attributes in a tag + /([^=<>\"\'\s]+)\s*=\s*"([^"]*)"|([^=<>\"\'\s]+)\s*=\s*'([^']*)'|([^=<>\"\'\s]+)\s*=\s*([^'"\s]+)|([^=<>\"\'\s\/]+)/g; + Parser._reTags = /[\<\>]/g; //Find tag markers + + //**Public**// + //Methods// + //Parses a complete HTML and pushes it to the handler + Parser.prototype.parseComplete = function Parser$parseComplete (data) { + this.reset(); + this.parseChunk(data); + this.done(); + } + + //Parses a piece of an HTML document + Parser.prototype.parseChunk = function Parser$parseChunk (data) { + if (this._done) + this.handleError(new Error("Attempted to parse chunk after parsing already done")); + this._buffer += data; //FIXME: this can be a bottleneck + this.parseTags(); + } + + //Tells the parser that the HTML being parsed is complete + Parser.prototype.done = function Parser$done () { + if (this._done) + return; + this._done = true; + + //Push any unparsed text into a final element in the element list + if (this._buffer.length) { + var rawData = this._buffer; + this._buffer = ""; + var element = { + raw: rawData + , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(Parser._reTrim, "") + , type: this._parseState + }; + if (this._parseState == ElementType.Tag || this._parseState == ElementType.Script || this._parseState == ElementType.Style) + element.name = this.parseTagName(element.data); + this.parseAttribs(element); + this._elements.push(element); + } + + this.writeHandler(); + this._handler.done(); + } + + //Resets the parser to a blank state, ready to parse a new HTML document + Parser.prototype.reset = function Parser$reset () { + this._buffer = ""; + this._done = false; + this._elements = []; + this._elementsCurrent = 0; + this._current = 0; + this._next = 0; + this._location = { + row: 0 + , col: 0 + , charOffset: 0 + , inBuffer: 0 + }; + this._parseState = ElementType.Text; + this._prevTagSep = ''; + this._tagStack = []; + this._handler.reset(); + } + + //**Private**// + //Properties// + Parser.prototype._options = null; //Parser options for how to behave + Parser.prototype._handler = null; //Handler for parsed elements + Parser.prototype._buffer = null; //Buffer of unparsed data + Parser.prototype._done = false; //Flag indicating whether parsing is done + Parser.prototype._elements = null; //Array of parsed elements + Parser.prototype._elementsCurrent = 0; //Pointer to last element in _elements that has been processed + Parser.prototype._current = 0; //Position in data that has already been parsed + Parser.prototype._next = 0; //Position in data of the next tag marker (<>) + Parser.prototype._location = null; //Position tracking for elements in a stream + Parser.prototype._parseState = ElementType.Text; //Current type of element being parsed + Parser.prototype._prevTagSep = ''; //Previous tag marker found + //Stack of element types previously encountered; keeps track of when + //parsing occurs inside a script/comment/style tag + Parser.prototype._tagStack = null; + + //Methods// + //Takes an array of elements and parses any found attributes + Parser.prototype.parseTagAttribs = function Parser$parseTagAttribs (elements) { + var idxEnd = elements.length; + var idx = 0; + + while (idx < idxEnd) { + var element = elements[idx++]; + if (element.type == ElementType.Tag || element.type == ElementType.Script || element.type == ElementType.style) + this.parseAttribs(element); + } + + return(elements); + } + + //Takes an element and adds an "attribs" property for any element attributes found + Parser.prototype.parseAttribs = function Parser$parseAttribs (element) { + //Only parse attributes for tags + if (element.type != ElementType.Script && element.type != ElementType.Style && element.type != ElementType.Tag) + return; + + var tagName = element.data.split(Parser._reWhitespace, 1)[0]; + var attribRaw = element.data.substring(tagName.length); + if (attribRaw.length < 1) + return; + + var match; + Parser._reAttrib.lastIndex = 0; + while (match = Parser._reAttrib.exec(attribRaw)) { + if (element.attribs == undefined) + element.attribs = {}; + + if (typeof match[1] == "string" && match[1].length) { + element.attribs[match[1]] = match[2]; + } else if (typeof match[3] == "string" && match[3].length) { + element.attribs[match[3].toString()] = match[4].toString(); + } else if (typeof match[5] == "string" && match[5].length) { + element.attribs[match[5]] = match[6]; + } else if (typeof match[7] == "string" && match[7].length) { + element.attribs[match[7]] = match[7]; + } + } + } + + //Extracts the base tag name from the data value of an element + Parser.prototype.parseTagName = function Parser$parseTagName (data) { + if (data == null || data == "") + return(""); + var match = Parser._reTagName.exec(data); + if (!match) + return(""); + return((match[1] ? "/" : "") + match[2]); + } + + //Parses through HTML text and returns an array of found elements + //I admit, this function is rather large but splitting up had an noticeable impact on speed + Parser.prototype.parseTags = function Parser$parseTags () { + var bufferEnd = this._buffer.length - 1; + while (Parser._reTags.test(this._buffer)) { + this._next = Parser._reTags.lastIndex - 1; + var tagSep = this._buffer.charAt(this._next); //The currently found tag marker + var rawData = this._buffer.substring(this._current, this._next); //The next chunk of data to parse + + //A new element to eventually be appended to the element list + var element = { + raw: rawData + , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(Parser._reTrim, "") + , type: this._parseState + }; + + var elementName = this.parseTagName(element.data); + + //This section inspects the current tag stack and modifies the current + //element if we're actually parsing a special area (script/comment/style tag) + if (this._tagStack.length) { //We're parsing inside a script/comment/style tag + if (this._tagStack[this._tagStack.length - 1] == ElementType.Script) { //We're currently in a script tag + if (elementName == "/script") //Actually, we're no longer in a script tag, so pop it off the stack + this._tagStack.pop(); + else { //Not a closing script tag + if (element.raw.indexOf("!--") != 0) { //Make sure we're not in a comment + //All data from here to script close is now a text element + element.type = ElementType.Text; + //If the previous element is text, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + } + } + } + } + else if (this._tagStack[this._tagStack.length - 1] == ElementType.Style) { //We're currently in a style tag + if (elementName == "/style") //Actually, we're no longer in a style tag, so pop it off the stack + this._tagStack.pop(); + else { + if (element.raw.indexOf("!--") != 0) { //Make sure we're not in a comment + //All data from here to style close is now a text element + element.type = ElementType.Text; + //If the previous element is text, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) { + var prevElement = this._elements[this._elements.length - 1]; + if (element.raw != "") { + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + } else { //Element is empty, so just append the last tag marker found + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep; + } + } else { //The previous element was not text + if (element.raw != "") { + element.raw = element.data = element.raw; + } + } + } + } + } + else if (this._tagStack[this._tagStack.length - 1] == ElementType.Comment) { //We're currently in a comment tag + var rawLen = element.raw.length; + if (element.raw.charAt(rawLen - 2) == "-" && element.raw.charAt(rawLen - 1) == "-" && tagSep == ">") { + //Actually, we're no longer in a style tag, so pop it off the stack + this._tagStack.pop(); + //If the previous element is a comment, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = (prevElement.raw + element.raw).replace(Parser._reTrimComment, ""); + element.raw = element.data = ""; //This causes the current element to not be added to the element list + element.type = ElementType.Text; + } + else //Previous element not a comment + element.type = ElementType.Comment; //Change the current element's type to a comment + } + else { //Still in a comment tag + element.type = ElementType.Comment; + //If the previous element is a comment, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = prevElement.raw + element.raw + tagSep; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + element.type = ElementType.Text; + } + else + element.raw = element.data = element.raw + tagSep; + } + } + } + + //Processing of non-special tags + if (element.type == ElementType.Tag) { + element.name = elementName; + + if (element.raw.indexOf("!--") == 0) { //This tag is really comment + element.type = ElementType.Comment; + delete element["name"]; + var rawLen = element.raw.length; + //Check if the comment is terminated in the current element + if (element.raw.charAt(rawLen - 1) == "-" && element.raw.charAt(rawLen - 2) == "-" && tagSep == ">") + element.raw = element.data = element.raw.replace(Parser._reTrimComment, ""); + else { //It's not so push the comment onto the tag stack + element.raw += tagSep; + this._tagStack.push(ElementType.Comment); + } + } + else if (element.raw.indexOf("!") == 0 || element.raw.indexOf("?") == 0) { + element.type = ElementType.Directive; + //TODO: what about CDATA? + } + else if (element.name == "script") { + element.type = ElementType.Script; + //Special tag, push onto the tag stack if not terminated + if (element.data.charAt(element.data.length - 1) != "/") + this._tagStack.push(ElementType.Script); + } + else if (element.name == "/script") + element.type = ElementType.Script; + else if (element.name == "style") { + element.type = ElementType.Style; + //Special tag, push onto the tag stack if not terminated + if (element.data.charAt(element.data.length - 1) != "/") + this._tagStack.push(ElementType.Style); + } + else if (element.name == "/style") + element.type = ElementType.Style; + if (element.name && element.name.charAt(0) == "/") + element.data = element.name; + } + + //Add all tags and non-empty text elements to the element list + if (element.raw != "" || element.type != ElementType.Text) { + if (this._options.includeLocation && !element.location) { + element.location = this.getLocation(element.type == ElementType.Tag); + } + this.parseAttribs(element); + this._elements.push(element); + //If tag self-terminates, add an explicit, separate closing tag + if ( + element.type != ElementType.Text + && + element.type != ElementType.Comment + && + element.type != ElementType.Directive + && + element.data.charAt(element.data.length - 1) == "/" + ) + this._elements.push({ + raw: "/" + element.name + , data: "/" + element.name + , name: "/" + element.name + , type: element.type + }); + } + this._parseState = (tagSep == "<") ? ElementType.Tag : ElementType.Text; + this._current = this._next + 1; + this._prevTagSep = tagSep; + } + + if (this._options.includeLocation) { + this.getLocation(); + this._location.row += this._location.inBuffer; + this._location.inBuffer = 0; + this._location.charOffset = 0; + } + this._buffer = (this._current <= bufferEnd) ? this._buffer.substring(this._current) : ""; + this._current = 0; + + this.writeHandler(); + } + + Parser.prototype.getLocation = function Parser$getLocation (startTag) { + var c, + l = this._location, + end = this._current - (startTag ? 1 : 0), + chunk = startTag && l.charOffset == 0 && this._current == 0; + + for (; l.charOffset < end; l.charOffset++) { + c = this._buffer.charAt(l.charOffset); + if (c == '\n') { + l.inBuffer++; + l.col = 0; + } else if (c != '\r') { + l.col++; + } + } + return { + line: l.row + l.inBuffer + 1 + , col: l.col + (chunk ? 0: 1) + }; + } + + //Checks the handler to make it is an object with the right "interface" + Parser.prototype.validateHandler = function Parser$validateHandler (handler) { + if ((typeof handler) != "object") + throw new Error("Handler is not an object"); + if ((typeof handler.reset) != "function") + throw new Error("Handler method 'reset' is invalid"); + if ((typeof handler.done) != "function") + throw new Error("Handler method 'done' is invalid"); + if ((typeof handler.writeTag) != "function") + throw new Error("Handler method 'writeTag' is invalid"); + if ((typeof handler.writeText) != "function") + throw new Error("Handler method 'writeText' is invalid"); + if ((typeof handler.writeComment) != "function") + throw new Error("Handler method 'writeComment' is invalid"); + if ((typeof handler.writeDirective) != "function") + throw new Error("Handler method 'writeDirective' is invalid"); + } + + //Writes parsed elements out to the handler + Parser.prototype.writeHandler = function Parser$writeHandler (forceFlush) { + forceFlush = !!forceFlush; + if (this._tagStack.length && !forceFlush) + return; + while (this._elements.length) { + var element = this._elements.shift(); + switch (element.type) { + case ElementType.Comment: + this._handler.writeComment(element); + break; + case ElementType.Directive: + this._handler.writeDirective(element); + break; + case ElementType.Text: + this._handler.writeText(element); + break; + default: + this._handler.writeTag(element); + break; + } + } + } + + Parser.prototype.handleError = function Parser$handleError (error) { + if ((typeof this._handler.error) == "function") + this._handler.error(error); + else + throw error; + } + +//TODO: make this a trully streamable handler +function RssHandler (callback) { + RssHandler.super_.call(this, callback, { ignoreWhitespace: true, verbose: false, enforceEmptyTags: false }); +} +inherits(RssHandler, DefaultHandler); + + RssHandler.prototype.done = function RssHandler$done () { + var feed = { }; + var feedRoot; + + var found = DomUtils.getElementsByTagName(function (value) { return(value == "rss" || value == "feed"); }, this.dom, false); + if (found.length) { + feedRoot = found[0]; + } + if (feedRoot) { + if (feedRoot.name == "rss") { + feed.type = "rss"; + feedRoot = feedRoot.children[0]; // + feed.id = ""; + try { + feed.title = DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.link = DomUtils.getElementsByTagName("link", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.description = DomUtils.getElementsByTagName("description", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.updated = new Date(DomUtils.getElementsByTagName("lastBuildDate", feedRoot.children, false)[0].children[0].data); + } catch (ex) { } + try { + feed.author = DomUtils.getElementsByTagName("managingEditor", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + feed.items = []; + DomUtils.getElementsByTagName("item", feedRoot.children).forEach(function (item, index, list) { + var entry = {}; + try { + entry.id = DomUtils.getElementsByTagName("guid", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.title = DomUtils.getElementsByTagName("title", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.link = DomUtils.getElementsByTagName("link", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.description = DomUtils.getElementsByTagName("description", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.pubDate = new Date(DomUtils.getElementsByTagName("pubDate", item.children, false)[0].children[0].data); + } catch (ex) { } + feed.items.push(entry); + }); + } else { + feed.type = "atom"; + try { + feed.id = DomUtils.getElementsByTagName("id", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.title = DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.link = DomUtils.getElementsByTagName("link", feedRoot.children, false)[0].attribs.href; + } catch (ex) { } + try { + feed.description = DomUtils.getElementsByTagName("subtitle", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.updated = new Date(DomUtils.getElementsByTagName("updated", feedRoot.children, false)[0].children[0].data); + } catch (ex) { } + try { + feed.author = DomUtils.getElementsByTagName("email", feedRoot.children, true)[0].children[0].data; + } catch (ex) { } + feed.items = []; + DomUtils.getElementsByTagName("entry", feedRoot.children).forEach(function (item, index, list) { + var entry = {}; + try { + entry.id = DomUtils.getElementsByTagName("id", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.title = DomUtils.getElementsByTagName("title", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.link = DomUtils.getElementsByTagName("link", item.children, false)[0].attribs.href; + } catch (ex) { } + try { + entry.description = DomUtils.getElementsByTagName("summary", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.pubDate = new Date(DomUtils.getElementsByTagName("updated", item.children, false)[0].children[0].data); + } catch (ex) { } + feed.items.push(entry); + }); + } + + this.dom = feed; + } + RssHandler.super_.prototype.done.call(this); + } + +/////////////////////////////////////////////////// + +function DefaultHandler (callback, options) { + this.reset(); + this._options = options ? options : { }; + if (this._options.ignoreWhitespace == undefined) + this._options.ignoreWhitespace = false; //Keep whitespace-only text nodes + if (this._options.verbose == undefined) + this._options.verbose = true; //Keep data property for tags and raw property for all + if (this._options.enforceEmptyTags == undefined) + this._options.enforceEmptyTags = true; //Don't allow children for HTML tags defined as empty in spec + if ((typeof callback) == "function") + this._callback = callback; +} + + //**"Static"**// + //HTML Tags that shouldn't contain child nodes + DefaultHandler._emptyTags = { + area: 1 + , base: 1 + , basefont: 1 + , br: 1 + , col: 1 + , frame: 1 + , hr: 1 + , img: 1 + , input: 1 + , isindex: 1 + , link: 1 + , meta: 1 + , param: 1 + , embed: 1 + } + //Regex to detect whitespace only text nodes + DefaultHandler.reWhitespace = /^\s*$/; + + //**Public**// + //Properties// + DefaultHandler.prototype.dom = null; //The hierarchical object containing the parsed HTML + //Methods// + //Resets the handler back to starting state + DefaultHandler.prototype.reset = function DefaultHandler$reset() { + this.dom = []; + this._done = false; + this._tagStack = []; + this._tagStack.last = function DefaultHandler$_tagStack$last () { + return(this.length ? this[this.length - 1] : null); + } + } + //Signals the handler that parsing is done + DefaultHandler.prototype.done = function DefaultHandler$done () { + this._done = true; + this.handleCallback(null); + } + DefaultHandler.prototype.writeTag = function DefaultHandler$writeTag (element) { + this.handleElement(element); + } + DefaultHandler.prototype.writeText = function DefaultHandler$writeText (element) { + if (this._options.ignoreWhitespace) + if (DefaultHandler.reWhitespace.test(element.data)) + return; + this.handleElement(element); + } + DefaultHandler.prototype.writeComment = function DefaultHandler$writeComment (element) { + this.handleElement(element); + } + DefaultHandler.prototype.writeDirective = function DefaultHandler$writeDirective (element) { + this.handleElement(element); + } + DefaultHandler.prototype.error = function DefaultHandler$error (error) { + this.handleCallback(error); + } + + //**Private**// + //Properties// + DefaultHandler.prototype._options = null; //Handler options for how to behave + DefaultHandler.prototype._callback = null; //Callback to respond to when parsing done + DefaultHandler.prototype._done = false; //Flag indicating whether handler has been notified of parsing completed + DefaultHandler.prototype._tagStack = null; //List of parents to the currently element being processed + //Methods// + DefaultHandler.prototype.handleCallback = function DefaultHandler$handleCallback (error) { + if ((typeof this._callback) != "function") + if (error) + throw error; + else + return; + this._callback(error, this.dom); + } + + DefaultHandler.prototype.isEmptyTag = function(element) { + var name = element.name.toLowerCase(); + if (name.charAt(0) == '/') { + name = name.substring(1); + } + return this._options.enforceEmptyTags && !!DefaultHandler._emptyTags[name]; + }; + + DefaultHandler.prototype.handleElement = function DefaultHandler$handleElement (element) { + if (this._done) + this.handleCallback(new Error("Writing to the handler after done() called is not allowed without a reset()")); + if (!this._options.verbose) { +// element.raw = null; //FIXME: Not clean + //FIXME: Serious performance problem using delete + delete element.raw; + if (element.type == "tag" || element.type == "script" || element.type == "style") + delete element.data; + } + if (!this._tagStack.last()) { //There are no parent elements + //If the element can be a container, add it to the tag stack and the top level list + if (element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive) { + if (element.name.charAt(0) != "/") { //Ignore closing tags that obviously don't have an opening tag + this.dom.push(element); + if (!this.isEmptyTag(element)) { //Don't add tags to the tag stack that can't have children + this._tagStack.push(element); + } + } + } + else //Otherwise just add to the top level list + this.dom.push(element); + } + else { //There are parent elements + //If the element can be a container, add it as a child of the element + //on top of the tag stack and then add it to the tag stack + if (element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive) { + if (element.name.charAt(0) == "/") { + //This is a closing tag, scan the tagStack to find the matching opening tag + //and pop the stack up to the opening tag's parent + var baseName = element.name.substring(1); + if (!this.isEmptyTag(element)) { + var pos = this._tagStack.length - 1; + while (pos > -1 && this._tagStack[pos--].name != baseName) { } + if (pos > -1 || this._tagStack[0].name == baseName) + while (pos < this._tagStack.length - 1) + this._tagStack.pop(); + } + } + else { //This is not a closing tag + if (!this._tagStack.last().children) + this._tagStack.last().children = []; + this._tagStack.last().children.push(element); + if (!this.isEmptyTag(element)) //Don't add tags to the tag stack that can't have children + this._tagStack.push(element); + } + } + else { //This is not a container element + if (!this._tagStack.last().children) + this._tagStack.last().children = []; + this._tagStack.last().children.push(element); + } + } + } + + var DomUtils = { + testElement: function DomUtils$testElement (options, element) { + if (!element) { + return false; + } + + for (var key in options) { + if (key == "tag_name") { + if (element.type != "tag" && element.type != "script" && element.type != "style") { + return false; + } + if (!options["tag_name"](element.name)) { + return false; + } + } else if (key == "tag_type") { + if (!options["tag_type"](element.type)) { + return false; + } + } else if (key == "tag_contains") { + if (element.type != "text" && element.type != "comment" && element.type != "directive") { + return false; + } + if (!options["tag_contains"](element.data)) { + return false; + } + } else { + if (!element.attribs || !options[key](element.attribs[key])) { + return false; + } + } + } + + return true; + } + + , getElements: function DomUtils$getElements (options, currentElement, recurse, limit) { + recurse = (recurse === undefined || recurse === null) || !!recurse; + limit = isNaN(parseInt(limit)) ? -1 : parseInt(limit); + + if (!currentElement) { + return([]); + } + + var found = []; + var elementList; + + function getTest (checkVal) { + return(function (value) { return(value == checkVal); }); + } + for (var key in options) { + if ((typeof options[key]) != "function") { + options[key] = getTest(options[key]); + } + } + + if (DomUtils.testElement(options, currentElement)) { + found.push(currentElement); + } + + if (limit >= 0 && found.length >= limit) { + return(found); + } + + if (recurse && currentElement.children) { + elementList = currentElement.children; + } else if (currentElement instanceof Array) { + elementList = currentElement; + } else { + return(found); + } + + for (var i = 0; i < elementList.length; i++) { + found = found.concat(DomUtils.getElements(options, elementList[i], recurse, limit)); + if (limit >= 0 && found.length >= limit) { + break; + } + } + + return(found); + } + + , getElementById: function DomUtils$getElementById (id, currentElement, recurse) { + var result = DomUtils.getElements({ id: id }, currentElement, recurse, 1); + return(result.length ? result[0] : null); + } + + , getElementsByTagName: function DomUtils$getElementsByTagName (name, currentElement, recurse, limit) { + return(DomUtils.getElements({ tag_name: name }, currentElement, recurse, limit)); + } + + , getElementsByTagType: function DomUtils$getElementsByTagType (type, currentElement, recurse, limit) { + return(DomUtils.getElements({ tag_type: type }, currentElement, recurse, limit)); + } + } + + function inherits (ctor, superCtor) { + var tempCtor = function(){}; + tempCtor.prototype = superCtor.prototype; + ctor.super_ = superCtor; + ctor.prototype = new tempCtor(); + ctor.prototype.constructor = ctor; + } + +exports.Parser = Parser; + +exports.DefaultHandler = DefaultHandler; + +exports.RssHandler = RssHandler; + +exports.ElementType = ElementType; + +exports.DomUtils = DomUtils; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/lib/htmlparser.min.js b/rails/node_modules/jquery/node_modules/htmlparser/lib/htmlparser.min.js new file mode 100644 index 0000000..2f029f7 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/lib/htmlparser.min.js @@ -0,0 +1,22 @@ +/*********************************************** +Copyright 2010, Chris Winberry . All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +***********************************************/ +/* v1.7.2 */ +(function(){function e(a,c){this._options=c?c:{};if(this._options.includeLocation==undefined)this._options.includeLocation=false;this.validateHandler(a);this._handler=a;this.reset()}function n(a){n.super_.call(this,a,{ignoreWhitespace:true,verbose:false,enforceEmptyTags:false})}function i(a,c){this.reset();this._options=c?c:{};if(this._options.ignoreWhitespace==undefined)this._options.ignoreWhitespace=false;if(this._options.verbose==undefined)this._options.verbose=true;if(this._options.enforceEmptyTags== undefined)this._options.enforceEmptyTags=true;if(typeof a=="function")this._callback=a}if(!(typeof require=="function"&&typeof exports=="object"&&typeof module=="object"&&typeof __filename=="string"&&typeof __dirname=="string")){if(this.Tautologistics){if(this.Tautologistics.NodeHtmlParser)return}else this.Tautologistics={};this.Tautologistics.NodeHtmlParser={};exports=this.Tautologistics.NodeHtmlParser}var d={Text:"text",Directive:"directive",Comment:"comment",Script:"script",Style:"style",Tag:"tag"}; e._reTrim=/(^\s+|\s+$)/g;e._reTrimComment=/(^\!--|--$)/g;e._reWhitespace=/\s/g;e._reTagName=/^\s*(\/?)\s*([^\s\/]+)/;e._reAttrib=/([^=<>\"\'\s]+)\s*=\s*"([^"]*)"|([^=<>\"\'\s]+)\s*=\s*'([^']*)'|([^=<>\"\'\s]+)\s*=\s*([^'"\s]+)|([^=<>\"\'\s\/]+)/g;e._reTags=/[\<\>]/g;e.prototype.parseComplete=function(a){this.reset();this.parseChunk(a);this.done()};e.prototype.parseChunk=function(a){this._done&&this.handleError(Error("Attempted to parse chunk after parsing already done"));this._buffer+=a;this.parseTags()}; e.prototype.done=function(){if(!this._done){this._done=true;if(this._buffer.length){var a=this._buffer;this._buffer="";a={raw:a,data:this._parseState==d.Text?a:a.replace(e._reTrim,""),type:this._parseState};if(this._parseState==d.Tag||this._parseState==d.Script||this._parseState==d.Style)a.name=this.parseTagName(a.data);this.parseAttribs(a);this._elements.push(a)}this.writeHandler();this._handler.done()}};e.prototype.reset=function(){this._buffer="";this._done=false;this._elements=[];this._next=this._current= this._elementsCurrent=0;this._location={row:0,col:0,charOffset:0,inBuffer:0};this._parseState=d.Text;this._prevTagSep="";this._tagStack=[];this._handler.reset()};e.prototype._options=null;e.prototype._handler=null;e.prototype._buffer=null;e.prototype._done=false;e.prototype._elements=null;e.prototype._elementsCurrent=0;e.prototype._current=0;e.prototype._next=0;e.prototype._location=null;e.prototype._parseState=d.Text;e.prototype._prevTagSep="";e.prototype._tagStack=null;e.prototype.parseTagAttribs= function(a){for(var c=a.length,b=0;b"){this._tagStack.pop(); if(this._elements.length&&this._elements[this._elements.length-1].type==d.Comment){g=this._elements[this._elements.length-1];g.raw=g.data=(g.raw+b.raw).replace(e._reTrimComment,"");b.raw=b.data="";b.type=d.Text}else b.type=d.Comment}else{b.type=d.Comment;if(this._elements.length&&this._elements[this._elements.length-1].type==d.Comment){g=this._elements[this._elements.length-1];g.raw=g.data=g.raw+b.raw+c;b.raw=b.data="";b.type=d.Text}else b.raw=b.data=b.raw+c}}if(b.type==d.Tag){b.name=h;if(b.raw.indexOf("!--")== 0){b.type=d.Comment;delete b.name;g=b.raw.length;if(b.raw.charAt(g-1)=="-"&&b.raw.charAt(g-2)=="-"&&c==">")b.raw=b.data=b.raw.replace(e._reTrimComment,"");else{b.raw+=c;this._tagStack.push(d.Comment)}}else if(b.raw.indexOf("!")==0||b.raw.indexOf("?")==0)b.type=d.Directive;else if(b.name=="script"){b.type=d.Script;b.data.charAt(b.data.length-1)!="/"&&this._tagStack.push(d.Script)}else if(b.name=="/script")b.type=d.Script;else if(b.name=="style"){b.type=d.Style;b.data.charAt(b.data.length-1)!="/"&& this._tagStack.push(d.Style)}else if(b.name=="/style")b.type=d.Style;if(b.name&&b.name.charAt(0)=="/")b.data=b.name}if(b.raw!=""||b.type!=d.Text){if(this._options.includeLocation&&!b.location)b.location=this.getLocation(b.type==d.Tag);this.parseAttribs(b);this._elements.push(b);b.type!=d.Text&&b.type!=d.Comment&&b.type!=d.Directive&&b.data.charAt(b.data.length-1)=="/"&&this._elements.push({raw:"/"+b.name,data:"/"+b.name,name:"/"+b.name,type:b.type})}this._parseState=c=="<"?d.Tag:d.Text;this._current= this._next+1;this._prevTagSep=c}if(this._options.includeLocation){this.getLocation();this._location.row+=this._location.inBuffer;this._location.inBuffer=0;this._location.charOffset=0}this._buffer=this._current<=a?this._buffer.substring(this._current):"";this._current=0;this.writeHandler()};e.prototype.getLocation=function(a){for(var c=this._location,b=this._current-(a?1:0),h=a&&c.charOffset==0&&this._current==0;c.charOffset-1&&this._tagStack[a--].name!=c;);if(a>-1||this._tagStack[0].name==c)for(;a=0&&l.length>=h)return l;if(b&&c.children)c=c.children;else if(c instanceof Array)c=c;else return l; for(m=0;m=0&&l.length>=h)break}return l},getElementById:function(a,c,b){a=f.getElements({id:a},c,b,1);return a.length?a[0]:null},getElementsByTagName:function(a,c,b,h){return f.getElements({tag_name:a},c,b,h)},getElementsByTagType:function(a,c,b,h){return f.getElements({tag_type:a},c,b,h)}};exports.Parser=e;exports.DefaultHandler=i;exports.RssHandler=n;exports.ElementType=d;exports.DomUtils=f})(); \ No newline at end of file diff --git a/rails/node_modules/jquery/node_modules/htmlparser/lib/node-htmlparser.js b/rails/node_modules/jquery/node_modules/htmlparser/lib/node-htmlparser.js new file mode 100644 index 0000000..1fc03ea --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/lib/node-htmlparser.js @@ -0,0 +1,6 @@ +var htmlparser = require("./htmlparser"); +exports.Parser = htmlparser.Parser; +exports.DefaultHandler = htmlparser.DefaultHandler; +exports.RssHandler = htmlparser.RssHandler; +exports.ElementType = htmlparser.ElementType; +exports.DomUtils = htmlparser.DomUtils; diff --git a/rails/node_modules/jquery/node_modules/htmlparser/lib/node-htmlparser.min.js b/rails/node_modules/jquery/node_modules/htmlparser/lib/node-htmlparser.min.js new file mode 100644 index 0000000..27d5eea --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/lib/node-htmlparser.min.js @@ -0,0 +1,6 @@ +var htmlparser = require("./htmlparser.min"); +exports.Parser = htmlparser.Parser; +exports.DefaultHandler = htmlparser.DefaultHandler; +exports.RssHandler = htmlparser.RssHandler; +exports.ElementType = htmlparser.ElementType; +exports.DomUtils = htmlparser.DomUtils; diff --git a/rails/node_modules/jquery/node_modules/htmlparser/libxmljs.node b/rails/node_modules/jquery/node_modules/htmlparser/libxmljs.node new file mode 100755 index 0000000..07e08c8 Binary files /dev/null and b/rails/node_modules/jquery/node_modules/htmlparser/libxmljs.node differ diff --git a/rails/node_modules/jquery/node_modules/htmlparser/newparser.js b/rails/node_modules/jquery/node_modules/htmlparser/newparser.js new file mode 100644 index 0000000..2487f23 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/newparser.js @@ -0,0 +1,54 @@ +//node --prof --prof_auto profile.js +//deps/v8/tools/mac-tick-processor v8.log +var sys = require("sys"); +var fs = require("fs"); + +var testHtml = "./testdata/api.html"; //Test HTML file to load +var testIterations = 100; //Number of test loops to run + +var html = fs.readFileSync(testHtml).toString(); + +function getMillisecs () { + return((new Date()).getTime()); +} + +function timeExecutions (loops, func) { + var start = getMillisecs(); + + while (loops--) + func(); + + return(getMillisecs() - start); +} + +sys.puts("HTML Length: " + html.length); + +sys.puts("Test 1: " + timeExecutions(testIterations, function () { +// function parseText (data) { +// // +// } +// function parseTag (data) { +// // +// } +// function parseAttrib (data) { +// // +// } +// function parseComment (data) { +// // +// } + var data = html.split(""); + data.meta = { + length: data.length + , pos: 0 + } + while (data.meta.length > data.meta.pos && data[data.meta.pos++] !== ""); +// sys.puts("Found: " + [data.meta.pos, data[data.meta.pos]]); +}) + "ms"); + +sys.puts("Test 2: " + timeExecutions(testIterations, function () { + var data = html; + var dataLen = data.length; + var pos = 0; + while (dataLen > pos && data.charAt(pos++) !== ""); +// sys.puts("Found: " + [pos, data.charAt(pos)]); +}) + "ms"); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/node-htmlparser.old.js b/rails/node_modules/jquery/node_modules/htmlparser/node-htmlparser.old.js new file mode 100644 index 0000000..cfc1664 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/node-htmlparser.old.js @@ -0,0 +1,754 @@ +/*********************************************** +Copyright 2010, Chris Winberry . All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +***********************************************/ +/* v1.5.0 */ + +(function () { + +function runningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!runningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + else if (this.Tautologistics.NodeHtmlParser) + return; //NodeHtmlParser already defined! + this.Tautologistics.NodeHtmlParser = {}; + exports = this.Tautologistics.NodeHtmlParser; +} + +//Types of elements found in the DOM +var ElementType = { + Text: "text" //Plain text + , Directive: "directive" //Special tag + , Comment: "comment" //Special tag + , Script: "script" //Special tag + , Style: "style" //Special tag + , Tag: "tag" //Any tag that isn't special +} + +function Parser (handler) { + this.validateHandler(handler); + this._handler = handler; + this.reset(); +} + + //**"Static"**// + //Regular expressions used for cleaning up and parsing (stateless) + Parser._reTrim = /(^\s+|\s+$)/g; //Trim leading/trailing whitespace + Parser._reTrimComment = /(^\!--|--$)/g; //Remove comment tag markup from comment contents + Parser._reWhitespace = /\s/g; //Used to find any whitespace to split on + Parser._reTagName = /^\s*(\/?)\s*([^\s\/]+)/; //Used to find the tag name for an element + + //Regular expressions used for parsing (stateful) + Parser._reAttrib = //Find attributes in a tag + /([^=<>\"\'\s]+)\s*=\s*"([^"]*)"|([^=<>\"\'\s]+)\s*=\s*'([^']*)'|([^=<>\"\'\s]+)\s*=\s*([^'"\s]+)|([^=<>\"\'\s\/]+)/g; + Parser._reTags = /[\<\>]/g; //Find tag markers + + //**Public**// + //Methods// + //Parses a complete HTML and pushes it to the handler + Parser.prototype.parseComplete = function Parser$parseComplete (data) { + this.reset(); + this.parseChunk(data); + this.done(); + } + + //Parses a piece of an HTML document + Parser.prototype.parseChunk = function Parser$parseChunk (data) { + if (this._done) + this.handleError(new Error("Attempted to parse chunk after parsing already done")); + this._buffer += data; //FIXME: this can be a bottleneck + this.parseTags(); + } + + //Tells the parser that the HTML being parsed is complete + Parser.prototype.done = function Parser$done () { + if (this._done) + return; + this._done = true; + + //Push any unparsed text into a final element in the element list + if (this._buffer.length) { + var rawData = this._buffer; + this._buffer = ""; + var element = { + raw: rawData + , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(Parser._reTrim, "") + , type: this._parseState + }; + if (this._parseState == ElementType.Tag || this._parseState == ElementType.Script || this._parseState == ElementType.Style) + element.name = this.parseTagName(element.data); + this.parseAttribs(element); + this._elements.push(element); + } + + this.writeHandler(); + this._handler.done(); + } + + //Resets the parser to a blank state, ready to parse a new HTML document + Parser.prototype.reset = function Parser$reset () { + this._buffer = ""; + this._done = false; + this._elements = []; + this._elementsCurrent = 0; + this._current = 0; + this._next = 0; + this._parseState = ElementType.Text; + this._prevTagSep = ''; + this._tagStack = []; + this._handler.reset(); + } + + //**Private**// + //Properties// + Parser.prototype._handler = null; //Handler for parsed elements + Parser.prototype._buffer = null; //Buffer of unparsed data + Parser.prototype._done = false; //Flag indicating whether parsing is done + Parser.prototype._elements = null; //Array of parsed elements + Parser.prototype._elementsCurrent = 0; //Pointer to last element in _elements that has been processed + Parser.prototype._current = 0; //Position in data that has already been parsed + Parser.prototype._next = 0; //Position in data of the next tag marker (<>) + Parser.prototype._parseState = ElementType.Text; //Current type of element being parsed + Parser.prototype._prevTagSep = ''; //Previous tag marker found + //Stack of element types previously encountered; keeps track of when + //parsing occurs inside a script/comment/style tag + Parser.prototype._tagStack = null; + + //Methods// + //Takes an array of elements and parses any found attributes + Parser.prototype.parseTagAttribs = function Parser$parseTagAttribs (elements) { + var idxEnd = elements.length; + var idx = 0; + + while (idx < idxEnd) { + var element = elements[idx++]; + if (element.type == ElementType.Tag || element.type == ElementType.Script || element.type == ElementType.style) + this.parseAttribs(element); + } + + return(elements); + } + + //Takes an element and adds an "attribs" property for any element attributes found + Parser.prototype.parseAttribs = function Parser$parseAttribs (element) { + //Only parse attributes for tags + if (element.type != ElementType.Script && element.type != ElementType.Style && element.type != ElementType.Tag) + return; + + var tagName = element.data.split(Parser._reWhitespace, 1)[0]; + var attribRaw = element.data.substring(tagName.length); + if (attribRaw.length < 1) + return; + + var match; + Parser._reAttrib.lastIndex = 0; + while (match = Parser._reAttrib.exec(attribRaw)) { + if (element.attribs == undefined) + element.attribs = {}; + + if (typeof match[1] == "string" && match[1].length) { + element.attribs[match[1]] = match[2]; + } else if (typeof match[3] == "string" && match[3].length) { + element.attribs[match[3].toString()] = match[4].toString(); + } else if (typeof match[5] == "string" && match[5].length) { + element.attribs[match[5]] = match[6]; + } else if (typeof match[7] == "string" && match[7].length) { + element.attribs[match[7]] = match[7]; + } + } + } + + //Extracts the base tag name from the data value of an element + Parser.prototype.parseTagName = function Parser$parseTagName (data) { + if (data == null || data == "") + return(""); + var match = Parser._reTagName.exec(data); + if (!match) + return(""); + return((match[1] ? "/" : "") + match[2]); + } + + //Parses through HTML text and returns an array of found elements + //I admit, this function is rather large but splitting up had an noticeable impact on speed + Parser.prototype.parseTags = function Parser$parseTags () { + var bufferEnd = this._buffer.length - 1; + while (Parser._reTags.test(this._buffer)) { + this._next = Parser._reTags.lastIndex - 1; + var tagSep = this._buffer.charAt(this._next); //The currently found tag marker + var rawData = this._buffer.substring(this._current, this._next); //The next chunk of data to parse + + //A new element to eventually be appended to the element list + var element = { + raw: rawData + , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(Parser._reTrim, "") + , type: this._parseState + }; + + var elementName = this.parseTagName(element.data); + + //This section inspects the current tag stack and modifies the current + //element if we're actually parsing a special area (script/comment/style tag) + if (this._tagStack.length) { //We're parsing inside a script/comment/style tag + if (this._tagStack[this._tagStack.length - 1] == ElementType.Script) { //We're currently in a script tag + if (elementName == "/script") //Actually, we're no longer in a script tag, so pop it off the stack + this._tagStack.pop(); + else { //Not a closing script tag + if (element.raw.indexOf("!--") != 0) { //Make sure we're not in a comment + //All data from here to script close is now a text element + element.type = ElementType.Text; + //If the previous element is text, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + } + } + } + } + else if (this._tagStack[this._tagStack.length - 1] == ElementType.Style) { //We're currently in a style tag + if (elementName == "/style") //Actually, we're no longer in a style tag, so pop it off the stack + this._tagStack.pop(); + else { + if (element.raw.indexOf("!--") != 0) { //Make sure we're not in a comment + //All data from here to style close is now a text element + element.type = ElementType.Text; + //If the previous element is text, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) { + if (element.raw != "") { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + } + else //Element is empty, so just append the last tag marker found + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep; + } + else //The previous element was not text + if (element.raw != "") + element.raw = element.data = element.raw; + } + } + } + else if (this._tagStack[this._tagStack.length - 1] == ElementType.Comment) { //We're currently in a comment tag + var rawLen = element.raw.length; + if (element.raw.charAt(rawLen - 2) == "-" && element.raw.charAt(rawLen - 1) == "-" && tagSep == ">") { + //Actually, we're no longer in a style tag, so pop it off the stack + this._tagStack.pop(); + //If the previous element is a comment, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = (prevElement.raw + element.raw).replace(Parser._reTrimComment, ""); + element.raw = element.data = ""; //This causes the current element to not be added to the element list + element.type = ElementType.Text; + } + else //Previous element not a comment + element.type = ElementType.Comment; //Change the current element's type to a comment + } + else { //Still in a comment tag + element.type = ElementType.Comment; + //If the previous element is a comment, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = prevElement.raw + element.raw + tagSep; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + element.type = ElementType.Text; + } + else + element.raw = element.data = element.raw + tagSep; + } + } + } + + //Processing of non-special tags + if (element.type == ElementType.Tag) { + element.name = elementName; + + if (element.raw.indexOf("!--") == 0) { //This tag is really comment + element.type = ElementType.Comment; + delete element["name"]; + var rawLen = element.raw.length; + //Check if the comment is terminated in the current element + if (element.raw.charAt(rawLen - 1) == "-" && element.raw.charAt(rawLen - 2) == "-" && tagSep == ">") + element.raw = element.data = element.raw.replace(Parser._reTrimComment, ""); + else { //It's not so push the comment onto the tag stack + element.raw += tagSep; + this._tagStack.push(ElementType.Comment); + } + } + else if (element.raw.indexOf("!") == 0 || element.raw.indexOf("?") == 0) { + element.type = ElementType.Directive; + //TODO: what about CDATA? + } + else if (element.name == "script") { + element.type = ElementType.Script; + //Special tag, push onto the tag stack if not terminated + if (element.data.charAt(element.data.length - 1) != "/") + this._tagStack.push(ElementType.Script); + } + else if (element.name == "/script") + element.type = ElementType.Script; + else if (element.name == "style") { + element.type = ElementType.Style; + //Special tag, push onto the tag stack if not terminated + if (element.data.charAt(element.data.length - 1) != "/") + this._tagStack.push(ElementType.Style); + } + else if (element.name == "/style") + element.type = ElementType.Style; + if (element.name && element.name.charAt(0) == "/") + element.data = element.name; + } + + //Add all tags and non-empty text elements to the element list + if (element.raw != "" || element.type != ElementType.Text) { + this.parseAttribs(element); + this._elements.push(element); + //If tag self-terminates, add an explicit, separate closing tag + if ( + element.type != ElementType.Text + && + element.type != ElementType.Comment + && + element.type != ElementType.Directive + && + element.data.charAt(element.data.length - 1) == "/" + ) + this._elements.push({ + raw: "/" + element.name + , data: "/" + element.name + , name: "/" + element.name + , type: element.type + }); + } + this._parseState = (tagSep == "<") ? ElementType.Tag : ElementType.Text; + this._current = this._next + 1; + this._prevTagSep = tagSep; + } + + this._buffer = (this._current <= bufferEnd) ? this._buffer.substring(this._current) : ""; + this._current = 0; + + this.writeHandler(); + } + + //Checks the handler to make it is an object with the right "interface" + Parser.prototype.validateHandler = function Parser$validateHandler (handler) { + if ((typeof handler) != "object") + throw new Error("Handler is not an object"); + if ((typeof handler.reset) != "function") + throw new Error("Handler method 'reset' is invalid"); + if ((typeof handler.done) != "function") + throw new Error("Handler method 'done' is invalid"); + if ((typeof handler.writeTag) != "function") + throw new Error("Handler method 'writeTag' is invalid"); + if ((typeof handler.writeText) != "function") + throw new Error("Handler method 'writeText' is invalid"); + if ((typeof handler.writeComment) != "function") + throw new Error("Handler method 'writeComment' is invalid"); + if ((typeof handler.writeDirective) != "function") + throw new Error("Handler method 'writeDirective' is invalid"); + } + + //Writes parsed elements out to the handler + Parser.prototype.writeHandler = function Parser$writeHandler (forceFlush) { + forceFlush = !!forceFlush; + if (this._tagStack.length && !forceFlush) + return; + while (this._elements.length) { + var element = this._elements.shift(); + switch (element.type) { + case ElementType.Comment: + this._handler.writeComment(element); + break; + case ElementType.Directive: + this._handler.writeDirective(element); + break; + case ElementType.Text: + this._handler.writeText(element); + break; + default: + this._handler.writeTag(element); + break; + } + } + } + + Parser.prototype.handleError = function Parser$handleError (error) { + if ((typeof this._handler.error) == "function") + this._handler.error(error); + else + throw error; + } + +//TODO: make this a trully streamable handler +function RssHandler (callback) { + RssHandler.super_.call(this, callback, { ignoreWhitespace: true, verbose: false, enforceEmptyTags: false }); +} +inherits(RssHandler, DefaultHandler); + + RssHandler.prototype.done = function RssHandler$done () { + var feed = { }; + var feedRoot; + + var found = DomUtils.getElementsByTagName(function (value) { return(value == "rss" || value == "feed"); }, this.dom, false); + if (found.length) { + feedRoot = found[0]; + } + if (feedRoot) { + if (feedRoot.name == "rss") { + feed.type = "rss"; + feedRoot = feedRoot.children[0]; // + feed.id = ""; +// require("sys").debug(require("sys").inspect(feedRoot, false, null)); +// require("sys").debug(require("sys").inspect(DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data, false, null)); + try { + feed.title = DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.link = DomUtils.getElementsByTagName("link", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.description = DomUtils.getElementsByTagName("description", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.updated = new Date(DomUtils.getElementsByTagName("lastBuildDate", feedRoot.children, false)[0].children[0].data); + } catch (ex) { } + try { + feed.author = DomUtils.getElementsByTagName("managingEditor", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + feed.items = []; + DomUtils.getElementsByTagName("item", feedRoot.children).forEach(function (item, index, list) { + var entry = {}; + try { + entry.id = DomUtils.getElementsByTagName("guid", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.title = DomUtils.getElementsByTagName("title", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.link = DomUtils.getElementsByTagName("link", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.description = DomUtils.getElementsByTagName("description", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.pubDate = new Date(DomUtils.getElementsByTagName("pubDate", item.children, false)[0].children[0].data); + } catch (ex) { } + feed.items.push(entry); + }); + } else { + feed.type = "atom"; + try { + feed.id = DomUtils.getElementsByTagName("id", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.title = DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.link = DomUtils.getElementsByTagName("link", feedRoot.children, false)[0].attribs.href; + } catch (ex) { } + try { + feed.description = DomUtils.getElementsByTagName("subtitle", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.updated = new Date(DomUtils.getElementsByTagName("updated", feedRoot.children, false)[0].children[0].data); + } catch (ex) { } + try { + feed.author = DomUtils.getElementsByTagName("email", feedRoot.children, true)[0].children[0].data; + } catch (ex) { } + feed.items = []; + DomUtils.getElementsByTagName("entry", feedRoot.children).forEach(function (item, index, list) { + var entry = {}; + try { + entry.id = DomUtils.getElementsByTagName("id", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.title = DomUtils.getElementsByTagName("title", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.link = DomUtils.getElementsByTagName("link", item.children, false)[0].attribs.href; + } catch (ex) { } + try { + entry.description = DomUtils.getElementsByTagName("summary", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.pubDate = new Date(DomUtils.getElementsByTagName("updated", item.children, false)[0].children[0].data); + } catch (ex) { } + feed.items.push(entry); + }); + } + + this.dom = feed; + } + RssHandler.super_.prototype.done.call(this); + } + +/////////////////////////////////////////////////// + +function DefaultHandler (callback, options) { + this.reset(); + this._options = options ? options : { }; + if (this._options.ignoreWhitespace == undefined) + this._options.ignoreWhitespace = false; //Keep whitespace-only text nodes + if (this._options.verbose == undefined) + this._options.verbose = true; //Keep data property for tags and raw property for all + if (this._options.enforceEmptyTags == undefined) + this._options.enforceEmptyTags = true; //Don't allow children for HTML tags defined as empty in spec + if ((typeof callback) == "function") + this._callback = callback; +} + + //**"Static"**// + //HTML Tags that shouldn't contain child nodes + DefaultHandler._emptyTags = { + area: 1 + , base: 1 + , basefont: 1 + , br: 1 + , col: 1 + , frame: 1 + , hr: 1 + , img: 1 + , input: 1 + , isindex: 1 + , link: 1 + , meta: 1 + , param: 1 + , embed: 1 + } + //Regex to detect whitespace only text nodes + DefaultHandler.reWhitespace = /^\s*$/; + + //**Public**// + //Properties// + DefaultHandler.prototype.dom = null; //The hierarchical object containing the parsed HTML + //Methods// + //Resets the handler back to starting state + DefaultHandler.prototype.reset = function DefaultHandler$reset() { + this.dom = []; + this._done = false; + this._tagStack = []; + this._tagStack.last = function DefaultHandler$_tagStack$last () { + return(this.length ? this[this.length - 1] : null); + } + } + //Signals the handler that parsing is done + DefaultHandler.prototype.done = function DefaultHandler$done () { + this._done = true; + this.handleCallback(null); + } + DefaultHandler.prototype.writeTag = function DefaultHandler$writeTag (element) { + this.handleElement(element); + } + DefaultHandler.prototype.writeText = function DefaultHandler$writeText (element) { + if (this._options.ignoreWhitespace) + if (DefaultHandler.reWhitespace.test(element.data)) + return; + this.handleElement(element); + } + DefaultHandler.prototype.writeComment = function DefaultHandler$writeComment (element) { + this.handleElement(element); + } + DefaultHandler.prototype.writeDirective = function DefaultHandler$writeDirective (element) { + this.handleElement(element); + } + DefaultHandler.prototype.error = function DefaultHandler$error (error) { + this.handleCallback(error); + } + + //**Private**// + //Properties// + DefaultHandler.prototype._options = null; //Handler options for how to behave + DefaultHandler.prototype._callback = null; //Callback to respond to when parsing done + DefaultHandler.prototype._done = false; //Flag indicating whether handler has been notified of parsing completed + DefaultHandler.prototype._tagStack = null; //List of parents to the currently element being processed + //Methods// + DefaultHandler.prototype.handleCallback = function DefaultHandler$handleCallback (error) { + if ((typeof this._callback) != "function") + if (error) + throw error; + else + return; + this._callback(error, this.dom); + } + DefaultHandler.prototype.handleElement = function DefaultHandler$handleElement (element) { + if (this._done) + this.handleCallback(new Error("Writing to the handler after done() called is not allowed without a reset()")); + if (!this._options.verbose) { +// element.raw = null; //FIXME: Not clean + //FIXME: Serious performance problem using delete + delete element.raw; + if (element.type == "tag" || element.type == "script" || element.type == "style") + delete element.data; + } + if (!this._tagStack.last()) { //There are no parent elements + //If the element can be a container, add it to the tag stack and the top level list + if (element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive) { + if (element.name.charAt(0) != "/") { //Ignore closing tags that obviously don't have an opening tag + this.dom.push(element); + if (!this._options.enforceEmptyTags || !DefaultHandler._emptyTags[element.name]) { //Don't add tags to the tag stack that can't have children + this._tagStack.push(element); + } + } + } + else //Otherwise just add to the top level list + this.dom.push(element); + } + else { //There are parent elements + //If the element can be a container, add it as a child of the element + //on top of the tag stack and then add it to the tag stack + if (element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive) { + if (element.name.charAt(0) == "/") { + //This is a closing tag, scan the tagStack to find the matching opening tag + //and pop the stack up to the opening tag's parent + var baseName = element.name.substring(1); + if (!this._options.enforceEmptyTags || !DefaultHandler._emptyTags[baseName]) { + var pos = this._tagStack.length - 1; + while (pos > -1 && this._tagStack[pos--].name != baseName) { } + if (pos > -1 || this._tagStack[0].name == baseName) + while (pos < this._tagStack.length - 1) + this._tagStack.pop(); + } + } + else { //This is not a closing tag + if (!this._tagStack.last().children) + this._tagStack.last().children = []; + this._tagStack.last().children.push(element); + if (!this._options.enforceEmptyTags || !DefaultHandler._emptyTags[element.name]) //Don't add tags to the tag stack that can't have children + this._tagStack.push(element); + } + } + else { //This is not a container element + if (!this._tagStack.last().children) + this._tagStack.last().children = []; + this._tagStack.last().children.push(element); + } + } + } + + var DomUtils = { + testElement: function DomUtils$testElement (options, element) { + if (!element) { + return(false); + } + + for (var key in options) { + if (key == "tag_name") { + if (element.type != "tag" && element.type != "script" && element.type != "style") { + return(false); + } + return(options["tag_name"](element.name)); + } else if (key == "tag_type") { + return(options["tag_type"](element.type)); + } else if (key == "tag_contains") { + if (element.type != "text" && element.type != "comment" && element.type != "directive") { + return(false); + } + return(options["tag_contains"](element.data)); + } else { + return(element.attribs && options[key](element.attribs[key])); + } + } + + return(true); + } + + , getElements: function DomUtils$getElements (options, currentElement, recurse) { + recurse = (recurse === undefined || recurse === null) || !!recurse; + + if (!currentElement) { + return([]); + } + + var found = []; + var elementList; + + function getTest (checkVal) { + return(((typeof options[key]) == "function") ? checkVal : function (value) { return(value == checkVal); }); + } + for (var key in options) { + options[key] = getTest(options[key]); + } + + if (DomUtils.testElement(options, currentElement)) { + found.push(currentElement); + } + + if (recurse && currentElement.children) + elementList = currentElement.children; + else if (currentElement instanceof Array) + elementList = currentElement; + else + return(found); + + for (var i = 0; i < elementList.length; i++) + found = found.concat(DomUtils.getElements(options, elementList[i], recurse)); + + return(found); + } + + , getElementById: function DomUtils$getElementById (id, currentElement, recurse) { + recurse = (recurse === undefined || recurse === null) || !!recurse; + var result = DomUtils.getElements({ id: id }, currentElement, recurse); + return(result.length ? result[0] : null); + } + + , getElementsByTagName: function DomUtils$getElementsByTagName (name, currentElement, recurse) { + recurse = (recurse === undefined || recurse === null) || !!recurse; + return(DomUtils.getElements({ tag_name: name }, currentElement, recurse)); + } + + , getElementsByTagType: function DomUtils$getElementsByTagType (type, currentElement, recurse) { + recurse = (recurse === undefined || recurse === null) || !!recurse; + return(DomUtils.getElements({ tag_type: type }, currentElement, recurse)); + } + } + + function inherits (ctor, superCtor) { + var tempCtor = function(){}; + tempCtor.prototype = superCtor.prototype; + ctor.super_ = superCtor; + ctor.prototype = new tempCtor(); + ctor.prototype.constructor = ctor; + } + +exports.Parser = Parser; + +exports.DefaultHandler = DefaultHandler; + +exports.RssHandler = RssHandler; + +exports.ElementType = ElementType; + +exports.DomUtils = DomUtils; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/package.json b/rails/node_modules/jquery/node_modules/htmlparser/package.json new file mode 100644 index 0000000..b395c90 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/package.json @@ -0,0 +1,23 @@ +{ + "name": "htmlparser" + , "description": "Forgiving HTML/XML/RSS Parser in JS for *both* Node and Browsers" + , "version": "1.7.3" + , "author": "Chris Winberry " + , "contributors": [] + , "repository": { + "type": "git" + , "url": "git://github.com/tautologistics/node-htmlparser.git" + } + , "bugs": { + "mail": "chris@winberry.net" + , "web": "http://github.com/tautologistics/node-htmlparser/issues" + } + , "os": [ "linux", "darwin", "freebsd", "win32" ] + , "directories": { "lib": "./lib/" } + , "main": "./lib/htmlparser" + , "engines": { "node": ">=0.1.33" } + , "licenses": [{ + "type": "MIT" + , "url": "http://github.com/tautologistics/node-htmlparser/raw/master/LICENSE" + }] +} diff --git a/rails/node_modules/jquery/node_modules/htmlparser/profile b/rails/node_modules/jquery/node_modules/htmlparser/profile new file mode 100755 index 0000000..e0109b0 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/profile @@ -0,0 +1,4 @@ +#!/bin/sh +node --prof --prof_auto profile.js +~/Documents/src/NodeJS/node-v0.1.91/deps/v8/tools/mac-tick-processor v8.log > profileresults.txt + diff --git a/rails/node_modules/jquery/node_modules/htmlparser/profile.getelement.js b/rails/node_modules/jquery/node_modules/htmlparser/profile.getelement.js new file mode 100644 index 0000000..a5768df --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/profile.getelement.js @@ -0,0 +1,53 @@ +//node --prof --prof_auto profile.getelement.js +//deps/v8/tools/mac-tick-processor v8.log > profile.getelement.txt +var sys = require("sys"); +var fs = require("fs"); +var htmlparser = require("./node-htmlparser"); +var htmlparser_old = require("./node-htmlparser.old"); + +var testIterations = 100; //Number of test loops to run + +function getMillisecs () { + return((new Date()).getTime()); +} + +function timeExecutions (loops, func) { + var start = getMillisecs(); + + while (loops--) + func(); + + return(getMillisecs() - start); +} + +var html = fs.readFileSync("testdata/getelement.html"); +var handler = new htmlparser.DefaultHandler(function(err, dom) { + if (err) + sys.debug("Error: " + err); +}); +var parser = new htmlparser.Parser(handler); +parser.parseComplete(html); +var dom = handler.dom; + +//sys.debug(sys.inspect(dom, false, null)); +sys.puts("New: " + timeExecutions(testIterations, function () { + var foundDivs = htmlparser.DomUtils.getElementsByTagName("div", dom); +// sys.puts("Found: " + foundDivs.length); + + var foundLimitDivs = htmlparser.DomUtils.getElementsByTagName("div", dom, null, 100); +// sys.puts("Found: " + foundLimitDivs.length); + + var foundId = htmlparser.DomUtils.getElementById("question-summary-3018026", dom); +// sys.puts("Found: " + foundId); +})); + +sys.puts("Old: " + timeExecutions(testIterations, function () { + var foundDivs = htmlparser_old.DomUtils.getElementsByTagName("div", dom); +// sys.puts("Found: " + foundDivs.length); + +// var foundLimitDivs = htmlparser.DomUtils.getElementsByTagName("div", dom); +// sys.puts("Found: " + foundLimitDivs.length); + + var foundId = htmlparser_old.DomUtils.getElementById("question-summary-3018026", dom); +// sys.puts("Found: " + foundId); +})); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/profile.getelement.txt b/rails/node_modules/jquery/node_modules/htmlparser/profile.getelement.txt new file mode 100644 index 0000000..41b4e50 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/profile.getelement.txt @@ -0,0 +1,199 @@ +line 656: unknown command: .str.split. +line 657: unknown command: .map.join. +line 658: unknown command: sys:139" +Statistical profiling result from v8.log, (429 ticks, 26 unaccounted, 0 excluded). + + [Unknown]: + ticks total nonlib name + 26 6.1% + + [Shared libraries]: + ticks total nonlib name + + [JavaScript]: + ticks total nonlib name + 108 25.2% 25.2% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 19 4.4% 4.4% Function: DomUtils$testElement /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:658 + 8 1.9% 1.9% Stub: FastNewClosure + 8 1.9% 1.9% Stub: Compare + 7 1.6% 1.6% Stub: ToBoolean + 7 1.6% 1.6% LazyCompile: isNaN native v8natives.js:78 + 7 1.6% 1.6% KeyedLoadIC: A keyed load IC from the snapshot + 7 1.6% 1.6% Builtin: A builtin from the snapshot + 5 1.2% 1.2% LazyCompile: parseInt native v8natives.js:94 + 4 0.9% 0.9% Stub: FastCloneShallowArray + 4 0.9% 0.9% Stub: CEntry + 4 0.9% 0.9% Function: Parser$parseTags /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:204 + 3 0.7% 0.7% Stub: SubString + 3 0.7% 0.7% Stub: Compare {1} + 3 0.7% 0.7% Function: Module._compile module:348 + 3 0.7% 0.7% Function: /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:697 + 2 0.5% 0.5% Stub: Instanceof + 2 0.5% 0.5% RegExp: (^\\s+|\\s+$) {1} + 2 0.5% 0.5% LazyCompile: split native string.js:587 + 2 0.5% 0.5% LazyCompile: exec native regexp.js:186 + 2 0.5% 0.5% LazyCompile: StringReplaceRegExp native string.js:278 + 2 0.5% 0.5% Function: Parser$parseAttribs /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:164 + 2 0.5% 0.5% Function: DefaultHandler$_tagStack$last /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:559 + 1 0.2% 0.2% Stub: StringAdd + 1 0.2% 0.2% RegExp: ^\\s*(\\/?)\\s*([^\\s\\/]+) + 1 0.2% 0.2% RegExp: \\s + 1 0.2% 0.2% RegExp: [\\<\\>] + 1 0.2% 0.2% RegExp: (^\\s+|\\s+$) + 1 0.2% 0.2% RegExp: ([^=<>\\ + 1 0.2% 0.2% LazyCompile: test native regexp.js:264 + 1 0.2% 0.2% LazyCompile: substring native string.js:707 + 1 0.2% 0.2% LazyCompile: slice native string.js:552 + 1 0.2% 0.2% LazyCompile: charAt native string.js:64 + 1 0.2% 0.2% LazyCompile: SubString native string.js:214 + 1 0.2% 0.2% LazyCompile: EQUALS native runtime.js:54 + 1 0.2% 0.2% Function: createInternalModule module:26 + 1 0.2% 0.2% Function: Parser$writeHandler /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:383 + 1 0.2% 0.2% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:87 + 1 0.2% 0.2% Function: DomUtils$getElementsByTagName /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:736 + 1 0.2% 0.2% Function: DefaultHandler$writeTag /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:568 + + [C++]: + ticks total nonlib name + 24 5.6% 5.6% v8::internal::Builtin_ArrayConcat + 13 3.0% 3.0% v8::internal::Heap::AllocateJSObjectFromMap + 13 3.0% 3.0% v8::internal::ArrayPrototypeHasNoElements + 12 2.8% 2.8% v8::internal::CopyElements + 10 2.3% 2.3% v8::internal::Context::global_context + 8 1.9% 1.9% v8::internal::Heap::Allocate + 7 1.6% 1.6% v8::internal::AllocateFixedArrayWithFiller + 6 1.4% 1.4% v8::internal::CharacterStreamUTF16Buffer::Advance + 6 1.4% 1.4% v8::internal::Builtin_ArrayPush + 4 0.9% 0.9% v8::internal::String::SlowEquals + 4 0.9% 0.9% v8::internal::Heap::AllocateUninitializedFixedArray + 4 0.9% 0.9% v8::internal::Heap::AllocateJSObject + 3 0.7% 0.7% v8::internal::String::ComputeAndSetHash + 3 0.7% 0.7% v8::internal::Scanner::ScanJavaScript + 3 0.7% 0.7% v8::internal::JSObject::LocalLookup + 3 0.7% 0.7% v8::internal::Heap::AllocateRawFixedArray + 2 0.5% 0.5% v8::internal::VirtualFrame::PrepareMergeTo + 2 0.5% 0.5% v8::internal::ScavengeVisitor::VisitPointers + 2 0.5% 0.5% v8::internal::Runtime_StringEquals + 2 0.5% 0.5% v8::internal::MarkingVisitor::VisitPointers + 2 0.5% 0.5% v8::internal::KeywordMatcher::Step + 2 0.5% 0.5% v8::internal::JumpTarget::DoBind + 2 0.5% 0.5% v8::internal::JumpTarget::ComputeEntryFrame + 2 0.5% 0.5% v8::internal::Heap::IterateRSetRange + 2 0.5% 0.5% v8::internal::Heap::AllocateStringFromUtf8 + 2 0.5% 0.5% v8::internal::Heap::AllocateFixedArray + 2 0.5% 0.5% ___dtoa + 1 0.2% 0.2% v8::internal::VirtualFrame::SyncRange + 1 0.2% 0.2% v8::internal::VirtualFrame::SyncElementByPushing + 1 0.2% 0.2% v8::internal::VirtualFrame::Push + 1 0.2% 0.2% v8::internal::VirtualFrame::MergeMoveMemoryToRegisters + 1 0.2% 0.2% v8::internal::SweepNewSpace + 1 0.2% 0.2% v8::internal::String::WriteToFlat + 1 0.2% 0.2% v8::internal::String::IsEqualTo + 1 0.2% 0.2% v8::internal::SetElement + 1 0.2% 0.2% v8::internal::Scanner::ScanIdentifier + 1 0.2% 0.2% v8::internal::Runtime_StringReplaceRegExpWithString + 1 0.2% 0.2% v8::internal::Runtime_StringIndexOf + 1 0.2% 0.2% v8::internal::RegisterAllocator::Allocate + 1 0.2% 0.2% v8::internal::RegExpMacroAssemblerIA32::PushBacktrack + 1 0.2% 0.2% v8::internal::Object::GetPrototype + 1 0.2% 0.2% v8::internal::Object::GetProperty + 1 0.2% 0.2% v8::internal::MemoryAllocator::InitializePagesInChunk + 1 0.2% 0.2% v8::internal::Map::PropertyIndexFor + 1 0.2% 0.2% v8::internal::Map::FindInCodeCache + 1 0.2% 0.2% v8::internal::MacroAssembler::InvokeFunction + 1 0.2% 0.2% v8::internal::JumpTarget::DoJump + 1 0.2% 0.2% v8::internal::JumpTarget::DoBranch + 1 0.2% 0.2% v8::internal::HeapObject::IterateBody + 1 0.2% 0.2% v8::internal::HeapObject::Iterate + 1 0.2% 0.2% v8::internal::Heap::Scavenge + 1 0.2% 0.2% v8::internal::Heap::AllocateSubString + 1 0.2% 0.2% v8::internal::Heap::AllocateStringFromAscii + 1 0.2% 0.2% v8::internal::Heap::AllocateRawAsciiString + 1 0.2% 0.2% v8::internal::HashTable::FindEntry + 1 0.2% 0.2% v8::internal::FreeListNode::set_size + 1 0.2% 0.2% v8::internal::Deserializer::ReadChunk + 1 0.2% 0.2% v8::internal::DescriptorArray::CopyInsert + 1 0.2% 0.2% v8::internal::CompareStub::MinorKey + 1 0.2% 0.2% v8::internal::CompareLocal + 1 0.2% 0.2% v8::internal::CodeGenerator::VisitStatements + 1 0.2% 0.2% v8::internal::CodeGenerator::Load + 1 0.2% 0.2% v8::internal::CodeGenerator::Comparison + 1 0.2% 0.2% v8::internal::CallIC::LoadFunction + 1 0.2% 0.2% v8::internal::AssignedVariablesAnalyzer::ProcessExpression + 1 0.2% 0.2% v8::internal::Assembler::mov + 1 0.2% 0.2% v8::internal::Assembler::jmp + 1 0.2% 0.2% v8::internal::AllocateEmptyJSArray + 1 0.2% 0.2% unibrow::Utf8::ReadBlock + 1 0.2% 0.2% node::Cipher::Initialize + 1 0.2% 0.2% _szone_free + 1 0.2% 0.2% _small_malloc_from_region_no_lock + 1 0.2% 0.2% _sha1_block_data_order + 1 0.2% 0.2% _pthread_mutex_unlock + 1 0.2% 0.2% _ares_library_init + 1 0.2% 0.2% _aes_decrypt_cbc + 1 0.2% 0.2% __mh_dylib_header + 1 0.2% 0.2% _NSGetNextSearchPathEnumeration + + [GC]: + ticks total nonlib name + 13 3.0% + + [Bottom up (heavy) profile]: + Note: percentage shows a share of a particular caller in the total + amount of its parent calls. + Callers occupying less than 2.0% are not shown. + + ticks parent name + 108 25.2% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 108 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 108 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 103 95.4% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 103 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 102 99.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 5 4.6% Function: DomUtils$getElementsByTagName /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:736 + 5 100.0% Function: /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.getelement.js:33 + 5 100.0% Function: timeExecutions /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.getelement.js:14 + + 24 5.6% v8::internal::Builtin_ArrayConcat + 24 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 24 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 24 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 24 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 23 95.8% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 1 4.2% Function: DomUtils$getElementsByTagName /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:736 + + 19 4.4% Function: DomUtils$testElement /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:658 + 18 94.7% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 18 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 18 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 18 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 18 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + + 13 3.0% v8::internal::Heap::AllocateJSObjectFromMap + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + + 13 3.0% v8::internal::ArrayPrototypeHasNoElements + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 13 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + + 12 2.8% v8::internal::CopyElements + 12 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 12 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 12 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 12 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 12 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + + 10 2.3% v8::internal::Context::global_context + 10 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 10 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 10 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 10 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + 10 100.0% Function: DomUtils$getElements /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:684 + diff --git a/rails/node_modules/jquery/node_modules/htmlparser/profile.js b/rails/node_modules/jquery/node_modules/htmlparser/profile.js new file mode 100644 index 0000000..f9d0ef2 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/profile.js @@ -0,0 +1,63 @@ +//node --prof --prof_auto profile.js +//deps/v8/tools/mac-tick-processor v8.log +var sys = require("sys"); +var fs = require("fs"); +var http = require("http"); +var htmlparser = require("./lib/htmlparser"); +//var libxml = require('./libxmljs'); + +var testNHP = true; //Should node-htmlparser be exercised? +var testLXJS = false; //Should libxmljs be exercised? +var testIterations = 100; //Number of test loops to run + +var testHost = "localhost"; //Host to fetch test HTML from +var testPort = 80; //Port on host to fetch test HTML from +var testPath = "/~chris/feed.xml"; //Path on host to fetch HTML from + +function getMillisecs () { + return((new Date()).getTime()); +} + +function timeExecutions (loops, func) { + var start = getMillisecs(); + + while (loops--) + func(); + + return(getMillisecs() - start); +} + +var html = ""; +http.createClient(testPort, testHost) + .request("GET", testPath, { host: testHost }) + .addListener("response", function (response) { + if (response.statusCode == "200") { + response.setEncoding("utf8"); + response.addListener("data", function (chunk) { + html += chunk; + }).addListener("end", function() { + var timeNodeHtmlParser = !testNHP ? 0 : timeExecutions(testIterations, function () { + var handler = new htmlparser.DefaultHandler(function(err, dom) { + if (err) + sys.debug("Error: " + err); + }); + var parser = new htmlparser.Parser(handler, { includeLocation: true }); + parser.parseComplete(html); + }) + + var timeLibXmlJs = !testLXJS ? 0 : timeExecutions(testIterations, function () { + var dom = libxml.parseHtmlString(html); + }) + + if (testNHP) + sys.debug("NodeHtmlParser: " + timeNodeHtmlParser); + if (testLXJS) + sys.debug("LibXmlJs: " + timeLibXmlJs); + if (testNHP && testLXJS) + sys.debug("Difference: " + ((timeNodeHtmlParser - timeLibXmlJs) / timeLibXmlJs) * 100); + }); + } + else + sys.debug("Error: got response status " + response.statusCode); + }) + .end(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/profileresults.txt b/rails/node_modules/jquery/node_modules/htmlparser/profileresults.txt new file mode 100644 index 0000000..933a319 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/profileresults.txt @@ -0,0 +1,301 @@ +line 663: unknown command: .str.split. +line 664: unknown command: .map.join. +line 665: unknown command: sys:139" +Statistical profiling result from v8.log, (3681 ticks, 563 unaccounted, 0 excluded). + + [Unknown]: + ticks total nonlib name + 563 15.3% + + [Shared libraries]: + ticks total nonlib name + + [JavaScript]: + ticks total nonlib name + 545 14.8% 14.8% Function: timeLibXmlJs.testLXJS.timeExecutions.testIterations /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:48 + 225 6.1% 6.1% Function: Parser$parseTags /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:205 + 110 3.0% 3.0% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:88 + 91 2.5% 2.5% LazyCompile: test native regexp.js:264 + 81 2.2% 2.2% Stub: RegExpExecStub + 73 2.0% 2.0% LazyCompile: exec native regexp.js:186 + 66 1.8% 1.8% Stub: SubString + 66 1.8% 1.8% LazyCompile: BuildResultFromMatchInfo native regexp.js:151 + 54 1.5% 1.5% RegExp: ^\\s*(\\/?)\\s*([^\\s\\/]+) + 52 1.4% 1.4% LazyCompile: substring native string.js:707 + 50 1.4% 1.4% LazyCompile: split native string.js:587 + 46 1.2% 1.2% Stub: CEntry + 44 1.2% 1.2% Function: DefaultHandler$writeTag /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:465 + 42 1.1% 1.1% Stub: Compare {1} + 38 1.0% 1.0% LazyCompile: slice native string.js:552 + 31 0.8% 0.8% LazyCompile: indexOf native string.js:109 + 29 0.8% 0.8% RegExp: [\\<\\>] + 29 0.8% 0.8% LazyCompile: SubString native string.js:214 + 29 0.8% 0.8% Function: DefaultHandler$handleElement /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:499 + 28 0.8% 0.8% Function: Parser$parseTagName /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:194 + 26 0.7% 0.7% Stub: Compare {2} + 26 0.7% 0.7% Function: DefaultHandler$writeText /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:468 + 20 0.5% 0.5% KeyedLoadIC: A keyed load IC from the snapshot + 20 0.5% 0.5% Function: Parser$writeHandler /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:384 + 19 0.5% 0.5% LazyCompile: STRING_ADD_LEFT native runtime.js:175 + 19 0.5% 0.5% Function: Parser$parseAttribs /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:165 + 17 0.5% 0.5% LazyCompile: EQUALS native runtime.js:54 + 16 0.4% 0.4% Stub: ToBoolean + 16 0.4% 0.4% RegExp: ^\\s*(\\/?)\\s*([^\\s\\/]+) {1} + 15 0.4% 0.4% RegExp: (^\\s+|\\s+$) {1} + 14 0.4% 0.4% RegExp: (^\\s+|\\s+$) + 13 0.4% 0.4% LazyCompile: StringReplaceRegExp native string.js:278 + 12 0.3% 0.3% LazyCompile: replace native string.js:236 + 12 0.3% 0.3% LazyCompile: charAt native string.js:64 + 12 0.3% 0.3% KeyedStoreIC: A keyed store IC from the snapshot + 10 0.3% 0.3% RegExp: \\s + 9 0.2% 0.2% Stub: StringAdd + 9 0.2% 0.2% Stub: FastCloneShallowArray + 9 0.2% 0.2% Function: DefaultHandler$_tagStack$last /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:456 + 8 0.2% 0.2% RegExp: \\s {1} + 7 0.2% 0.2% Stub: Compare {3} + 7 0.2% 0.2% LazyCompile: splitMatch native string.js:696 + 4 0.1% 0.1% Stub: Compare + 4 0.1% 0.1% LazyCompile: DoRegExpExec native regexp.js:117 + 3 0.1% 0.1% Builtin: A builtin from the snapshot + 2 0.1% 0.1% Stub: GenericBinaryOpStub_ADD_Alloc_RegArgs_UnknownType_Default + 1 0.0% 0.0% Stub: ArgumentsAccess + 1 0.0% 0.0% RegExp: ([^=<>\\ {1} + 1 0.0% 0.0% RegExp: ([^=<>\\ + 1 0.0% 0.0% Function: DefaultHandler /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:415 + + [C++]: + ticks total nonlib name + 214 5.8% 5.8% _libinfoDSmig_Query_async + 74 2.0% 2.0% v8::internal::String::ReadBlock + 63 1.7% 1.7% v8::internal::JSObject::LocalLookupRealNamedProperty + 61 1.7% 1.7% v8::internal::CallIC::UpdateCaches + 55 1.5% 1.5% v8::internal::CallIC::LoadFunction + 53 1.4% 1.4% v8::internal::Object::GetProperty + 53 1.4% 1.4% v8::String::WriteUtf8 + 52 1.4% 1.4% v8::internal::CallIC_Miss + 46 1.2% 1.2% v8::internal::JSObject::LocalLookup + 36 1.0% 1.0% v8::internal::JSObject::LookupInDescriptor + 31 0.8% 0.8% v8::internal::JSObject::Lookup + 26 0.7% 0.7% v8::internal::Object::Lookup + 26 0.7% 0.7% ___vfprintf + 25 0.7% 0.7% v8::internal::String::Utf8Length + 25 0.7% 0.7% v8::internal::Heap::AllocateRawFixedArray + 23 0.6% 0.6% v8::internal::Heap::CopyJSObject + 23 0.6% 0.6% __mh_dylib_header + 22 0.6% 0.6% v8::internal::SharedStoreIC_ExtendStorage + 22 0.6% 0.6% v8::internal::SetElement + 22 0.6% 0.6% v8::internal::Runtime_CreateObjectLiteralShallow + 22 0.6% 0.6% v8::internal::HashTable::FindEntry + 21 0.6% 0.6% v8::internal::Runtime::StringMatch + 20 0.5% 0.5% v8::internal::JSObject::SetFastElement + 19 0.5% 0.5% v8::internal::IC::StateFrom + 19 0.5% 0.5% v8::internal::Heap::AllocateSubString + 19 0.5% 0.5% v8::internal::Heap::AllocateRawTwoByteString + 19 0.5% 0.5% _asprintf + 18 0.5% 0.5% v8::internal::Runtime_StringReplaceRegExpWithString + 18 0.5% 0.5% v8::internal::Object::GetPrototype + 18 0.5% 0.5% v8::internal::DescriptorArray::BinarySearch + 17 0.5% 0.5% v8::internal::Runtime::SetObjectProperty + 16 0.4% 0.4% v8::internal::String::SlowEquals + 15 0.4% 0.4% v8::internal::AllocateFixedArrayWithFiller + 14 0.4% 0.4% v8::internal::LookupForRead + 14 0.4% 0.4% v8::internal::Heap::AllocateRawAsciiString + 13 0.4% 0.4% v8::internal::Runtime_StringIndexOf + 12 0.3% 0.3% v8::internal::JSObject::SetFastElements + 11 0.3% 0.3% v8::internal::Runtime_SubString + 11 0.3% 0.3% v8::internal::Runtime_StringEquals + 11 0.3% 0.3% v8::internal::Heap::AllocateFixedArray + 10 0.3% 0.3% v8::internal::RegExpImpl::IrregexpExecOnce + 10 0.3% 0.3% _szone_calloc + 10 0.3% 0.3% _nanosleep$UNIX2003 + 10 0.3% 0.3% _mach_init_doit + 9 0.2% 0.2% v8::internal::TwoCharHashTableKey::IsMatch + 9 0.2% 0.2% v8::internal::JSObject::GetNormalizedProperty + 9 0.2% 0.2% _bootstrap_look_up + 8 0.2% 0.2% v8::internal::String::ComputeAndSetHash + 8 0.2% 0.2% v8::internal::RegExpStack::RegExpStack + 8 0.2% 0.2% v8::internal::RegExpImpl::IrregexpPrepare + 8 0.2% 0.2% v8::internal::RegExpImpl::IrregexpExec + 8 0.2% 0.2% v8::internal::JSObject::SetElementWithoutInterceptor + 7 0.2% 0.2% v8::internal::String::WriteToFlat + 7 0.2% 0.2% v8::internal::SimpleIndexOf + 7 0.2% 0.2% v8::internal::ScavengeVisitor::VisitPointers + 7 0.2% 0.2% v8::internal::HashTable::FindEntry + 6 0.2% 0.2% v8::internal::ArrayPrototypeHasNoElements + 5 0.1% 0.1% v8::internal::SymbolTable::LookupTwoCharsSymbolIfExists + 5 0.1% 0.1% v8::internal::Runtime_SetProperty + 5 0.1% 0.1% v8::internal::Runtime_KeyedGetProperty + 5 0.1% 0.1% v8::internal::Runtime::GetObjectProperty + 5 0.1% 0.1% v8::internal::NativeRegExpMacroAssembler::Match + 5 0.1% 0.1% v8::internal::JumpTarget::ComputeEntryFrame + 5 0.1% 0.1% v8::internal::Heap::AllocateConsString + 5 0.1% 0.1% v8::internal::Builtin_ArrayShift + 5 0.1% 0.1% v8::internal::Builtin_ArrayPush + 5 0.1% 0.1% _small_malloc_from_region_no_lock + 4 0.1% 0.1% v8::internal::String::WriteToFlat + 4 0.1% 0.1% v8::internal::String::SubString + 4 0.1% 0.1% v8::internal::NativeRegExpMacroAssembler::StringCharacterPosition + 4 0.1% 0.1% v8::internal::LeftTrimFixedArray + 4 0.1% 0.1% v8::internal::JSObject::SetElement + 4 0.1% 0.1% v8::internal::Heap::AllocateFixedArrayWithHoles + 3 0.1% 0.1% v8::internal::String::ToUC16Vector + 3 0.1% 0.1% v8::internal::RegExpImpl::Exec + 3 0.1% 0.1% v8::internal::NativeRegExpMacroAssembler::Execute + 3 0.1% 0.1% v8::internal::JumpTarget::DoBind + 3 0.1% 0.1% v8::internal::HeapObject::IterateBody + 3 0.1% 0.1% v8::internal::Heap::DoScavenge + 3 0.1% 0.1% v8::internal::AssignedVariablesAnalyzer::ProcessExpression + 3 0.1% 0.1% _select$NOCANCEL$UNIX2003 + 3 0.1% 0.1% _mach_init + 2 0.1% 0.1% v8::internal::VirtualFrame::PrepareMergeTo + 2 0.1% 0.1% v8::internal::StringHasher::GetHashField + 2 0.1% 0.1% v8::internal::String::ToAsciiVector + 2 0.1% 0.1% v8::internal::Scanner::ScanJavaScript + 2 0.1% 0.1% v8::internal::Result::Result + 2 0.1% 0.1% v8::internal::RegExpStack::~RegExpStack + 2 0.1% 0.1% v8::internal::HeapObject::SlowSizeFromMap + 2 0.1% 0.1% v8::internal::Heap::ScavengeObjectSlow + 2 0.1% 0.1% v8::internal::Context::global_context + 2 0.1% 0.1% v8::internal::CharacterStreamUTF16Buffer::Advance + 2 0.1% 0.1% v8::internal::AstVisitor::CheckStackOverflow + 2 0.1% 0.1% v8::internal::AstOptimizer::VisitVariableProxy + 2 0.1% 0.1% unibrow::Utf8::ReadBlock + 2 0.1% 0.1% _mach_reply_port + 2 0.1% 0.1% __keymgr_get_and_lock_processwide_ptr_2 + 1 0.0% 0.0% v8::internal::Zone::NewExpand + 1 0.0% 0.0% v8::internal::VirtualFrame::Pop + 1 0.0% 0.0% v8::internal::TypeInfo::TypeFromValue + 1 0.0% 0.0% v8::internal::SweepNewSpace + 1 0.0% 0.0% v8::internal::String::ToCString + 1 0.0% 0.0% v8::internal::String::IsEqualTo + 1 0.0% 0.0% v8::internal::String::ComputeHashField + 1 0.0% 0.0% v8::internal::Slot::AsSlot + 1 0.0% 0.0% v8::internal::SetProperty + 1 0.0% 0.0% v8::internal::ScopeInfo::ScopeInfo + 1 0.0% 0.0% v8::internal::Scope::Scope + 1 0.0% 0.0% v8::internal::ScavengeVisitor::VisitPointer + 1 0.0% 0.0% v8::internal::Scanner::ScanIdentifier + 1 0.0% 0.0% v8::internal::Runtime::GetElementOrCharAt + 1 0.0% 0.0% v8::internal::RelocIterator::next + 1 0.0% 0.0% v8::internal::Parser::ParseUnaryExpression + 1 0.0% 0.0% v8::internal::Parser::ParseStatement + 1 0.0% 0.0% v8::internal::OldSpace::SlowAllocateRaw + 1 0.0% 0.0% v8::internal::MarkingVisitor::VisitPointer + 1 0.0% 0.0% v8::internal::Literal::IsPropertyName + 1 0.0% 0.0% v8::internal::KeyedLookupCache::Lookup + 1 0.0% 0.0% v8::internal::JumpTarget::DoBranch + 1 0.0% 0.0% v8::internal::JumpTarget::Branch + 1 0.0% 0.0% v8::internal::HeapObject::Iterate + 1 0.0% 0.0% v8::internal::Heap::UpdateRSet + 1 0.0% 0.0% v8::internal::Heap::CreateFillerObjectAt + 1 0.0% 0.0% v8::internal::Heap::AllocateUninitializedFixedArray + 1 0.0% 0.0% v8::internal::Heap::AllocateStringFromUtf8 + 1 0.0% 0.0% v8::internal::Heap::AllocateStringFromAscii + 1 0.0% 0.0% v8::internal::HashTable::EnsureCapacity + 1 0.0% 0.0% v8::internal::HashMap::HashMap + 1 0.0% 0.0% v8::internal::FreeListNode::set_size + 1 0.0% 0.0% v8::internal::FixedArray::CopySize + 1 0.0% 0.0% v8::internal::Deserializer::GetAddressFromStart + 1 0.0% 0.0% v8::internal::DescriptorArray::LinearSearch + 1 0.0% 0.0% v8::internal::ContextSlotCache::Lookup + 1 0.0% 0.0% v8::internal::CodeGenerator::VisitObjectLiteral + 1 0.0% 0.0% v8::internal::CodeGenerator::VisitAssignment + 1 0.0% 0.0% v8::internal::AstOptimizer::VisitCompareOperation + 1 0.0% 0.0% v8::internal::Assembler::push + 1 0.0% 0.0% v8::internal::Assembler::j + 1 0.0% 0.0% v8::Integer::New + 1 0.0% 0.0% node::Socket + 1 0.0% 0.0% node::DLOpen + 1 0.0% 0.0% _tiny_malloc_from_free_list + 1 0.0% 0.0% _szone_free + 1 0.0% 0.0% _small_free_list_remove_ptr + 1 0.0% 0.0% _sha1_block_data_order + 1 0.0% 0.0% _pthread_mutex_unlock + 1 0.0% 0.0% _memset_pattern4 + 1 0.0% 0.0% _memset_pattern16 + 1 0.0% 0.0% _mach_port_allocate + 1 0.0% 0.0% _mach_msg_trap + 1 0.0% 0.0% _localeconv_l + 1 0.0% 0.0% _libSystem_initializer + 1 0.0% 0.0% _getsectbynamefromheader + 1 0.0% 0.0% _get_or_create_key_element + 1 0.0% 0.0% _expl + 1 0.0% 0.0% __nc_table_insert_n + 1 0.0% 0.0% ___sfvwrite + 1 0.0% 0.0% __LI_async_send + + [GC]: + ticks total nonlib name + 30 0.8% + + [Bottom up (heavy) profile]: + Note: percentage shows a share of a particular caller in the total + amount of its parent calls. + Callers occupying less than 2.0% are not shown. + + ticks parent name + 545 14.8% Function: timeLibXmlJs.testLXJS.timeExecutions.testIterations /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:48 + 545 100.0% Function: timeExecutions /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:21 + 545 100.0% Function: /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:38 + 545 100.0% LazyCompile: process.EventEmitter.emit events:4 + 545 100.0% Function: parser.onMessageComplete http:99 + 545 100.0% Function: Client.self.ondata http:635 + + 225 6.1% Function: Parser$parseTags /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:205 + 225 100.0% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:88 + 225 100.0% Function: Parser$parseComplete /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:81 + 225 100.0% Function: timeNodeHtmlParser.testNHP.timeExecutions.testIterations /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:39 + 225 100.0% Function: timeExecutions /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:21 + 225 100.0% Function: /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:38 + + 214 5.8% _libinfoDSmig_Query_async + 214 100.0% node::Loop + 214 100.0% LazyCompile: node.js:1 + + 110 3.0% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:88 + 110 100.0% Function: Parser$parseComplete /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:81 + 110 100.0% Function: timeNodeHtmlParser.testNHP.timeExecutions.testIterations /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:39 + 110 100.0% Function: timeExecutions /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:21 + 110 100.0% Function: /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:38 + 110 100.0% LazyCompile: process.EventEmitter.emit events:4 + + 91 2.5% LazyCompile: test native regexp.js:264 + 89 97.8% Function: Parser$parseTags /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:205 + 89 100.0% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:88 + 89 100.0% Function: Parser$parseComplete /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:81 + 89 100.0% Function: timeNodeHtmlParser.testNHP.timeExecutions.testIterations /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:39 + 89 100.0% Function: timeExecutions /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:21 + 2 2.2% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:88 + 2 100.0% Function: Parser$parseComplete /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:81 + 2 100.0% Function: timeNodeHtmlParser.testNHP.timeExecutions.testIterations /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:39 + 2 100.0% Function: timeExecutions /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:21 + 2 100.0% Function: /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:38 + + 81 2.2% Stub: RegExpExecStub + 38 46.9% LazyCompile: test native regexp.js:264 + 38 100.0% Function: Parser$parseTags /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:205 + 38 100.0% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:88 + 38 100.0% Function: Parser$parseComplete /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:81 + 38 100.0% Function: timeNodeHtmlParser.testNHP.timeExecutions.testIterations /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:39 + 31 38.3% LazyCompile: exec native regexp.js:186 + 30 96.8% Function: Parser$parseTagName /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:194 + 30 100.0% Function: Parser$parseTags /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:205 + 30 100.0% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:88 + 30 100.0% Function: Parser$parseComplete /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:81 + 1 3.2% Function: Parser$parseAttribs /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:165 + 1 100.0% Function: Parser$parseTags /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:205 + 1 100.0% Function: Parser$parseChunk /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:88 + 1 100.0% Function: Parser$parseComplete /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:81 + 12 14.8% LazyCompile: DoRegExpExec native regexp.js:117 + 12 100.0% LazyCompile: splitMatch native string.js:696 + 12 100.0% LazyCompile: split native string.js:587 + 12 100.0% Function: Parser$parseAttribs /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:165 + 12 100.0% Function: Parser$parseTags /Users/chris/Documents/workspace_3.5/NodeHtmlParser/node-htmlparser.js:205 + + 74 2.0% v8::internal::String::ReadBlock + 74 100.0% Function: timeLibXmlJs.testLXJS.timeExecutions.testIterations /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:48 + 74 100.0% Function: timeExecutions /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:21 + 74 100.0% Function: /Users/chris/Documents/workspace_3.5/NodeHtmlParser/profile.js:38 + 74 100.0% LazyCompile: process.EventEmitter.emit events:4 + 74 100.0% Function: parser.onMessageComplete http:99 + diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/CHANGELOG b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/CHANGELOG new file mode 100644 index 0000000..c02e8e2 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/CHANGELOG @@ -0,0 +1,9 @@ + +v1.5.0 + * Added DefaultHandler option "enforceEmptyTags" so that XML can be parsed correctly + +v1.4.2 + * Added tests for parsing XML with namespaces + +v1.4.1 + * Added minified version diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/LICENSE b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/LICENSE new file mode 100644 index 0000000..3196dba --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/LICENSE @@ -0,0 +1,18 @@ +Copyright 2010, Chris Winberry . All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. \ No newline at end of file diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/README.md b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/README.md new file mode 100644 index 0000000..e81ceb3 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/README.md @@ -0,0 +1,186 @@ +#NodeHtmlParser +A forgiving HTML/XML/RSS parser written in JS for both the browser and NodeJS (yes, despite the name it works just fine in any modern browser). The parser can handle streams (chunked data) and supports custom handlers for writing custom DOMs/output. + +##Installing + + npm install htmlparser + +##Running Tests + +###Run tests under node: + node runtests.js + +###Run tests in browser: +View runtests.html in any browser + +##Usage In Node + var htmlparser = require("node-htmlparser"); + var rawHtml = "Xyz + , Style: "style" //Special tag + , Tag: "tag" //Any tag that isn't special + } + + function Parser (handler) { + this.validateHandler(handler); + this._handler = handler; + this.reset(); + } + + //**"Static"**// + //Regular expressions used for cleaning up and parsing (stateless) + Parser._reTrim = /(^\s+|\s+$)/g; //Trim leading/trailing whitespace + Parser._reTrimComment = /(^\!--|--$)/g; //Remove comment tag markup from comment contents + Parser._reWhitespace = /\s/g; //Used to find any whitespace to split on + Parser._reTagName = /^\s*(\/?)\s*([^\s\/]+)/; //Used to find the tag name for an element + + //Regular expressions used for parsing (stateful) + Parser._reAttrib = //Find attributes in a tag + /([^=<>\"\'\s]+)\s*=\s*"([^"]*)"|([^=<>\"\'\s]+)\s*=\s*'([^']*)'|([^=<>\"\'\s]+)\s*=\s*([^'"\s]+)|([^=<>\"\'\s\/]+)/g; +Parser._reTags = /[\<\>]/g; //Find tag markers + +//**Public**// +//Methods// +//Parses a complete HTML and pushes it to the handler +Parser.prototype.parseComplete = function Parser$parseComplete (data) { + this.reset(); + this.parseChunk(data); + this.done(); +} + +//Parses a piece of an HTML document +Parser.prototype.parseChunk = function Parser$parseChunk (data) { + if (this._done) + this.handleError(new Error("Attempted to parse chunk after parsing already done")); + this._buffer += data; //FIXME: this can be a bottleneck + this.parseTags(); +} + +//Tells the parser that the HTML being parsed is complete +Parser.prototype.done = function Parser$done () { + if (this._done) + return; + this._done = true; + + //Push any unparsed text into a final element in the element list + if (this._buffer.length) { + var rawData = this._buffer; + this._buffer = ""; + var element = { + raw: rawData + , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(Parser._reTrim, "") + , type: this._parseState + }; + if (this._parseState == ElementType.Tag || this._parseState == ElementType.Script || this._parseState == ElementType.Style) + element.name = this.parseTagName(element.data); + this.parseAttribs(element); + this._elements.push(element); + } + + this.writeHandler(); + this._handler.done(); +} + +//Resets the parser to a blank state, ready to parse a new HTML document +Parser.prototype.reset = function Parser$reset () { + this._buffer = ""; + this._done = false; + this._elements = []; + this._elementsCurrent = 0; + this._current = 0; + this._next = 0; + this._parseState = ElementType.Text; + this._prevTagSep = ''; + this._tagStack = []; + this._handler.reset(); +} + +//**Private**// +//Properties// +Parser.prototype._handler = null; //Handler for parsed elements +Parser.prototype._buffer = null; //Buffer of unparsed data +Parser.prototype._done = false; //Flag indicating whether parsing is done +Parser.prototype._elements = null; //Array of parsed elements +Parser.prototype._elementsCurrent = 0; //Pointer to last element in _elements that has been processed +Parser.prototype._current = 0; //Position in data that has already been parsed +Parser.prototype._next = 0; //Position in data of the next tag marker (<>) +Parser.prototype._parseState = ElementType.Text; //Current type of element being parsed +Parser.prototype._prevTagSep = ''; //Previous tag marker found +//Stack of element types previously encountered; keeps track of when +//parsing occurs inside a script/comment/style tag +Parser.prototype._tagStack = null; + +//Methods// +//Takes an array of elements and parses any found attributes +Parser.prototype.parseTagAttribs = function Parser$parseTagAttribs (elements) { + var idxEnd = elements.length; + var idx = 0; + + while (idx < idxEnd) { + var element = elements[idx++]; + if (element.type == ElementType.Tag || element.type == ElementType.Script || element.type == ElementType.style) + this.parseAttribs(element); + } + + return(elements); +} + +//Takes an element and adds an "attribs" property for any element attributes found +Parser.prototype.parseAttribs = function Parser$parseAttribs (element) { + //Only parse attributes for tags + if (element.type != ElementType.Script && element.type != ElementType.Style && element.type != ElementType.Tag) + return; + + var tagName = element.data.split(Parser._reWhitespace, 1)[0]; + var attribRaw = element.data.substring(tagName.length); + if (attribRaw.length < 1) + return; + + var match; + Parser._reAttrib.lastIndex = 0; + while (match = Parser._reAttrib.exec(attribRaw)) { + if (element.attribs == undefined) + element.attribs = {}; + + if (typeof match[1] == "string" && match[1].length) { + element.attribs[match[1]] = match[2]; + } else if (typeof match[3] == "string" && match[3].length) { + element.attribs[match[3].toString()] = match[4].toString(); + } else if (typeof match[5] == "string" && match[5].length) { + element.attribs[match[5]] = match[6]; + } else if (typeof match[7] == "string" && match[7].length) { + element.attribs[match[7]] = match[7]; + } + } +} + +//Extracts the base tag name from the data value of an element +Parser.prototype.parseTagName = function Parser$parseTagName (data) { + if (data == null || data == "") + return(""); + var match = Parser._reTagName.exec(data); + if (!match) + return(""); + return((match[1] ? "/" : "") + match[2]); +} + +//Parses through HTML text and returns an array of found elements +//I admit, this function is rather large but splitting up had an noticeable impact on speed +Parser.prototype.parseTags = function Parser$parseTags () { + var bufferEnd = this._buffer.length - 1; + while (Parser._reTags.test(this._buffer)) { + this._next = Parser._reTags.lastIndex - 1; + var tagSep = this._buffer.charAt(this._next); //The currently found tag marker + var rawData = this._buffer.substring(this._current, this._next); //The next chunk of data to parse + + //A new element to eventually be appended to the element list + var element = { + raw: rawData + , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(Parser._reTrim, "") + , type: this._parseState + }; + + var elementName = this.parseTagName(element.data); + + //This section inspects the current tag stack and modifies the current + //element if we're actually parsing a special area (script/comment/style tag) + if (this._tagStack.length) { //We're parsing inside a script/comment/style tag + if (this._tagStack[this._tagStack.length - 1] == ElementType.Script) { //We're currently in a script tag + if (elementName == "/script") //Actually, we're no longer in a script tag, so pop it off the stack + this._tagStack.pop(); + else { //Not a closing script tag + if (element.raw.indexOf("!--") != 0) { //Make sure we're not in a comment + //All data from here to script close is now a text element + element.type = ElementType.Text; + //If the previous element is text, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + } + } + } + } + else if (this._tagStack[this._tagStack.length - 1] == ElementType.Style) { //We're currently in a style tag + if (elementName == "/style") //Actually, we're no longer in a style tag, so pop it off the stack + this._tagStack.pop(); + else { + if (element.raw.indexOf("!--") != 0) { //Make sure we're not in a comment + //All data from here to style close is now a text element + element.type = ElementType.Text; + //If the previous element is text, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) { + if (element.raw != "") { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + } + else{ //Element is empty, so just append the last tag marker found + if (prevElement) { + prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep; + } + } + } + else //The previous element was not text + if (element.raw != "") + element.raw = element.data = element.raw; + } + } + } + else if (this._tagStack[this._tagStack.length - 1] == ElementType.Comment) { //We're currently in a comment tag + var rawLen = element.raw.length; + if (element.raw.charAt(rawLen - 2) == "-" && element.raw.charAt(rawLen - 1) == "-" && tagSep == ">") { + //Actually, we're no longer in a style tag, so pop it off the stack + this._tagStack.pop(); + //If the previous element is a comment, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = (prevElement.raw + element.raw).replace(Parser._reTrimComment, ""); + element.raw = element.data = ""; //This causes the current element to not be added to the element list + element.type = ElementType.Text; + } + else //Previous element not a comment + element.type = ElementType.Comment; //Change the current element's type to a comment + } + else { //Still in a comment tag + element.type = ElementType.Comment; + //If the previous element is a comment, append the current text to it + if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) { + var prevElement = this._elements[this._elements.length - 1]; + prevElement.raw = prevElement.data = prevElement.raw + element.raw + tagSep; + element.raw = element.data = ""; //This causes the current element to not be added to the element list + element.type = ElementType.Text; + } + else + element.raw = element.data = element.raw + tagSep; + } + } + } + + //Processing of non-special tags + if (element.type == ElementType.Tag) { + element.name = elementName; + + if (element.raw.indexOf("!--") == 0) { //This tag is really comment + element.type = ElementType.Comment; + delete element["name"]; + var rawLen = element.raw.length; + //Check if the comment is terminated in the current element + if (element.raw.charAt(rawLen - 1) == "-" && element.raw.charAt(rawLen - 2) == "-" && tagSep == ">") + element.raw = element.data = element.raw.replace(Parser._reTrimComment, ""); + else { //It's not so push the comment onto the tag stack + element.raw += tagSep; + this._tagStack.push(ElementType.Comment); + } + } + else if (element.raw.indexOf("!") == 0 || element.raw.indexOf("?") == 0) { + element.type = ElementType.Directive; + //TODO: what about CDATA? + } + else if (element.name == "script") { + element.type = ElementType.Script; + //Special tag, push onto the tag stack if not terminated + if (element.data.charAt(element.data.length - 1) != "/") + this._tagStack.push(ElementType.Script); + } + else if (element.name == "/script") + element.type = ElementType.Script; + else if (element.name == "style") { + element.type = ElementType.Style; + //Special tag, push onto the tag stack if not terminated + if (element.data.charAt(element.data.length - 1) != "/") + this._tagStack.push(ElementType.Style); + } + else if (element.name == "/style") + element.type = ElementType.Style; + if (element.name && element.name.charAt(0) == "/") + element.data = element.name; + } + + //Add all tags and non-empty text elements to the element list + if (element.raw != "" || element.type != ElementType.Text) { + this.parseAttribs(element); + this._elements.push(element); + //If tag self-terminates, add an explicit, separate closing tag + if ( + element.type != ElementType.Text + && + element.type != ElementType.Comment + && + element.type != ElementType.Directive + && + element.data.charAt(element.data.length - 1) == "/" + ) + this._elements.push({ + raw: "/" + element.name + , data: "/" + element.name + , name: "/" + element.name + , type: element.type + }); + } + this._parseState = (tagSep == "<") ? ElementType.Tag : ElementType.Text; + this._current = this._next + 1; + this._prevTagSep = tagSep; + } + + this._buffer = (this._current <= bufferEnd) ? this._buffer.substring(this._current) : ""; + this._current = 0; + + this.writeHandler(); +} + +//Checks the handler to make it is an object with the right "interface" +Parser.prototype.validateHandler = function Parser$validateHandler (handler) { + if ((typeof handler) != "object") + throw new Error("Handler is not an object"); + if ((typeof handler.reset) != "function") + throw new Error("Handler method 'reset' is invalid"); + if ((typeof handler.done) != "function") + throw new Error("Handler method 'done' is invalid"); + if ((typeof handler.writeTag) != "function") + throw new Error("Handler method 'writeTag' is invalid"); + if ((typeof handler.writeText) != "function") + throw new Error("Handler method 'writeText' is invalid"); + if ((typeof handler.writeComment) != "function") + throw new Error("Handler method 'writeComment' is invalid"); + if ((typeof handler.writeDirective) != "function") + throw new Error("Handler method 'writeDirective' is invalid"); +} + +//Writes parsed elements out to the handler +Parser.prototype.writeHandler = function Parser$writeHandler (forceFlush) { + forceFlush = !!forceFlush; + if (this._tagStack.length && !forceFlush) + return; + while (this._elements.length) { + var element = this._elements.shift(); + switch (element.type) { + case ElementType.Comment: + this._handler.writeComment(element); + break; + case ElementType.Directive: + this._handler.writeDirective(element); + break; + case ElementType.Text: + this._handler.writeText(element); + break; + default: + this._handler.writeTag(element); + break; + } + } +} + +Parser.prototype.handleError = function Parser$handleError (error) { + if ((typeof this._handler.error) == "function") + this._handler.error(error); + else + throw error; +} + +//TODO: make this a trully streamable handler +function RssHandler (callback) { + RssHandler.super_.call(this, callback, { ignoreWhitespace: true, verbose: false, enforceEmptyTags: false }); +} +inherits(RssHandler, DefaultHandler); + +RssHandler.prototype.done = function RssHandler$done () { + var feed = { }; + var feedRoot; + + var found = DomUtils.getElementsByTagName(function (value) { return(value == "rss" || value == "feed"); }, this.dom, false); + if (found.length) { + feedRoot = found[0]; + } + if (feedRoot) { + if (feedRoot.name == "rss") { + feed.type = "rss"; + feedRoot = feedRoot.children[0]; // + feed.id = ""; + try { + feed.title = DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.link = DomUtils.getElementsByTagName("link", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.description = DomUtils.getElementsByTagName("description", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.updated = new Date(DomUtils.getElementsByTagName("lastBuildDate", feedRoot.children, false)[0].children[0].data); + } catch (ex) { } + try { + feed.author = DomUtils.getElementsByTagName("managingEditor", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + feed.items = []; + DomUtils.getElementsByTagName("item", feedRoot.children).forEach(function (item, index, list) { + var entry = {}; + try { + entry.id = DomUtils.getElementsByTagName("guid", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.title = DomUtils.getElementsByTagName("title", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.link = DomUtils.getElementsByTagName("link", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.description = DomUtils.getElementsByTagName("description", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.pubDate = new Date(DomUtils.getElementsByTagName("pubDate", item.children, false)[0].children[0].data); + } catch (ex) { } + feed.items.push(entry); + }); + } else { + feed.type = "atom"; + try { + feed.id = DomUtils.getElementsByTagName("id", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.title = DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.link = DomUtils.getElementsByTagName("link", feedRoot.children, false)[0].attribs.href; + } catch (ex) { } + try { + feed.description = DomUtils.getElementsByTagName("subtitle", feedRoot.children, false)[0].children[0].data; + } catch (ex) { } + try { + feed.updated = new Date(DomUtils.getElementsByTagName("updated", feedRoot.children, false)[0].children[0].data); + } catch (ex) { } + try { + feed.author = DomUtils.getElementsByTagName("email", feedRoot.children, true)[0].children[0].data; + } catch (ex) { } + feed.items = []; + DomUtils.getElementsByTagName("entry", feedRoot.children).forEach(function (item, index, list) { + var entry = {}; + try { + entry.id = DomUtils.getElementsByTagName("id", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.title = DomUtils.getElementsByTagName("title", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.link = DomUtils.getElementsByTagName("link", item.children, false)[0].attribs.href; + } catch (ex) { } + try { + entry.description = DomUtils.getElementsByTagName("summary", item.children, false)[0].children[0].data; + } catch (ex) { } + try { + entry.pubDate = new Date(DomUtils.getElementsByTagName("updated", item.children, false)[0].children[0].data); + } catch (ex) { } + feed.items.push(entry); + }); + } + + this.dom = feed; + } + RssHandler.super_.prototype.done.call(this); +} + +/////////////////////////////////////////////////// + +function DefaultHandler (callback, options) { + this.reset(); + this._options = options ? options : { }; + if (this._options.ignoreWhitespace == undefined) + this._options.ignoreWhitespace = false; //Keep whitespace-only text nodes + if (this._options.verbose == undefined) + this._options.verbose = true; //Keep data property for tags and raw property for all + if (this._options.enforceEmptyTags == undefined) + this._options.enforceEmptyTags = true; //Don't allow children for HTML tags defined as empty in spec + if ((typeof callback) == "function") + this._callback = callback; +} + +//**"Static"**// +//HTML Tags that shouldn't contain child nodes +DefaultHandler._emptyTags = { + area: 1 + , base: 1 + , basefont: 1 + , br: 1 + , col: 1 + , frame: 1 + , hr: 1 + , img: 1 + , input: 1 + , isindex: 1 + , link: 1 + , meta: 1 + , param: 1 + , embed: 1 +} +//Regex to detect whitespace only text nodes +DefaultHandler.reWhitespace = /^\s*$/; + +//**Public**// +//Properties// +DefaultHandler.prototype.dom = null; //The hierarchical object containing the parsed HTML +//Methods// +//Resets the handler back to starting state +DefaultHandler.prototype.reset = function DefaultHandler$reset() { + this.dom = []; + this._done = false; + this._tagStack = []; + this._tagStack.last = function DefaultHandler$_tagStack$last () { + return(this.length ? this[this.length - 1] : null); + } +} +//Signals the handler that parsing is done +DefaultHandler.prototype.done = function DefaultHandler$done () { + this._done = true; + this.handleCallback(null); +} +DefaultHandler.prototype.writeTag = function DefaultHandler$writeTag (element) { + this.handleElement(element); +} +DefaultHandler.prototype.writeText = function DefaultHandler$writeText (element) { + if (this._options.ignoreWhitespace) + if (DefaultHandler.reWhitespace.test(element.data)) + return; + this.handleElement(element); +} +DefaultHandler.prototype.writeComment = function DefaultHandler$writeComment (element) { + this.handleElement(element); +} +DefaultHandler.prototype.writeDirective = function DefaultHandler$writeDirective (element) { + this.handleElement(element); +} +DefaultHandler.prototype.error = function DefaultHandler$error (error) { + this.handleCallback(error); +} + +//**Private**// +//Properties// +DefaultHandler.prototype._options = null; //Handler options for how to behave +DefaultHandler.prototype._callback = null; //Callback to respond to when parsing done +DefaultHandler.prototype._done = false; //Flag indicating whether handler has been notified of parsing completed +DefaultHandler.prototype._tagStack = null; //List of parents to the currently element being processed +//Methods// +DefaultHandler.prototype.handleCallback = function DefaultHandler$handleCallback (error) { + if ((typeof this._callback) != "function") + if (error) + throw error; + else + return; + this._callback(error, this.dom); +} +DefaultHandler.prototype.handleElement = function DefaultHandler$handleElement (element) { + if (this._done) + this.handleCallback(new Error("Writing to the handler after done() called is not allowed without a reset()")); + if (!this._options.verbose) { + // element.raw = null; //FIXME: Not clean + //FIXME: Serious performance problem using delete + delete element.raw; + if (element.type == "tag" || element.type == "script" || element.type == "style") + delete element.data; + } + if (!this._tagStack.last()) { //There are no parent elements + //If the element can be a container, add it to the tag stack and the top level list + if (element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive) { + if (element.name.charAt(0) != "/") { //Ignore closing tags that obviously don't have an opening tag + this.dom.push(element); + if (!this._options.enforceEmptyTags || !DefaultHandler._emptyTags[element.name]) { //Don't add tags to the tag stack that can't have children + this._tagStack.push(element); + } + } + } + else //Otherwise just add to the top level list + this.dom.push(element); + } + else { //There are parent elements + //If the element can be a container, add it as a child of the element + //on top of the tag stack and then add it to the tag stack + if (element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive) { + if (element.name.charAt(0) == "/") { + //This is a closing tag, scan the tagStack to find the matching opening tag + //and pop the stack up to the opening tag's parent + var baseName = element.name.substring(1); + if (!this._options.enforceEmptyTags || !DefaultHandler._emptyTags[baseName]) { + var pos = this._tagStack.length - 1; + while (pos > -1 && this._tagStack[pos--].name != baseName) { } + if (pos > -1 || this._tagStack[0].name == baseName) + while (pos < this._tagStack.length - 1) + this._tagStack.pop(); + } + } + else { //This is not a closing tag + if (!this._tagStack.last().children) + this._tagStack.last().children = []; + this._tagStack.last().children.push(element); + if (!this._options.enforceEmptyTags || !DefaultHandler._emptyTags[element.name]) //Don't add tags to the tag stack that can't have children + this._tagStack.push(element); + } + } + else { //This is not a container element + if (!this._tagStack.last().children) + this._tagStack.last().children = []; + this._tagStack.last().children.push(element); + } + } +} + +var DomUtils = { + testElement: function DomUtils$testElement (options, element) { + if (!element) { + return false; + } + + for (var key in options) { + if (key == "tag_name") { + if (element.type != "tag" && element.type != "script" && element.type != "style") { + return false; + } + if (!options["tag_name"](element.name)) { + return false; + } + } else if (key == "tag_type") { + if (!options["tag_type"](element.type)) { + return false; + } + } else if (key == "tag_contains") { + if (element.type != "text" && element.type != "comment" && element.type != "directive") { + return false; + } + if (!options["tag_contains"](element.data)) { + return false; + } + } else { + if (!element.attribs || !options[key](element.attribs[key])) { + return false; + } + } + } + + return true; + } + + , getElements: function DomUtils$getElements (options, currentElement, recurse, limit) { + recurse = (recurse === undefined || recurse === null) || !!recurse; + limit = isNaN(parseInt(limit)) ? -1 : parseInt(limit); + + if (!currentElement) { + return([]); + } + + var found = []; + var elementList; + + function getTest (checkVal) { + return(function (value) { return(value == checkVal); }); + } + for (var key in options) { + if ((typeof options[key]) != "function") { + options[key] = getTest(options[key]); + } + } + + if (DomUtils.testElement(options, currentElement)) { + found.push(currentElement); + } + + if (limit >= 0 && found.length >= limit) { + return(found); + } + + if (recurse && currentElement.children) { + elementList = currentElement.children; + } else if (currentElement instanceof Array) { + elementList = currentElement; + } else { + return(found); + } + + for (var i = 0; i < elementList.length; i++) { + found = found.concat(DomUtils.getElements(options, elementList[i], recurse, limit)); + if (limit >= 0 && found.length >= limit) { + break; + } + } + + return(found); + } + + , getElementById: function DomUtils$getElementById (id, currentElement, recurse) { + var result = DomUtils.getElements({ id: id }, currentElement, recurse, 1); + return(result.length ? result[0] : null); + } + + , getElementsByTagName: function DomUtils$getElementsByTagName (name, currentElement, recurse, limit) { + return(DomUtils.getElements({ tag_name: name }, currentElement, recurse, limit)); + } + + , getElementsByTagType: function DomUtils$getElementsByTagType (type, currentElement, recurse, limit) { + return(DomUtils.getElements({ tag_type: type }, currentElement, recurse, limit)); + } +} + +function inherits (ctor, superCtor) { + var tempCtor = function(){}; + tempCtor.prototype = superCtor.prototype; + ctor.super_ = superCtor; + ctor.prototype = new tempCtor(); + ctor.prototype.constructor = ctor; +} + +exports.Parser = Parser; + +exports.DefaultHandler = DefaultHandler; + +exports.RssHandler = RssHandler; + +exports.ElementType = ElementType; + +exports.DomUtils = DomUtils; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/lib/node-htmlparser.min.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/lib/node-htmlparser.min.js new file mode 100644 index 0000000..5ab1e72 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/lib/node-htmlparser.min.js @@ -0,0 +1,22 @@ +/*********************************************** +Copyright 2010, Chris Winberry . All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +***********************************************/ +/* v1.6.3 */ +(function(){function e(a){this.validateHandler(a);this._handler=a;this.reset()}function n(a){n.super_.call(this,a,{ignoreWhitespace:true,verbose:false,enforceEmptyTags:false})}function g(a,c){this.reset();this._options=c?c:{};if(this._options.ignoreWhitespace==undefined)this._options.ignoreWhitespace=false;if(this._options.verbose==undefined)this._options.verbose=true;if(this._options.enforceEmptyTags==undefined)this._options.enforceEmptyTags=true;if(typeof a=="function")this._callback=a}if(!(typeof require== "function"&&typeof exports=="object"&&typeof module=="object"&&typeof __filename=="string"&&typeof __dirname=="string")){if(this.Tautologistics){if(this.Tautologistics.NodeHtmlParser)return}else this.Tautologistics={};this.Tautologistics.NodeHtmlParser={};exports=this.Tautologistics.NodeHtmlParser}var d={Text:"text",Directive:"directive",Comment:"comment",Script:"script",Style:"style",Tag:"tag"};e._reTrim=/(^\s+|\s+$)/g;e._reTrimComment=/(^\!--|--$)/g;e._reWhitespace=/\s/g;e._reTagName=/^\s*(\/?)\s*([^\s\/]+)/; e._reAttrib=/([^=<>\"\'\s]+)\s*=\s*"([^"]*)"|([^=<>\"\'\s]+)\s*=\s*'([^']*)'|([^=<>\"\'\s]+)\s*=\s*([^'"\s]+)|([^=<>\"\'\s\/]+)/g;e._reTags=/[\<\>]/g;e.prototype.parseComplete=function(a){this.reset();this.parseChunk(a);this.done()};e.prototype.parseChunk=function(a){this._done&&this.handleError(Error("Attempted to parse chunk after parsing already done"));this._buffer+=a;this.parseTags()};e.prototype.done=function(){if(!this._done){this._done=true;if(this._buffer.length){var a=this._buffer;this._buffer= "";a={raw:a,data:this._parseState==d.Text?a:a.replace(e._reTrim,""),type:this._parseState};if(this._parseState==d.Tag||this._parseState==d.Script||this._parseState==d.Style)a.name=this.parseTagName(a.data);this.parseAttribs(a);this._elements.push(a)}this.writeHandler();this._handler.done()}};e.prototype.reset=function(){this._buffer="";this._done=false;this._elements=[];this._next=this._current=this._elementsCurrent=0;this._parseState=d.Text;this._prevTagSep="";this._tagStack=[];this._handler.reset()}; e.prototype._handler=null;e.prototype._buffer=null;e.prototype._done=false;e.prototype._elements=null;e.prototype._elementsCurrent=0;e.prototype._current=0;e.prototype._next=0;e.prototype._parseState=d.Text;e.prototype._prevTagSep="";e.prototype._tagStack=null;e.prototype.parseTagAttribs=function(a){for(var c=a.length,b=0;b"){this._tagStack.pop();if(this._elements.length&&this._elements[this._elements.length-1].type==d.Comment){i=this._elements[this._elements.length-1];i.raw=i.data=(i.raw+b.raw).replace(e._reTrimComment, "");b.raw=b.data="";b.type=d.Text}else b.type=d.Comment}else{b.type=d.Comment;if(this._elements.length&&this._elements[this._elements.length-1].type==d.Comment){i=this._elements[this._elements.length-1];i.raw=i.data=i.raw+b.raw+c;b.raw=b.data="";b.type=d.Text}else b.raw=b.data=b.raw+c}}if(b.type==d.Tag){b.name=h;if(b.raw.indexOf("!--")==0){b.type=d.Comment;delete b.name;j=b.raw.length;if(b.raw.charAt(j-1)=="-"&&b.raw.charAt(j-2)=="-"&&c==">")b.raw=b.data=b.raw.replace(e._reTrimComment,"");else{b.raw+= c;this._tagStack.push(d.Comment)}}else if(b.raw.indexOf("!")==0||b.raw.indexOf("?")==0)b.type=d.Directive;else if(b.name=="script"){b.type=d.Script;b.data.charAt(b.data.length-1)!="/"&&this._tagStack.push(d.Script)}else if(b.name=="/script")b.type=d.Script;else if(b.name=="style"){b.type=d.Style;b.data.charAt(b.data.length-1)!="/"&&this._tagStack.push(d.Style)}else if(b.name=="/style")b.type=d.Style;if(b.name&&b.name.charAt(0)=="/")b.data=b.name}if(b.raw!=""||b.type!=d.Text){this.parseAttribs(b); this._elements.push(b);b.type!=d.Text&&b.type!=d.Comment&&b.type!=d.Directive&&b.data.charAt(b.data.length-1)=="/"&&this._elements.push({raw:"/"+b.name,data:"/"+b.name,name:"/"+b.name,type:b.type})}this._parseState=c=="<"?d.Tag:d.Text;this._current=this._next+1;this._prevTagSep=c}this._buffer=this._current<=a?this._buffer.substring(this._current):"";this._current=0;this.writeHandler()};e.prototype.validateHandler=function(a){if(typeof a!="object")throw Error("Handler is not an object");if(typeof a.reset!= "function")throw Error("Handler method 'reset' is invalid");if(typeof a.done!="function")throw Error("Handler method 'done' is invalid");if(typeof a.writeTag!="function")throw Error("Handler method 'writeTag' is invalid");if(typeof a.writeText!="function")throw Error("Handler method 'writeText' is invalid");if(typeof a.writeComment!="function")throw Error("Handler method 'writeComment' is invalid");if(typeof a.writeDirective!="function")throw Error("Handler method 'writeDirective' is invalid");}; e.prototype.writeHandler=function(a){a=!!a;if(!(this._tagStack.length&&!a))for(;this._elements.length;){a=this._elements.shift();switch(a.type){case d.Comment:this._handler.writeComment(a);break;case d.Directive:this._handler.writeDirective(a);break;case d.Text:this._handler.writeText(a);break;default:this._handler.writeTag(a)}}};e.prototype.handleError=function(a){if(typeof this._handler.error=="function")this._handler.error(a);else throw a;};(function(a,c){var b=function(){};b.prototype=c.prototype; a.super_=c;a.prototype=new b;a.prototype.constructor=a})(n,g);n.prototype.done=function(){var a={},c,b=f.getElementsByTagName(function(k){return k=="rss"||k=="feed"},this.dom,false);if(b.length)c=b[0];if(c){if(c.name=="rss"){a.type="rss";c=c.children[0];a.id="";try{a.title=f.getElementsByTagName("title",c.children,false)[0].children[0].data}catch(h){}try{a.link=f.getElementsByTagName("link",c.children,false)[0].children[0].data}catch(i){}try{a.description=f.getElementsByTagName("description",c.children, false)[0].children[0].data}catch(j){}try{a.updated=new Date(f.getElementsByTagName("lastBuildDate",c.children,false)[0].children[0].data)}catch(m){}try{a.author=f.getElementsByTagName("managingEditor",c.children,false)[0].children[0].data}catch(o){}a.items=[];f.getElementsByTagName("item",c.children).forEach(function(k){var l={};try{l.id=f.getElementsByTagName("guid",k.children,false)[0].children[0].data}catch(q){}try{l.title=f.getElementsByTagName("title",k.children,false)[0].children[0].data}catch(r){}try{l.link= f.getElementsByTagName("link",k.children,false)[0].children[0].data}catch(s){}try{l.description=f.getElementsByTagName("description",k.children,false)[0].children[0].data}catch(t){}try{l.pubDate=new Date(f.getElementsByTagName("pubDate",k.children,false)[0].children[0].data)}catch(u){}a.items.push(l)})}else{a.type="atom";try{a.id=f.getElementsByTagName("id",c.children,false)[0].children[0].data}catch(p){}try{a.title=f.getElementsByTagName("title",c.children,false)[0].children[0].data}catch(v){}try{a.link= f.getElementsByTagName("link",c.children,false)[0].attribs.href}catch(w){}try{a.description=f.getElementsByTagName("subtitle",c.children,false)[0].children[0].data}catch(x){}try{a.updated=new Date(f.getElementsByTagName("updated",c.children,false)[0].children[0].data)}catch(y){}try{a.author=f.getElementsByTagName("email",c.children,true)[0].children[0].data}catch(z){}a.items=[];f.getElementsByTagName("entry",c.children).forEach(function(k){var l={};try{l.id=f.getElementsByTagName("id",k.children, false)[0].children[0].data}catch(q){}try{l.title=f.getElementsByTagName("title",k.children,false)[0].children[0].data}catch(r){}try{l.link=f.getElementsByTagName("link",k.children,false)[0].attribs.href}catch(s){}try{l.description=f.getElementsByTagName("summary",k.children,false)[0].children[0].data}catch(t){}try{l.pubDate=new Date(f.getElementsByTagName("updated",k.children,false)[0].children[0].data)}catch(u){}a.items.push(l)})}this.dom=a}n.super_.prototype.done.call(this)};g._emptyTags={area:1, base:1,basefont:1,br:1,col:1,frame:1,hr:1,img:1,input:1,isindex:1,link:1,meta:1,param:1,embed:1};g.reWhitespace=/^\s*$/;g.prototype.dom=null;g.prototype.reset=function(){this.dom=[];this._done=false;this._tagStack=[];this._tagStack.last=function(){return this.length?this[this.length-1]:null}};g.prototype.done=function(){this._done=true;this.handleCallback(null)};g.prototype.writeTag=function(a){this.handleElement(a)};g.prototype.writeText=function(a){if(this._options.ignoreWhitespace)if(g.reWhitespace.test(a.data))return; this.handleElement(a)};g.prototype.writeComment=function(a){this.handleElement(a)};g.prototype.writeDirective=function(a){this.handleElement(a)};g.prototype.error=function(a){this.handleCallback(a)};g.prototype._options=null;g.prototype._callback=null;g.prototype._done=false;g.prototype._tagStack=null;g.prototype.handleCallback=function(a){if(typeof this._callback!="function")if(a)throw a;else return;this._callback(a,this.dom)};g.prototype.handleElement=function(a){this._done&&this.handleCallback(Error("Writing to the handler after done() called is not allowed without a reset()")); if(!this._options.verbose){delete a.raw;if(a.type=="tag"||a.type=="script"||a.type=="style")delete a.data}if(this._tagStack.last())if(a.type!=d.Text&&a.type!=d.Comment&&a.type!=d.Directive)if(a.name.charAt(0)=="/"){a=a.name.substring(1);if(!this._options.enforceEmptyTags||!g._emptyTags[a]){for(var c=this._tagStack.length-1;c>-1&&this._tagStack[c--].name!=a;);if(c>-1||this._tagStack[0].name==a)for(;c=0&&j.length>=h)return j;if(b&&c.children)c=c.children;else if(c instanceof Array)c=c;else return j;for(m=0;m=0&&j.length>=h)break}return j},getElementById:function(a,c,b){a=f.getElements({id:a},c,b,1);return a.length?a[0]:null},getElementsByTagName:function(a,c,b,h){return f.getElements({tag_name:a},c,b,h)},getElementsByTagType:function(a, c,b,h){return f.getElements({tag_type:a},c,b,h)}};exports.Parser=e;exports.DefaultHandler=g;exports.RssHandler=n;exports.ElementType=d;exports.DomUtils=f})(); \ No newline at end of file diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/package.json b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/package.json new file mode 100644 index 0000000..ced4c0a --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/package.json @@ -0,0 +1,23 @@ +{ + "name": "htmlparser" + , "description": "Forgiving HTML/XML/RSS Parser in JS for *both* Node and Browsers" + , "version": "1.6.2" + , "author": "Chris Winberry " + , "contributors": [] + , "repository": { + "type": "git" + , "url": "git://github.com/tautologistics/node-htmlparser.git" + } + , "bugs": { + "mail": "chris@winberry.net" + , "web": "http://github.com/tautologistics/node-htmlparser/issues" + } + , "os": [ "linux", "darwin", "freebsd" ] + , "directories": { "lib": "./lib/" } + , "main": "./lib/node-htmlparser" + , "engines": { "node": ">=0.1.33" } + , "licenses": [{ + "type": "MIT" + , "url": "http://github.com/tautologistics/node-htmlparser/raw/master/LICENSE" + }] +} diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/profile.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/profile.js new file mode 100644 index 0000000..c5a474e --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/profile.js @@ -0,0 +1,63 @@ +//node --prof --prof_auto profile.js +//deps/v8/tools/mac-tick-processor v8.log +var sys = require("sys"); +var fs = require("fs"); +var http = require("http"); +var htmlparser = require("./node-htmlparser"); +var libxml = require('./libxmljs'); + +var testNHP = true; //Should node-htmlparser be exercised? +var testLXJS = true; //Should libxmljs be exercised? +var testIterations = 100; //Number of test loops to run + +var testHost = "nodejs.org"; //Host to fetch test HTML from +var testPort = 80; //Port on host to fetch test HTML from +var testPath = "/api.html"; //Path on host to fetch HTML from + +function getMillisecs () { + return((new Date()).getTime()); +} + +function timeExecutions (loops, func) { + var start = getMillisecs(); + + while (loops--) + func(); + + return(getMillisecs() - start); +} + +var html = ""; +http.createClient(testPort, testHost) + .request("GET", testPath, { host: testHost }) + .addListener("response", function (response) { + if (response.statusCode == "200") { + response.setEncoding("utf8"); + response.addListener("data", function (chunk) { + html += chunk; + }).addListener("end", function() { + var timeNodeHtmlParser = !testNHP ? 0 : timeExecutions(testIterations, function () { + var handler = new htmlparser.DefaultHandler(function(err, dom) { + if (err) + sys.debug("Error: " + err); + }); + var parser = new htmlparser.Parser(handler); + parser.parseComplete(html); + }) + + var timeLibXmlJs = !testLXJS ? 0 : timeExecutions(testIterations, function () { + var dom = libxml.parseHtmlString(html); + }) + + if (testNHP) + sys.debug("NodeHtmlParser: " + timeNodeHtmlParser); + if (testLXJS) + sys.debug("LibXmlJs: " + timeLibXmlJs); + if (testNHP && testLXJS) + sys.debug("Difference: " + ((timeNodeHtmlParser - timeLibXmlJs) / timeLibXmlJs) * 100); + }); + } + else + sys.debug("Error: got response status " + response.statusCode); + }) + .end(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.html b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.html new file mode 100644 index 0000000..3543adc --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.html @@ -0,0 +1,107 @@ + + + + + Node.js HTML Parser + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.js new file mode 100644 index 0000000..c59393c --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.js @@ -0,0 +1,75 @@ +/*********************************************** +Copyright 2010, Chris Winberry . All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +***********************************************/ + +var sys = require("sys"); +var fs = require("fs"); +var htmlparser = require("./lib/node-htmlparser"); + +var testFolder = "./tests"; +var chunkSize = 5; + +var testFiles = fs.readdirSync(testFolder); +var testCount = 0; +var failedCount = 0; +for (var i in testFiles) { + testCount++; + var fileParts = testFiles[i].split("."); + fileParts.pop(); + var moduleName = fileParts.join("."); + var test = require(testFolder + "/" + moduleName); + var handlerCallback = function handlerCallback (error) { + if (error) + sys.puts("Handler error: " + error); + } + var handler = (test.type == "rss") ? + new htmlparser.RssHandler(handlerCallback, test.options) + : + new htmlparser.DefaultHandler(handlerCallback, test.options) + ; + var parser = new htmlparser.Parser(handler); + parser.parseComplete(test.html); + var resultComplete = handler.dom; + var chunkPos = 0; + parser.reset(); + while (chunkPos < test.html.length) { + parser.parseChunk(test.html.substring(chunkPos, chunkPos + chunkSize)); + chunkPos += chunkSize; + } + parser.done(); + var resultChunk = handler.dom; + var testResult = + sys.inspect(resultComplete, false, null) === sys.inspect(test.expected, false, null) + && + sys.inspect(resultChunk, false, null) === sys.inspect(test.expected, false, null) + ; + sys.puts("[" + test.name + "\]: " + (testResult ? "passed" : "FAILED")); + if (!testResult) { + failedCount++; + sys.puts("== Complete =="); + sys.puts(sys.inspect(resultComplete, false, null)); + sys.puts("== Chunked =="); + sys.puts(sys.inspect(resultChunk, false, null)); + sys.puts("== Expected =="); + sys.puts(sys.inspect(test.expected, false, null)); + } +} +sys.puts("Total tests: " + testCount); +sys.puts("Failed tests: " + failedCount); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.min.html b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.min.html new file mode 100644 index 0000000..2ec9e8f --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.min.html @@ -0,0 +1,107 @@ + + + + + Node.js HTML Parser + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.min.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.min.js new file mode 100644 index 0000000..d32c3aa --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/runtests.min.js @@ -0,0 +1,75 @@ +/*********************************************** +Copyright 2010, Chris Winberry . All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +***********************************************/ + +var sys = require("sys"); +var fs = require("fs"); +var htmlparser = require("./lib/node-htmlparser.min"); + +var testFolder = "./tests"; +var chunkSize = 5; + +var testFiles = fs.readdirSync(testFolder); +var testCount = 0; +var failedCount = 0; +for (var i in testFiles) { + testCount++; + var fileParts = testFiles[i].split("."); + fileParts.pop(); + var moduleName = fileParts.join("."); + var test = require(testFolder + "/" + moduleName); + var handlerCallback = function handlerCallback (error) { + if (error) + sys.puts("Handler error: " + error); + } + var handler = (test.type == "rss") ? + new htmlparser.RssHandler(handlerCallback, test.options) + : + new htmlparser.DefaultHandler(handlerCallback, test.options) + ; + var parser = new htmlparser.Parser(handler); + parser.parseComplete(test.html); + var resultComplete = handler.dom; + var chunkPos = 0; + parser.reset(); + while (chunkPos < test.html.length) { + parser.parseChunk(test.html.substring(chunkPos, chunkPos + chunkSize)); + chunkPos += chunkSize; + } + parser.done(); + var resultChunk = handler.dom; + var testResult = + sys.inspect(resultComplete, false, null) === sys.inspect(test.expected, false, null) + && + sys.inspect(resultChunk, false, null) === sys.inspect(test.expected, false, null) + ; + sys.puts("[" + test.name + "\]: " + (testResult ? "passed" : "FAILED")); + if (!testResult) { + failedCount++; + sys.puts("== Complete =="); + sys.puts(sys.inspect(resultComplete, false, null)); + sys.puts("== Chunked =="); + sys.puts(sys.inspect(resultChunk, false, null)); + sys.puts("== Expected =="); + sys.puts(sys.inspect(test.expected, false, null)); + } +} +sys.puts("Total tests: " + testCount); +sys.puts("Failed tests: " + failedCount); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/snippet.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/snippet.js new file mode 100644 index 0000000..2f54b36 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/snippet.js @@ -0,0 +1,15 @@ +//node --prof --prof_auto profile.js +//deps/v8/tools/mac-tick-processor v8.log +var sys = require("sys"); +var htmlparser = require("./node-htmlparser"); + +var html = "text"; + +var handler = new htmlparser.DefaultHandler(function(err, dom) { + if (err) + sys.debug("Error: " + err); + else + sys.debug(sys.inspect(dom, false, null)); +}, { enforceEmptyTags: true }); +var parser = new htmlparser.Parser(handler); +parser.parseComplete(html); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/01-basic.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/01-basic.js new file mode 100644 index 0000000..57de7dc --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/01-basic.js @@ -0,0 +1,57 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Basic test"; +exports.html = "The TitleHello world"; +exports.expected = + [ { raw: 'html' + , data: 'html' + , type: 'tag' + , name: 'html' + , children: + [ { raw: 'title' + , data: 'title' + , type: 'tag' + , name: 'title' + , children: [ { raw: 'The Title', data: 'The Title', type: 'text' } ] + } + , { raw: 'body' + , data: 'body' + , type: 'tag' + , name: 'body' + , children: + [ { raw: 'Hello world' + , data: 'Hello world' + , type: 'text' + } + ] + } + ] + } + ]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/02-single_tag_1.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/02-single_tag_1.js new file mode 100644 index 0000000..8af04d9 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/02-single_tag_1.js @@ -0,0 +1,35 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Single Tag 1"; +exports.html = "
text
"; +exports.expected = + [ { raw: 'br', data: 'br', type: 'tag', name: 'br' } + , { raw: 'text', data: 'text', type: 'text' } + ]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/03-single_tag_2.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/03-single_tag_2.js new file mode 100644 index 0000000..beae642 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/03-single_tag_2.js @@ -0,0 +1,36 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Single Tag 2"; +exports.html = "
text
"; +exports.expected = + [ { raw: 'br', data: 'br', type: 'tag', name: 'br' } + , { raw: 'text', data: 'text', type: 'text' } + , { raw: 'br', data: 'br', type: 'tag', name: 'br' } + ]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/04-unescaped_in_script.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/04-unescaped_in_script.js new file mode 100644 index 0000000..1a23385 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/04-unescaped_in_script.js @@ -0,0 +1,52 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Unescaped chars in script"; +exports.html = ""; +exports.expected = +[ { raw: 'head' + , data: 'head' + , type: 'tag' + , name: 'head' + , children: + [ { raw: 'script language="Javascript"' + , data: 'script language="Javascript"' + , type: 'script' + , name: 'script' + , attribs: { language: 'Javascript' } + , children: + [ { raw: 'var foo = ""; alert(2 > foo); var baz = 10 << 2; var zip = 10 >> 1; var yap = \"<<>>>><<\";' + , data: 'var foo = ""; alert(2 > foo); var baz = 10 << 2; var zip = 10 >> 1; var yap = \"<<>>>><<\";' + , type: 'text' + } + ] + } + ] + } +]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/05-tags_in_comment.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/05-tags_in_comment.js new file mode 100644 index 0000000..79fdd8c --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/05-tags_in_comment.js @@ -0,0 +1,44 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Special char in comment"; +exports.html = ""; +exports.expected = +[ { raw: 'head' + , data: 'head' + , type: 'tag' + , name: 'head' + , children: + [ { raw: ' commented out tags Test' + , data: ' commented out tags Test' + , type: 'comment' + } + ] + } +]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/06-comment_in_script.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/06-comment_in_script.js new file mode 100644 index 0000000..7737f38 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/06-comment_in_script.js @@ -0,0 +1,44 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Script source in comment"; +exports.html = ""; +exports.expected = +[ { raw: 'script' + , data: 'script' + , type: 'script' + , name: 'script' + , children: + [ { raw: 'var foo = 1;' + , data: 'var foo = 1;' + , type: 'comment' + } + ] + } +]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/07-unescaped_in_style.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/07-unescaped_in_style.js new file mode 100644 index 0000000..fe4efad --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/07-unescaped_in_style.js @@ -0,0 +1,45 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Unescaped chars in style"; +exports.html = ""; +exports.expected = +[ { raw: 'style type="text/css"' + , data: 'style type="text/css"' + , type: 'style' + , name: 'style' + , attribs: { type: 'text/css' } + , children: + [ { raw: '\n body > p\n { font-weight: bold; }' + , data: '\n body > p\n { font-weight: bold; }' + , type: 'text' + } + ] + } +]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/08-extra_spaces_in_tag.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/08-extra_spaces_in_tag.js new file mode 100644 index 0000000..84192af --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/08-extra_spaces_in_tag.js @@ -0,0 +1,45 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Extra spaces in tag"; +exports.html = "<\n font \n size='14' \n>the text<\n / \nfont \n>"; +exports.expected = +[ { raw: '\n font \n size=\'14\' \n' + , data: 'font \n size=\'14\'' + , type: 'tag' + , name: 'font' + , attribs: { size: '14' } + , children: + [ { raw: 'the text' + , data: 'the text' + , type: 'text' + } + ] + } +]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/09-unquoted_attrib.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/09-unquoted_attrib.js new file mode 100644 index 0000000..3ad54e6 --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/09-unquoted_attrib.js @@ -0,0 +1,45 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Unquoted attributes"; +exports.html = "the text"; +exports.expected = +[ { raw: 'font size= 14' + , data: 'font size= 14' + , type: 'tag' + , name: 'font' + , attribs: { size: '14' } + , children: + [ { raw: 'the text' + , data: 'the text' + , type: 'text' + } + ] + } +]; + +})(); diff --git a/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/10-singular_attribute.js b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/10-singular_attribute.js new file mode 100644 index 0000000..37897dc --- /dev/null +++ b/rails/node_modules/jquery/node_modules/htmlparser/pulls/node-htmlparser/tests/10-singular_attribute.js @@ -0,0 +1,39 @@ +(function () { + +function RunningInNode () { + return( + (typeof require) == "function" + && + (typeof exports) == "object" + && + (typeof module) == "object" + && + (typeof __filename) == "string" + && + (typeof __dirname) == "string" + ); +} + +if (!RunningInNode()) { + if (!this.Tautologistics) + this.Tautologistics = {}; + if (!this.Tautologistics.NodeHtmlParser) + this.Tautologistics.NodeHtmlParser = {}; + if (!this.Tautologistics.NodeHtmlParser.Tests) + this.Tautologistics.NodeHtmlParser.Tests = []; + exports = {}; + this.Tautologistics.NodeHtmlParser.Tests.push(exports); +} + +exports.name = "Singular attribute"; +exports.html = "