<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nicollet.Net</title>
	<atom:link href="http://www.nicollet.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.nicollet.net</link>
	<description>Go crazy with computers</description>
	<lastBuildDate>Thu, 04 Mar 2010 21:38:05 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PHP 5.3 Closures as Block Literals?</title>
		<link>http://www.nicollet.net/2010/03/php-closures-as-block-literals/</link>
		<comments>http://www.nicollet.net/2010/03/php-closures-as-block-literals/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 21:38:05 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Closure]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[PHP 5.3]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1285</guid>
		<description><![CDATA[I explained earlier a few things about writing reusable CSS code, and how it interacted with PHP. Let&#8217;s start with this basic HTML for generating two columns, with the right one being flexible and resizing to fill all available space:
&#60;div class="col2"&#62;
  &#60;div class="col2-l"&#62;
    [Content of left column]
  &#60;/div&#62;
  &#60;div [...]]]></description>
			<content:encoded><![CDATA[<p>I explained earlier a few things about <a href="http://www.nicollet.net/2010/02/reusable-css/" target="_blank">writing reusable CSS code</a>, and how it interacted with PHP. Let&#8217;s start with this basic HTML for generating two columns, with the right one being flexible and resizing to fill all available space:</p>
<pre style="padding-left: 30px;"><span style="color: #0000ff;">&lt;div class="col2"&gt;</span>
  <span style="color: #008000;">&lt;div class="col2-l"&gt;</span>
    [Content of left column]
  <span style="color: #008000;">&lt;/div&gt;</span>
  <span style="color: #ff6600;">&lt;div class="col2-r"&gt;</span>
    <span style="color: #ff0000;">&lt;div class="col2-ri"&gt;</span>
      [Content of right column]
    <span style="color: #ff0000;">&lt;/div&gt;</span><span style="color: #800080;">
</span><span style="color: #ff6600;">  &lt;/div&gt;
</span>  <span style="color: #800080;">&lt;div class="clearer"&gt;&lt;/div&gt;
</span><span style="color: #0000ff;">&lt;/div&gt;

</span><span style="color: #0000ff;">.col2    { }</span>
<span style="color: #008000;">.col2-l  { float: left ; padding: 0 ; margin: 0 ; width: 120px }</span>
<span style="color: #ff6600;">.col2-r  { padding: 0 0 0 120px ; margin: 0 ; width:auto }</span>
<span style="color: #ff0000;">.col2-ri { float: left ; width : 100% }</span>
<span style="color: #800080;">.clearer { clear: both }</span></pre>
<h4>Elementary PHP</h4>
<p>How does this translate to PHP? Basically as a series of constants (plus documentation detailing what the column HTML should look like):</p>
<pre style="padding-left: 30px;">class CSS_Col2
{
  const ROOT = "col2";
  const LEFT = "col2-l";
  const RIGHT = "col2-r";
  const RIGHT_INNER = "col2-ri";
}</pre>
<p>This serves both as documentation for the existence of this component, and as an entry in the auto-completion tool to avoid typing incorrect classes by mistake. However, you still have to get the actual code right:</p>
<pre style="padding-left: 30px;">&lt;div class="&lt;?=CSS_Col2::ROOT?&gt;"&gt;
  &lt;div class="&lt;?=CSS_Col2::LEFT?&gt;"&gt;
    [20 lines of left column here]
  &lt;/div&gt;
  &lt;div class="&lt;?=CSS_Col2::RIGHT?&gt;"&gt;
    &lt;div class="&lt;?=CSS_Col2::RIGHT_INNER?&gt;"&gt;
      [40 lines of right column here]
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;?CSS::CLEARER?&gt;
&lt;/div&gt;</pre>
<p>Did I write everything correctly? Did I forget or misplace a clearer? Forgetting about the inner container in the right column is an easy mistake, and you won&#8217;t notice it until you put a clearing element in that column. And if your script is long enough, you won&#8217;t be able to see which opening tag matches which closing tag. Surely there must be a way to improve this.</p>
<h4>Using HTML constants</h4>
<p>A possibility is using constants to contain the relevant HTML:</p>
<pre style="padding-left: 30px;">class CSS_Col2
{
  // as above ...
  const _BEGIN_LEFT = '&lt;div class="col2"&gt;&lt;div class="col2-l"&gt;';
  const _BEGIN_RIGHT = '&lt;/div&gt;&lt;div class="col2-r"&gt;&lt;div class="col2-ri"&gt;';
  const _END = '&lt;/div&gt;&lt;/div&gt;&lt;div class="clearer"&gt;&lt;/div&gt;';
}</pre>
<p>This makes code shorter, and you can&#8217;t mismatch or misplace tags as easily:</p>
<pre style="padding-left: 30px;">&lt;?=CSS_Col2::_BEGIN_LEFT?&gt;
  [20 lines of left column here]
&lt;?=CSS_Col2::_BEGIN_RIGHT?&gt;
  [40 lines of right column here]
&lt;?=CSS_Col2::_END?&gt;</pre>
<p>However, all benefits of a nice and clean HTML editor are lost, because HTML constants don&#8217;t react as code, and there is therefore no validation performed. At least Eclipse could detect mismatching open/closing tags on raw HTML. Now, if you forget to &#8220;_END&#8221; your columns, your life is pain.</p>
<h4>Using helpers</h4>
<p>A common technique is to use a helper function for such rendering tasks. The function accepts some arguments that let it configure what ought to be displayed, then renders the wrapper HTML and inserts the data. Staying within the previous code:</p>
<pre style="padding-left: 30px;">class View_Helper_Col2
{
  static function Render(<span style="color: #008000;">$left</span>, <span style="color: #ff0000;">$right</span>)
  {
    ?&gt;
&lt;div class="&lt;?=CSS_Col2::ROOT?&gt;"&gt;
  &lt;div class="&lt;?=CSS_Col2::LEFT?&gt;"&gt;
    <span style="color: #008000;">&lt;?php call_user_func($left); ?&gt;</span>
  &lt;/div&gt;
  &lt;div class="&lt;?=CSS_Col2::RIGHT?&gt;"&gt;
    &lt;div class="&lt;?=CSS_Col2::RIGHT_INNER?&gt;"&gt;
      <span style="color: #ff0000;">&lt;?php call_user_func($right); ?&gt;</span>
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;?CSS::CLEARER?&gt;
&lt;/div&gt;&lt;?
  }
}</pre>
<p>I used callbacks here to do the rendering, because they are the most versatile (it sure beats having to instantiate a &#8220;renderable&#8221; class for each column). This approach provides the obvious benefit that now the entire rendering is taken care of by a single function, so there is no risk of forgetting or misplacing a tag, and the auto-completion tool can now help check which arguments are provided and in what order.</p>
<p>Still, this means that one should create two functions to render the two columns, and that any necessary data should be made available to them (due to the absence of closures in PHP &lt; 5.3, this often means calling a member function of a view object containing the appropriate data). In the Zend Framework, for instance, one would just write two helpers, and provide them as callbacks knowing that they will have access to the data of the current view:</p>
<pre style="padding-left: 30px;">&lt;?php
  $this-&gt;render2col(
    array($this,'myLeftCol'),
    array($this,'myRightCol')
  );
?&gt;</pre>
<p>Of course, it&#8217;s questionable whether moving a three-line for-each loop to a helper of its own actually increases the readability of the code. If defining a new class for every view, there&#8217;s the possibility of defining the columns as member functions within that same class, but it&#8217;s still somewhat awkward.</p>
<h4>Helpers and Closures</h4>
<p>PHP 5.3 introduces closures and optional arguments. This means that one can now write the behavior inline:</p>
<pre style="padding-left: 30px;"><code><span style="color: #000000;"><span style="color: #0000bb;">&lt;?php
 $self </span><span style="color: #007700;">= &amp;</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">;
 </span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">render2col</span><span style="color: #007700;">(
   function() use(</span><span style="color: #0000bb;">$self</span><span style="color: #007700;">)
   {
     </span><span style="color: #0000bb;">?&gt;</span>&lt;h1&gt;<span style="color: #0000bb;">&lt;?=esc</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$self</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">user</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">name</span><span style="color: #007700;">)</span><span style="color: #0000bb;">?&gt;</span>&lt;/h1&gt;<span style="color: #0000bb;">&lt;?php
   </span><span style="color: #007700;">},
   function() use(</span><span style="color: #0000bb;">$self</span><span style="color: #007700;">)
   {
     </span><span style="color: #0000bb;">?&gt;</span>&lt;ul&gt;<span style="color: #0000bb;">&lt;?php </span><span style="color: #007700;">foreach (</span><span style="color: #0000bb;">$self</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">items </span><span style="color: #007700;">as </span><span style="color: #0000bb;">$item</span><span style="color: #007700;">): </span><span style="color: #0000bb;">?&gt;
      </span> &lt;li&gt;<span style="color: #0000bb;">&lt;?php $self</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">render</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$item</span><span style="color: #007700;">); </span><span style="color: #0000bb;">?&gt;</span>&lt;/li&gt;
     <span style="color: #0000bb;">&lt;?php </span><span style="color: #007700;">endforeach; </span><span style="color: #0000bb;">?&gt;</span>&lt;/ul&gt;<span style="color: #0000bb;">&lt;?php
   </span><span style="color: #007700;">}
 );</span><span style="color: #0000bb;"></span></span></code></pre>
<p>However, making those functions inline creates a new issue: its not so obvious anymore what exactly a function is doing (because it&#8217;s too far away from the original call to the helper function). This can be solved by using a command pattern (while simultaneously noticing that one can get rid of the use keyword by providing $self as an argument (the helper does that):</p>
<pre style="padding-left: 30px;"><code><span style="color: #000000;"><span style="color: #0000bb;">&lt;?php
 View_Col2</span><span style="color: #007700;">::</span><span style="color: #0000bb;">start</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">)

 -&gt;</span><span style="color: #0000bb;">left</span><span style="color: #007700;">(function(</span></span></code><code><span style="color: #000000;"><span style="color: #0000bb;">$view</span></span></code><code><span style="color: #000000;"><span style="color: #007700;">){
   </span><span style="color: #0000bb;">?&gt;</span>&lt;h1&gt;<span style="color: #0000bb;">&lt;?=esc</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$view</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">user</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">name</span><span style="color: #007700;">)</span><span style="color: #0000bb;">?&gt;</span>&lt;/h1&gt;<span style="color: #0000bb;">&lt;?php
</span><span style="color: #007700;"> })

 -&gt;</span><span style="color: #0000bb;">right</span><span style="color: #007700;">(function(</span></span></code><code><span style="color: #000000;"><span style="color: #0000bb;">$view</span></span></code><code><span style="color: #000000;"><span style="color: #007700;">){
   </span><span style="color: #0000bb;">?&gt;</span>&lt;ul&gt;<span style="color: #0000bb;">&lt;?php </span><span style="color: #007700;">foreach (</span><span style="color: #0000bb;">$view</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">items </span><span style="color: #007700;">as </span><span style="color: #0000bb;">$item</span><span style="color: #007700;">): </span><span style="color: #0000bb;">?&gt;
 </span>    &lt;li&gt;<span style="color: #0000bb;">&lt;?php $view</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">render</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$item</span><span style="color: #007700;">); </span><span style="color: #0000bb;">?&gt;</span>&lt;/li&gt;
   <span style="color: #0000bb;">&lt;?php </span><span style="color: #007700;">endforeach; </span><span style="color: #0000bb;">?&gt;</span>&lt;/ul&gt;<span style="color: #0000bb;">&lt;?php
 </span><span style="color: #007700;">})

 -&gt;</span><span style="color: #0000bb;">render</span><span style="color: #007700;">();
</span></span></code></pre>
<p>Labels are now clearly mentioned, allowing empty lines to be inserted to separate the columns without forgetting what they are, so that the code looks cleaner overall.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/03/php-closures-as-block-literals/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lorem Ipsum</title>
		<link>http://www.nicollet.net/2010/03/lorem-ipsum/</link>
		<comments>http://www.nicollet.net/2010/03/lorem-ipsum/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 21:06:56 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Imperative]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Lorem Ipsum]]></category>
		<category><![CDATA[Useless]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1280</guid>
		<description><![CDATA[Lorem Ipsum is a sample phrase used as a filler in typesetting, to illustrate how some text would look. Here&#8217;s a sample paragraph:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex [...]]]></description>
			<content:encoded><![CDATA[<p>Lorem Ipsum is a sample phrase used as a filler in typesetting, to illustrate how some text would look. Here&#8217;s a sample paragraph:</p>
<blockquote><p><em>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</em></p></blockquote>
<p>This approach to filler text is superior in many ways to most alternatives:</p>
<ul>
<li>It&#8217;s long, certainly longer than &#8220;Test&#8221; or &#8220;AAA&#8221;, so it can fill several lines (and test whether there is an unexpected length limit when saving the data).</li>
<li>Unlike random strings of characters copy-pasted several times, it is split into words of uneven length, spaces between words do not align horizontally or vertically.</li>
<li>It is readily recognizable as random text by any typesetter (or developer) worth its salt.</li>
</ul>
<p>A typical testing strategy, when filling forms by hand, is to copy-paste one or two Lorem Ipsum paragraph to test such things as how the text area reacts, whether it is saved correctly, and so on.</p>
<p>Lorem Ipsum does have some limitations:</p>
<ul>
<li>It&#8217;s written in latin, so it fits nicely in the ASCII range of characters. As such, it does not test for Unicode support.</li>
<li>It contains no quotes of any kind, so no testing of database escaping processing either.</li>
<li>It contains no HTML-specific characters like &lt; or &amp;, so HTML character escaping is not tested either.</li>
<li>For that matter, it does not contain exceedingly long words that would overflow a single line, so you cannot test for this kind of overflow either.</li>
<li>Sometimes, you want to auto-linkify links and URLs.</li>
<li>Sometimes, Skype turns numbers into &#8230; clickable numbers.</li>
</ul>
<p>I need to test these things on my web applications, so I&#8217;ve developed my own version of a &#8220;<strong>Modern Lorem Ipsum</strong>&#8220;:</p>
<blockquote><p><em>Lorem &lt;a href=&#8221;javascript:document.write(&#8221;)&#8221;&gt;ipsum&lt;/a&gt; dòlor sit àmet, consectetur adipisicing élit, sèd do eiusmod tempor incididunt ut labore &amp; dolore magna aliqua. &lt;hr/&gt;Ut enim@minim.com veniam, quis nostrud exercitation `&#8221;ullamco laboris nisi &amp; aliquip ex æ commodo consequat. Duis aute irure dolor 01 23 45 67 89 in reprehenderit in voluptate velit esse cillum dolore `eu fugiat https://nulla.biz/pariatur. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa </em></p>
<p><em>Excepteur [u]sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit &#8216;anim id est laborum.[u] </em><em>Lorem&#8221; ipsum dòlor sit àmet, consectetur adipisicing élit, sèd do eiusmod tempor http://incididunt.ut.com/labore &amp; dolore magna aliqua. &lt;b&gt;Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex æ commodo consequat.&lt;/b&gt; &#8220;Duis aute irure dolor in &#8216;reprehenderit in voluptate velit &#8212; esse cillum dolore eu fugiat nulla pariatur.</em></p></blockquote>
<p>Feel free to copy-paste it away. Wordpress certainly does seem to have a hard time with these long lines in post bodies—I wonder if it happens in comments as well <img src='http://www.nicollet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/03/lorem-ipsum/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Reusable CSS</title>
		<link>http://www.nicollet.net/2010/02/reusable-css/</link>
		<comments>http://www.nicollet.net/2010/02/reusable-css/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 04:01:23 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1274</guid>
		<description><![CDATA[Woe unto CSS, for it provides no refactoring-friendly tools! The CSS beast has neither functions nor variables, and its definition of inheritance is perverted beyond words. Pain and suffering await those who hope to keep their CSS from one project to the next, or even share the CSS between pages on a single website!
Consider two [...]]]></description>
			<content:encoded><![CDATA[<p>Woe unto CSS, for it provides no refactoring-friendly tools! The CSS beast has neither functions nor variables, and its definition of inheritance is perverted beyond words. Pain and suffering await those who hope to keep their CSS from one project to the next, or even share the CSS between pages on a single website!</p>
<p>Consider two simple pages: the home page has a small navigation bar (selected by <code>#navig</code>) at the top of the screen, while the catalog page as a larger navigation (still selected by <code>#navig</code>). Each page includes a different <code>layout.css</code> stylesheet, so everything&#8217;s fine. Except that now, anything defined in a layout has to be copied over by hand to the other layouts if you want to reuse them. Ouch.</p>
<p>Does that example sound extreme? It certainly is! But the danger of page-specific stylesheets remains: if you won&#8217;t be stepping on your own toes with something as trivial as <code>#navig</code>, perhaps <code>.book</code> will mean two different things on two different pages?</p>
<h4>Rule Zero : Keep all your CSS Together</h4>
<p>This might seem a bit harsh, especially if you have truckloads of CSS floating around and don&#8217;t want to slow down the initial loading time of your page, or the time spent resolving collisions. However,</p>
<ul>
<li>This rule will make it easier to factor out common bits of CSS, leading to an overall smaller set of stylesheets.</li>
<li>The number of HTTP requests matters as much as the bandwidth, so delivering all your CSS as a single, minified, gzipped blob is often a <a href="http://developer.yahoo.com/performance/rules.html#num_http">good performance idea</a>.</li>
<li>The entire point is to make it harder to create page-specific rules, so that you don&#8217;t make a rule page-specific by mistake, and strive to make most of your rules page-independent.</li>
</ul>
<p>I usually place all of my CSS in correctly named files in a directory on my server, then have the server generate a single, <code>all.css</code> master file that <code>@import</code>s the other stylesheets by path. <em>This means Firebug&#8217;s CSS browser will correctly identify the source file for any given rule.</em> When the code moves to a production server, the auto-generated master file becomes a pre-generated/minified/gzipped resource, and can even be moved to a CDN for improved performance.</p>
<p>On the other hand, keeping all your code in one place will only help you see collisions, it will not actually help you solve them.</p>
<p>Fortunately, we can look to other languages for tips and trick on how to make code easier to reuse. The fundamental observation is that you cannot use something if you don&#8217;t give it a name. One would expect CSS identifiers and classes to serve the same function, and indeed it does work in simple cases:</p>
<pre style="padding-left: 30px;"><code>a.important { font-weight: bold }</code></pre>
<p>Now, you have the <code>important</code> «function», that you «call» on an anchor element to make it appear important. Bam! Instant reusability. Using an identifier instead of a class still allows reuse on distinct pages, but restricts reuse within a single page.</p>
<h4>Rule One : Document your «Functions»</h4>
<p>You cannot reuse code if you cannot find it, and even if you don&#8217;t forget about it someone else on the team might be completely unaware that it even exists. So you should somehow document that the <code>important</code> class exists. My personal, PHP-friendly preference, is to have a &#8220;Css&#8221; class with all those nice classes available:</p>
<pre style="padding-left: 30px;"><code>class Css
{
  <span style="color: #008000;">/* a.important : make a link important */</span>
  const IMPORTANT = "important";
}</code></pre>
<p>Then, you can reuse them when you see fit to do so:</p>
<pre style="padding-left: 30px;"><code>Click &lt;a href="&lt;?=$url?&gt;" class="&lt;?=Css::IMPORTANT?&gt;"&gt;here&lt;/a&gt;</code></pre>
<p>That&#8217;s just personal preference—any way of documenting your CSS classes is fine as long as it&#8217;s somewhere everyone can see it. In fact, I have a nice set of PHP helpers lying around to bind jQuery UI CSS effects to my code, thereby documenting what jQuery UI can do without having to dive into the stylesheets every single time.</p>
<p>The real problem appears when you have more than one «argument». A typical example is the list of links with a &#8220;selected&#8221; link: the graphical effect applies to the list, to the elements of that list, and to the content of those elements, which leads to several rules selecting different elements.</p>
<pre style="padding-left: 30px;"><code>ul#navig { margin: 0 ; padding: 0}
ul#navig li { list-style-type: none }
ul#navig li.selected a { font-weight: bold ; color: black }</code></pre>
<p>This kind of structure cannot be documented simply by stating that the <code>ul#navig</code> element is going to become a pretty list, because without the <code>li.selected</code> in there there will be no «pretty» worth mentioning.</p>
<p>I document this as follows:</p>
<pre style="padding-left: 30px;"><code><span style="color: #008000;">/*
  &lt;ul id="navig"&gt;
    &lt;li&gt;&lt;a&gt;Item&lt;/a&gt;&lt;li&gt;
    &lt;li class="selected"&gt;&lt;a&gt;Item&lt;/a&gt;&lt;li&gt;
    &lt;li&gt;&lt;a&gt;Item&lt;/a&gt;&lt;li&gt;
  &lt;/ul&gt;
*/</span>
ul#navig { margin: 0 ; padding: 0}
ul#navig li { list-style-type: none }
ul#navig li.selected a { font-weight: bold ; color: black }</code></pre>
<p>Why not document it in the PHP code, then? IMO, a CSS designer to write a quick <code>const FOO = "bar";</code> line in PHP, but not an HTML helper that turns an array of links into pretty list HTML. CSS designers write the CSS (with documented HTML) and PHP developers turn that into HTML helpers.</p>
<p style="text-align: center;">&lt;/acronym soup&gt;</p>
<p>Another important element of code reuse is the notion of encapsulation, and in particular the existence of &#8220;private data&#8221; that is part of the program, but can only be accessed by some parts.</p>
<p>There is no such thing with CSS. There are two reasons for this. The main reason is that being sloppy with selectors is commonplace:</p>
<pre style="padding-left: 30px;"><span style="color: #008000;">/*
  &lt;div id="userList"&gt;
    &lt;ul class="users"&gt;
      ...
    &lt;/ul&gt;
    &lt;a&gt;New&lt;/a&gt; |
    &lt;a&gt;Edit&lt;/a&gt; |
    &lt;a&gt;Delete&lt;/a&gt;
  &lt;/div&gt;
*/</span>
#userList a { color: #FF9900 ; text-decoration: none }
#userList a:hover { text-decoration: underline }</pre>
<p>The three links in the user list component («new», «edit» and «delete») will appear in orange without underlining, as expected and documented. The unexpected and non-documented consequence of this code is that all links within the list of users will be orange without underlining as well.</p>
<h4>Rule Two : Only Select what you Need to Select</h4>
<p>The typical consequence of sloppy selectors is that «insert component A into component B» operations utterly destroy the formatting of component A. The typical designer reaction to such <em>graphicalypse</em> is «Darn, component B destroyed some property of component A, so let&#8217;s add some rules to component A to reverse the damage!»</p>
<p>Bad idea. It makes the code longer, and only hides the actual problem (along with any symptoms that only appear in specific cases). The real solution is to make sure selectors only select what they need to select.</p>
<p>One way of doing so is to use the «<code>&gt;</code>» selector, as it restricts the selection to only children of the initially selected element. This would work:</p>
<pre style="padding-left: 30px;"><code>#userList &gt; a { color: #FF9900 ; text-decoration: none }
#userList &gt; a:hover { text-decoration: underline }</code></pre>
<p>Of course, it wouldn&#8217;t work in IE6, but <a href="http://idroppedie6.com/">who cares about IE6 anymore</a>?</p>
<p>The general approach is to use specific classes for those elements that must be affected:</p>
<pre style="padding-left: 30px;"><code><span style="color: #008000;">/*
  &lt;div id="userList"&gt;
    &lt;ul&gt;
      ...
    &lt;/ul&gt;
    &lt;a class="userList-link"&gt;New&lt;/a&gt; |
    &lt;a class="userList-link"&gt;Edit&lt;/a&gt; |
    &lt;a class="userList-link&gt;Delete&lt;/a&gt;
  &lt;/div&gt;
*/</span>
a.userList-link { color: #FF9900 ; text-decoration: none }
a.userList-link:hover { text-decoration: underline }</code></pre>
<p>If anyone uses that <code>userList-link</code> class in their code (and your naming conventions were clean enough), they had it coming.</p>
<h4>Rule Three : Choose Proper Naming Conventions</h4>
<p>It is quite important to remain consistent in your naming practices, especially since you now need to identify, for any given identifier and/or class:</p>
<ul>
<li>If it represents a «function» (<code>#userList</code>), or if it helps select a specific «argument» (<code>.userList-link</code>).</li>
<li>In the latter situation, what function the argument corresponds to (so that you can look for its definition).</li>
</ul>
<p>My preference is to use <code>camelCase</code> names (classes or identifiers) for functions, and <code>camelCase-camelCase</code> names for arguments, where the first half is the name of the function. The CSS would then be gathered in a <code>camelCase.css</code> stylesheet named after the function, with a documentation of the expected HTML at the top, hence making it much easier to find and reuse.</p>
<p>Now that you have access to functions, you will probably want to use them to implement reusable «components» — standalone pieces of HTML and CSS that represent atoms of information.</p>
<p>At some point, you will have to make components interact (if only to respect each other on the page layout). All of this will be hell if component A uses normal block layout rules, component B is floating to the left and component C is positioned absolutely.</p>
<h4>Rule Four : a Component Should only Care about its Inner Layout</h4>
<p>As soon as a component starts to care about outer layout concepts such as margin, position, floating or clearing, you will be in a world of pain. This is because such concepts depend on where the component appears, and as such are not easy to reuse.</p>
<p>I split my CSS code into components and bones:</p>
<ul>
<li>
<p style="font-size:1em"><strong>Components</strong>. These are reusable atoms. They do not care about their outer layout at all, so they never specify anything like margin, position, floating, clearing, display mode or anything that might cause them to interact differently with their surroundings on the page.</p>
<p style="font-size:1em">They may specify a width and height if they wish, but it is discouraged (a component that can adapt to any geometry is easier to use). They can specify anything they want in terms of border, padding, font, color, background, font, and any inner properties they need.</p>
</li>
<li>
<p style="font-size:1em"><strong>Bones</strong>. These are elements found inside the components that handle the layout of the component contents themselves. They can and should make appropriate assumptions about what bones can be found within a component and how they should interact to result in the layout you need to see.</p>
</li>
</ul>
<p>A nice finishing touch is to make the component <code>overflow : hidden</code>, because the last thing you need is a component&#8217;s skeleton sticking out from its skin and interacting with other elements.</p>
<p>I repeat: <strong>never allow the contents of a component to stick out of that component</strong>!</p>
<p>In particular, if you have a component with floating elements inside, make sure you add a clearer element at the bottom of the component to have it resize with its contents.</p>
<p>In practice, I assume every function argument to be a bone, and every function to be a component. The situations where a function acts as a bone are so rare, and the results so difficult to reuse (so you&#8217;ve added a <code>float:left</code> to an element, where are you going to put it?), that I don&#8217;t really take them into account. The Component-Bone approach tends to solve almost everything elegantly, as long as you&#8217;re clever about where a component begins and a bone ends.</p>
<p>For instance, if you&#8217;re laying out a list of comments for a blog, you are probably going to have a «comment list» component with «comment» bones that are laid out on top of one another with appropriate margins, borders and paddings. The contents of every «comment» bone will be a «comment» component, with bones representing the picture, name, date and comment body, laid out cleanly without that component.</p>
<p>Whether the <code>.commentList-comment</code> is placed on the same element as <code>.comment</code> is something you can decide for yourself. What is essential is that, in order for the comment style to be reusable independently of the comment list style, all outer layout information should be in <code>.commentList-comment</code>, not in <code>.comment</code>.</p>
<p>Good.</p>
<p>Now, before I finish, do you remember when I said earlier that component B could be mangled by component A for two different reasons? The second reason happens to be inheritance. Everyone knows inheritance is bad for reuse. Right?</p>
<p>What happens is that, if you define a font size, color or family in a given element, then all descendants of that element will get the same font size, color and family (unless some CSS rule changes them). That&#8217;s inheritance: the value of the property in the child element is inherited from the parent element.</p>
<h4>Rule Five: Only Change Inheritable Properties on your own Content</h4>
<p>It&#8217;s impossible to define the entire list of inheritable properties at the root of every single component in your web side, however convenient it may be. Keeping everything in sync is very difficult, if not impossible. It is far easier, by comparison, to restrict such changes to only those areas of a component where the content is closely controlled and guaranteed not to contain any other components.</p>
<p>I believe there are basically three kinds of areas in any given page that are actually worth being paid attention to. These are:</p>
<ul>
<li><strong>Layout</strong> areas. These are those component-in-component-in-component places where touching an inheritable property can get you <span style="text-decoration: line-through;">killed</span> annoyed.</li>
<li><strong>Text</strong> areas. Those contain no components, but they might still contain paragraphs, links, headings, images in a typical «rich text editor» fashion. If you change one property (such as the color of text), be ready to change all the related properties (the color of links) to keep a consistent appearance.</li>
<li><strong>Line</strong> areas. These contain a short bit of text without any other tags. You don&#8217;t have to worry about changing properties here.</li>
</ul>
<p>Every component should document, for every piece of content that should be filled from outside the component, whether it is a layout, text or line area. For instance:</p>
<pre style="padding-left: 30px;"><span style="color: #008000;">/*
  &lt;div class="comment"&gt;
    &lt;span class="comment-author"&gt;...&lt;/span&gt;
    &lt;div class="comment-contents"&gt;&lt;p&gt;...&lt;/p&gt;&lt;/div&gt;
    &lt;div class="comment-reply"&gt;
      ...
    &lt;/div&gt;
  &lt;/div&gt;
*/</span></pre>
<p>Here, a span (can only contain inline elements or text) represents a line area, a div-with-paragraph represents a text area (may contain several paragraphs, of course) and a normal div represents a layout area. This tells me, for instance, «don&#8217;t even think about putting a component in the comment contents, or I&#8217;ll clobber their stylesheet beyond recognition.»</p>
<p>Depending on the kind of web site you are building, other kinds of areas may be useful to you, such as forms.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/02/reusable-css/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JavaScript (Un)Maintenance Trick</title>
		<link>http://www.nicollet.net/2010/02/javascript-unmaintenance-trick/</link>
		<comments>http://www.nicollet.net/2010/02/javascript-unmaintenance-trick/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 18:47:07 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Useless]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1270</guid>
		<description><![CDATA[You&#8217;re hunting your codebase for bugs, and doing some refactoring and cleanup along the way. You stumble across a classic WTF, if (x == true), and decide to replace it with the shorter if (x).
The trouble is that you&#8217;re playing with JavaScript here, and the two are not the same.
This is the story of why [...]]]></description>
			<content:encoded><![CDATA[<p>You&#8217;re hunting your codebase for bugs, and doing some refactoring and cleanup along the way. You stumble across a classic WTF, <code>if (x == true)</code>, and decide to replace it with the shorter <code>if (x)</code>.</p>
<p>The trouble is that you&#8217;re playing with JavaScript here, and the two are not the same.</p>
<h4>This is the story of why <code>[] == ![]</code> is true.</h4>
<p>First, the logical-not operator «!» is defined quite simply by <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" target="_blank">the ECMA standard</a> (§11.4.9) as evaluating its argument, converting it to a boolean, and returning true if it was false, and false otherwise. Converting the argument to a boolean is defined (§9.2) as returning <code>true</code> for objects. Since arrays are objects, it makes sense that <code>![]</code> evaluates to <code>false</code>.</p>
<p>Second, the comparison operator «==» is defined by the standard (§11.9.3) in a rather complex way: first, if its two operands are not of the same type, some type conversion occurs. The first step is that, if an operand is a boolean, it is turned into a number. So, <code>![]</code> becomes <code>0</code>.</p>
<p>The next step is, if one operand is a number and the other is an object, to turn the object into a primitive. This conversion is defined (§9.1) as calling the [[DefaultValue]] internal method, which in turn is defined (§8.12.8) as calling methods <code>valueOf()</code> and <code>toString()</code> until one of them returns a number or string. In the case of an array, the former returns the array itself (§15.2.4.4) and the latter calls join() (§15.4.4.2), which will concatenate all values inside the array, separated by commas (§15.4.4.5).</p>
<p>In the case of an empty array, this yields the empty string.</p>
<p>The third and final step is, if an operand is a number and the other is a string, to turn the string into a number (through a lengthy process described in §9.3.1) and compare the two. An empty string becomes zero, so the comparison is true.</p>
<p>Does your brain hurt, yet?</p>
<p>Back to the original question: <code>if([] == true)</code> does not run, but <code>if([])</code> does.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/02/javascript-unmaintenance-trick/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to build a page client-side?</title>
		<link>http://www.nicollet.net/2010/02/jquery-build-page/</link>
		<comments>http://www.nicollet.net/2010/02/jquery-build-page/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 19:47:00 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Imperative]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1264</guid>
		<description><![CDATA[The basic philosophy of jQuery is to start with some existing HTML sent over vanilla HTTP by the server. That HTML should be all you need (so that people without a JavaScript-enabled browser can still use the web site). Then, jQuery enhances that HTML by adding new behavior (usually changing the properties of existing elements, [...]]]></description>
			<content:encoded><![CDATA[<p>The basic philosophy of jQuery is to start with some existing HTML sent over vanilla HTTP by the server. That HTML should be all you need (so that people without a JavaScript-enabled browser can still use the web site). Then, jQuery enhances that HTML by adding new behavior (usually changing the properties of existing elements, sometimes adding new elements).</p>
<p>This is very useful for small pieces of behavior, but writing complete and complex components is hard for several reasons:</p>
<ul>
<li>A partial view strategy is required on the server side to insert the appropriate HTML in the appropriate location (as opposed to leaving an empty hole and having the component generate its own HTML).</li>
<li>If the behavior of your component is complex, then there will be a lot of parsing going on. A typical example would be sorting a table by a &#8220;date&#8221; column—since the date format in itself cannot be parsed (culture-dependent and may contain &#8220;Yesterday&#8221;, &#8220;13 seconds ago&#8221; and similar shortcuts).</li>
<li>Sometimes, the server needs to add information that is not visible, but is needed by the JavaScript. The format for sending this data (attribute, hidden field&#8230;) is difficult to document and type-check.</li>
<li>Selecting precisely the right fields in a blob of HTML, without hitting any others, is hard, especially for components that may later contain sub-components. Class-based selection is slow, id-based selection involves heavy logistics to move the identifiers around, and complete traversal takes a while and breaks if the HTML changes.</li>
</ul>
<p>My preferred approach to JavaScript components is to receive JSON-formatted data from the server (easy to parse) from which I construct the DOM elements I need and capture them at the same time.</p>
<pre style="background: #ffffff none repeat scroll 0% 0%; color: #000000; padding-left: 30px;"><span style="color: #000084; font-weight: bold;">var</span> $comment = $(<span style="color: #0000ff;">'&lt;div&gt;&lt;img/&gt;&lt;span/&gt;&lt;div/&gt;&lt;/div&gt;'</span>)
  .addClass(<span style="color: #0000ff;">"comment"</span>);

<span style="color: #000084; font-weight: bold;">var</span> obj =
{
  $self : $comment,

  $img  : $comment.children(<span style="color: #0000ff;">'img'</span>)
          .attr(<span style="color: #0000ff;">'src'</span>,data.imgUrl),

  $name : $comment.children(<span style="color: #0000ff;">'span'</span>)
          .text(data.authorName)
          .addClass(<span style="color: #0000ff;">'authorName'</span>),

  $body : $comment.children(<span style="color: #0000ff;">'div'</span>)
};

$.each(data.text,<span style="color: #000084; font-weight: bold;">function</span>(k,t){
  $(<span style="color: #0000ff;">'&lt;p/&gt;'</span>).text(t).appendTo(obj.$body);
});

<span style="color: #000084; font-weight: bold;">return</span> obj;</pre>
<p>The point is that you then have access, through the returned object, to all the relevant elements within the comment, so that you may target them with effects without any risky selector-based magic. Besides, if the HTML format of comments changes, you will only have to change the code above and nothing else.</p>
<p>And of course, using <code>text()</code> escapes any dangerous HTML you might have.</p>
<p>To make the above appear in your code, all you have to do is:</p>
<pre style="background: #ffffff none repeat scroll 0% 0%; color: #000000; padding-left: 30px;"><span style="color: #000084; font-weight: bold;">var</span> $commentsList = $(<span style="color: #0000ff;">'#my-comments-list'</span>);

$.each (comments, <span style="color: #000084; font-weight: bold;">function</span>(i,c){
  <span style="color: #000084; font-weight: bold;">var</span> obj = $comments[i] = renderComment(c);
  obj.$self.appendTo($commentsList);
});</pre>
<p>This is usually where you hit a performance wall, because this is one of <a href="http://www.artzstudio.com/2009/04/jquery-performance-rules/" target="_blank">the slowest ways of using jQuery</a> on a web page.</p>
<p>I&#8217;ve been in this situation recently on a smallish website that basically displays a list of contacts invited to various events as a 10-column/300-row table that includes additional functionality such as:</p>
<ul>
<li>Dynamically add or remove new rows (with server-side confirms)</li>
<li>Rows are grouped together, and groups can be collapsed and expanded</li>
<li>Clicking on rows opens a modal editor, modifications are propagated back to the table</li>
<li>The data and formatting for certain rows depend on some other rows</li>
</ul>
<p>The initial approach was exactly as described above: every cell was constructed as <code>$('&lt;td/&gt;')</code>, classes and attributes were applied to it, then all cells were inserted into rows constructed as <code>$('&lt;tr/&gt;')</code>, and these in turn were appended to the table tbody. Since some parts of the table were clickable to achieve various effects, jQuery&#8217;s <code>click()</code> function was used to add the appropriate event handlers, and the event handlers were closures that contained all relevant information about what row had to be collapsed or what element had to be removed.</p>
<p>The average time for rendering all of this was a solid <strong>2200</strong>ms on Firefox 3.5, which felt about as dynamic as a dead tortoise nailed to a slab of concrete. For comparison purposes, rendering the data server-side and sending it to the client took about <strong>390</strong>ms on average (arguably, the server would have scaling issues as it would have to render the HTML for all clients, but still).</p>
<p><strong>2200</strong>ms means about <strong>7</strong>ms per row. The problem here isn&#8217;t that the jQuery code is slow, but rather that it&#8217;s executed so many times to add up to a pretty large number.</p>
<p>My first attempt to improve performance was to avoid constructing rows cell by cell, instead building the final HTML of the row in one shot and then selecting clickable elements inside the row through their class to apply event handlers. Rows were then inserted into the table body using jQuery&#8217;s DOM functions. The new rendering time was <strong>1800</strong>ms, which was not as good as I hoped my improvement to be.</p>
<p>The second step was to move away from selecting clickable elements to apply event handlers. This meant that I could either insert the event handler code in the HTML (but this meant no closures, so I would have to rely on global, non-garbage-collected behavior) or add a click event to the entire table and determine what element had been clicked (and parsing the DOM for information about what to do with the click, which was annoying).</p>
<p>I went with the first way, rewriting my code as global handlers and eliminating all the select-child-with-class overhead. Rows were still constructed independently and inserted independently. The improvement was sensible, as the rendering time was then <strong>980</strong>ms.</p>
<p>The last wave of optimizations consisted in making sure the HTML for the entire table body was generated in one shot and concatenated as an array (using <code>[a,b,c].join('')</code> instead of <code>a+b+c</code>). This creates 5223-element array, concatenated into a string containing 72357 characters, which is then inserted into the table body using jQuery&#8217;s <code>html()</code> function. The entire process, including preliminary processing of the data to be displayed, takes about <strong>160</strong>m (a 13.7× performance increase).</p>
<p>The change was mostly moving from this design pattern:</p>
<pre style="background: #ffffff none repeat scroll 0% 0%; color: #000000; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; padding-left: 30px;"><span style="color: #000084; font-weight: bold;">function</span> renderRow(data)
{
  $tr = $(<span style="color: #0000ff;">'&lt;tr/&gt;'</span>);

  $(<span style="color: #0000ff;">'&lt;td/&gt;'</span>)
    .addClass(<span style="color: #0000ff;">'name'</span>)
    .append($(<span style="color: #0000ff;">'&lt;a/&gt;'</span>)
      .text(data.name)
      .click(<span style="color: #000084; font-weight: bold;">function</span>(){ frobnicate(data.id); }))
    .appendTo($tr);

  <span style="color: #808080;">// ...</span>

  <span style="color: #000084; font-weight: bold;">return</span> $tr;
}</pre>
<p>To this one:</p>
<pre style="background: #ffffff none repeat scroll 0% 0%; color: #000000; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; padding-left: 30px;"><span style="color: #000084; font-weight: bold;">function</span> renderRow(data,html)
{
  html.push(
    <span style="color: #0000ff;">'&lt;tr&gt;&lt;td&gt;'</span>,
    <span style="color: #0000ff;">'&lt;a href="javascript:frobnicate('</span>,
    data.id,
    <span style="color: #0000ff;">')"&gt;'</span>,
    esc(data.name),
    <span style="color: #0000ff;">'&lt;/a&gt;&lt;/td&gt;'</span>,
    <span style="color: #808080;">// ...</span>
    <span style="color: #0000ff;">'&lt;/tr&gt;'</span>
  );
}</pre>
<p>Again, this is an extreme situation where page-generation goes way out of hand because a lot of rows are generate—the net benefit, as far as rendering a single row is concerned, is around 6ms. If your page contains only a small number of complex components, you can ignore the performance issues to get the components done, and only optimize if it turns out to be noticeable.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/02/jquery-build-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>That DOM removal thing, again</title>
		<link>http://www.nicollet.net/2010/01/that-dom-removal-thing-again/</link>
		<comments>http://www.nicollet.net/2010/01/that-dom-removal-thing-again/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 06:56:26 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1255</guid>
		<description><![CDATA[Earlier this month, I pondered what looked like a bug in JavaScript/DOM/jQuery: removing an element from the DOM with jQuery (either manually with remove() or by setting the html() of its parent to something else) kept most of the data bound to the element around, but removed all event handlers from it. You could then [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier this month, I pondered what looked like <a href="http://www.nicollet.net/2010/01/dom-removal-and-events/" target="_blank">a bug in JavaScript/DOM/jQuery</a>: removing an element from the DOM with jQuery (either manually with remove() or by setting the html() of its parent to something else) kept most of the data bound to the element around, but removed all event handlers from it. You could then re-insert the element, but its event handlers would be lost.</p>
<p>I then gathered from several sources, such as <a href="http://stackoverflow.com/questions/2027706/why-do-registered-events-disappear-when-an-element-is-removed-from-dom">Stack Overflow</a>, that this is a jQuery issue (or rather, feature) and not a JavaScript one.</p>
<p>The <a href="http://javascript.crockford.com/memory/leak.html">underlying cause</a> is explained by Douglas Crockford:</p>
<blockquote><p>When a DOM object contains a reference to a    JavaScript object (such an    event handling function), and when that JavaScript object contains a reference    to that DOM object, then a cyclic structure is formed. This is not in itself    a problem. At such time as there are no other references to the DOM object and    the event handler, then the garbage collector (an automatic memory resource    manager) will reclaim them both, allowing their space to be reallocated. The    JavaScript garbage collector understands about cycles and is not confused by    them. Unfortunately, IE&#8217;s DOM is not managed by JScript. It has its own memory    manager that does not understand about cycles and so gets very confused. As    a result, when cycles occur, memory reclamation does not occur.</p></blockquote>
<p>A common solution to this problem is to remove the cycles when the element is removed from the DOM. Since a major source of cycles in your average jQuery program is the presence of event handlers, then removing the event handlers when an element is removed from the DOM solves the problem most of the time.</p>
<p>With the release of jQuery 1.4, the new documentation for <a href="http://api.jquery.com/remove/" target="_blank"><code>.remove()</code></a> makes mention of this fact:</p>
<blockquote><p>In addition to the elements themselves, all bound events and jQuery data  associated with the elements are removed.</p></blockquote>
<p>The documentation for <a href="http://api.jquery.com/html/" target="_blank"><code>.html()</code></a> still makes no mention of this. If you want to remove an element and keep all the goodies you bound to it, jQuery 1.4 provides you with <a href="http://api.jquery.com/detach/" target="_blank"><code>.detach()</code></a>:</p>
<blockquote><p>The <code>.detach()</code> method is the same as <code>.remove()</code>, except that <code>.detach()</code> keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/01/that-dom-removal-thing-again/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shouldn&#8217;t Happen&#8230;</title>
		<link>http://www.nicollet.net/2010/01/shouldnt-happen/</link>
		<comments>http://www.nicollet.net/2010/01/shouldnt-happen/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 20:29:26 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Imperative]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Psychology]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1252</guid>
		<description><![CDATA[Design and development is turning the great unknown chaos into tiny bits of controlled functionality with promises about what the result will be, and expectations about what the input should be.
There is an interesting duality between two categories of expectations, depending on whether they are the responsibility of the user, or of the programmer.
User errors [...]]]></description>
			<content:encoded><![CDATA[<p>Design and development is turning the great unknown chaos into tiny bits of controlled functionality with promises about what the result will be, and expectations about what the input should be.</p>
<p>There is an interesting duality between two categories of expectations, depending on whether they are the responsibility of the user, or of the programmer.</p>
<p>User errors are classic mistakes involving incorrect input, such as attempting to load a file that does not have the right format, or visiting a web site that does not exist, or entering an incorrect email address. A program is expected to, at the very least, gracefully handle these situations (because nobody likes errors) and the best programs are actively designed to reduce the possibility of error though appropriate user interface choices.</p>
<p>Programmer errors are the most frequent ones, but most of there are luckily caught by a compiler (or, in the case of the less lucky interpreted languages, the parser). The basic idea is that if you expect a function parameter to be an integer, and you tell your compiler, then static analysis will determine that you will receive a string argument, and the <span style="text-decoration: line-through;">universe will collapse</span> build will fail.</p>
<h3>Static Analysis</h3>
<p>Static analysis can be very smart. It can prove beyond any doubts <a href="http://www.astree.ens.fr/" target="_blank">complex properties</a> about complex software written in obscenely low-level code (such as C with inline assembly). The problem if that working with a static analysis tool can add unusual constraints on the developers themselves: the halting problem dictates that no tool can safely predict the behavior of a program, so any given tool will either have false negatives (undetected bugs) or false positives (safe code reported as dangerous) and the general trend for static analysis tools is to avoid any false negatives at the cost of false positives.</p>
<p>The quality of a static analysis tool is determined by how hard it is to write code without false positives (usually done by manually coding around the blind spots of the tool).</p>
<p>Static analysis tools have two problems. One, they&#8217;re not available for every single language and platform out there. Some of use are still using languages with <code>eval()</code>, throwing Java exception-safety out the window because we find it too constraining, doing without those pesky type systems and generally making a childish fuss about those &#8220;warning&#8221; thingies. Two, static analysis tools can only check constraints that are described by the developer in some form, such as assertions, preconditions, postconditions, type annotations or some other kind of attribute added to the code.</p>
<p>So, if you forget to &#8220;assert&#8221; it, nobody is going to check it for you. For instance, no tool is going to warn you that you unwittingly leak a credit card number to a third party.</p>
<h3>The Elephant Statue</h3>
<p>In a sense, predicting user errors is the mirror activity of gathering specifications. Both force you to think about all possible situations your software will face, and decide what should happen: maybe you have to display an error, maybe you will have to tread the input in a clever but predictable way, or maybe you will have to rework your process to prevent that situation from happening.</p>
<p>This is akin to creating an elephant statue by starting with a block of stone and carving out everything but the elephant. Deciding what your users can do implicitly defines what your users cannot do. Depending on the situation, you may guide your design with either approach.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/01/shouldnt-happen/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DOM removal and events</title>
		<link>http://www.nicollet.net/2010/01/dom-removal-and-events/</link>
		<comments>http://www.nicollet.net/2010/01/dom-removal-and-events/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 21:12:25 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1248</guid>
		<description><![CDATA[Let&#8217;s try something&#8230; go to a page with jQuery enabled (such as this one), and run the following code in your Javascript debugger console (such as Firebug):
var button =
  $('&#60;button&#62;Click me&#60;/button&#62;')
  .click(function(){alert('Clicked!')})
  .appendTo('body')
In case you were wondering, this creates a brand new button, causes it to display a &#8220;Clicked!&#8221; message box when [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s try something&#8230; go to a page with jQuery enabled (<a href="http://nicollet.net/files/articles/jstut/" target="_blank">such as this one</a>), and run the following code in your Javascript debugger console (such as Firebug):</p>
<pre style="padding-left: 30px;"><span>var button =
  $('&lt;button&gt;Click me&lt;/button&gt;')
  .click(function(){alert('Clicked!')})
  .appendTo('body')</span></pre>
<p>In case you were wondering, this creates a brand new button, causes it to display a &#8220;Clicked!&#8221; message box when it&#8217;s clicked, and appends it to the document you are viewing.</p>
<p>Click on the button that just appeared : the message box appears. Not very surprising.</p>
<p>Now, run the following code on the same page :</p>
<pre style="padding-left: 30px;"><span>$('body').html('');
button.appendTo('body')</span></pre>
<p>As expected, everything on the page, including the button, disappears. However, the button is still referenced by the <code>button</code> variable, so it sticks around and we can append it back to the document. And indeed, it does appear on the page.</p>
<p>Click on the button again. This time, no message box appears.</p>
<p>I honestly have no idea <strong>why</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/01/dom-removal-and-events/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Interest(ing) rates</title>
		<link>http://www.nicollet.net/2010/01/interesting-rates/</link>
		<comments>http://www.nicollet.net/2010/01/interesting-rates/#comments</comments>
		<pubDate>Wed, 06 Jan 2010 18:35:53 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Psychology]]></category>
		<category><![CDATA[Useless]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1244</guid>
		<description><![CDATA[The most common way of investing money is putting it in a savings account. You lend a fixed amount of money to someone, and they pay interest over that money at a predetermined rate. Let&#8217;s say you lend 1,000 € at an interest rate of 3%, paid every year: at the end of the year, [...]]]></description>
			<content:encoded><![CDATA[<p>The most common way of investing money is putting it in a savings account. You lend a fixed amount of money to someone, and they pay interest over that money at a predetermined rate. Let&#8217;s say you lend 1,000 € at an interest rate of 3%, paid every year: at the end of the year, you would receive 30 € as payment for your lending. You would spend these on fine wine or nice clothes and wait until the next year to get another 30 €, and so on.</p>
<p>Savings accounts work on the basis of <strong>simple interest</strong> : what you get paid is a linear function of both time and money. Lend for half a year? 3% ÷ 2 = 1.5% Lend for two years? 3% ×2 = 6%</p>
<p>An important thing to bear in mind is that interest is paid at fixed intervals, for instance at the beginning of January. You don&#8217;t have to spend those 30 € : you can them on the savings account and earn simple interest on them after a year (3% of 30 € is 0.90 €).</p>
<p>Using this strategy, lending for two years is done at a 6.09% rate instead of 6%, because you get interest on interest. This is known as <strong>compound interest</strong> : what you get paid is an exponential function of time. Lend for two years ? (+3%)² = +6.09% Lend for three years ? (+3%)³ = +9,27%</p>
<p>The mathematical justification is that, with a 3% interest, your total amount of money is multiplied by 1.03 every year:</p>
<p style="padding-left: 30px;">1,000 + 30 = 1,000 + 3% of 1,000 = 1,000 + 0.03 × 1,000 = 1.03 × 1,000</p>
<p>So, after two years, the amount is multiplied by 1.03 two times, and so on.</p>
<p style="padding-left: 30px;">1,060.90 = 1.03 × 1,030 = 1.03 × 1.03 × 1,000</p>
<p>In short, <strong>percentages have a multiplicative effect</strong>.</p>
<p>And now, pop quiz : I&#8217;ve gained +5% weight over the winter holidays. What percentage of my weight do I have to lose to be back to normal ?</p>
<p>If you answered -5%, you missed the point. Multiplicative effect means the total change of weight would be +5% × -5% = 1.05 × 0.95 = 0.9975 = <strong>-0.25%</strong>. I would be losing too much weight !</p>
<p>The correct answer was 1 ÷ 1.05 = <strong>-4.76%</strong>.</p>
<p>Similarly, if the number of graduates of a given school increases by +10% on year one and +25% on year two, the total increase is +37.5% and not +35%.</p>
<h3>Duality</h3>
<p>This is where mathematicians (and computer scientists) use an interesting little concept called duality. Percentages are numbers that are easy to understand, but hard to combine. We can transform them into something that is a little bit harder to understand, but easier to combine.</p>
<p>The traditional way to transform multiplication into addition is to exponentiate, due to an interesting property of the exponential function:</p>
<p style="padding-left: 30px;">exp(a) ×exp(b) = exp(a + b)</p>
<p>So, I wish to find a percentage operator (§) such that:</p>
<ul>
<li>we conserve some values, 0§ = 0% and 100§ = 100%</li>
<li>applying A§, then B§, is equivalent to applying (A+B)§</li>
</ul>
<p>Then this uniquely defines an operator which is called exponential percentage:</p>
<p style="padding-left: 30px;">A§ = B%  ↔  A = 100 × log(1 + B ÷ 100) ÷ log(2)</p>
<p>Some common values:</p>
<table border="0">
<tbody>
<tr>
<td>0% = 0§</td>
<td>+100% = +100§</td>
<td>-100% = -∞§</td>
<td>200% = 158.4§</td>
</tr>
<tr>
<td>+1% = +1.4§</td>
<td>+99% = +99.2§</td>
<td>-1% = -1.4§</td>
<td>-99% = -664§</td>
</tr>
<tr>
<td>+10% = +13.7§</td>
<td>+90% = +92.6§</td>
<td>-10% = -15.2§</td>
<td>-90% = -332§</td>
</tr>
<tr>
<td>+25% = +32.2§</td>
<td>+75% = +80.7§</td>
<td>+50% = +58.4§</td>
<td>-50% = -100§</td>
</tr>
</tbody>
</table>
<p><a href="http://www.nicollet.net/wp-content/uploads/2010/01/percent.png"><img class="aligncenter size-full wp-image-1246" title="percent" src="http://www.nicollet.net/wp-content/uploads/2010/01/percent.png" alt="percent" width="393" height="287" /></a></p>
<p>So, if I gained +5§ weight over the holidays, I can lose -5§ weight and be back to where I started, and if a number increases by 10§, then by 25§, it increases by 35§ overall.</p>
<p>And of course, a yearly interest rate of 4.2§ = 3% compounded over ten years is 42§ = 34%.</p>
<h3>No Free Lunch</h3>
<p>Normal percentage rules make compounding hard, but it&#8217;s reasonably easy to estimate a percentage based on a fraction. Exponential percentage rules make compounding easy, but evaluating a percentage based on real figures is harder.</p>
<p>In practice, compounding happens less often than evaluating, so humans use normal percentage rules. And computers are good at compounding through multiplication, so they don&#8217;t need exponentiation.</p>
<p>Duality does have some other uses, though. For instance, there&#8217;s the duality between two representations of complex numbers:</p>
<p style="padding-left: 30px;">a + <strong>i</strong>b = r exp <strong>i</strong>θ</p>
<p>The cartesian (a,b) notation makes it easier to add numbers, but multiplication is harder:</p>
<p style="padding-left: 30px;">a + <strong>i</strong>b + c + <strong>i</strong>d = (a+c) + <strong>i</strong>(b+d)</p>
<p>The polar (r,θ) notation makes it easier to multiply numbers, but addition is harder:</p>
<p style="padding-left: 30px;">r exp <strong>i</strong>θ × s exp <strong>i</strong>φ = (r × s) exp <strong>i</strong>(θ+φ)</p>
<p>For mathematically-oriented computer scientists, duality is a gold mine, because it lets one reduce a complex problem in one area to a simpler problem in another area (whether simpler means faster, as in the case of <a href="http://en.wikipedia.org/wiki/Fast_Fourier_transform" target="_blank">FFT</a>, or easier to think about)..</p>
<h3>The Law of DSLs</h3>
<p>There&#8217;s one common duality that is fundamental in the computer world: the correspondence between data and code. In a fit of narcissism, let me sit wisely atop a tall mountain to announce <strong>Nicollet&#8217;s Law of Domain Specific Languages</strong>:</p>
<blockquote><p>Any sufficiently complex data processing algorithm is as an interpreter for a small domain-specific language, and the data being processed is a program executed by the interpreter.</p></blockquote>
<p>In some cases, this law only complicates things further. In many cases, however, the different angle it provides leads to many advantages, one of them being to transform a non-programming concept (such as an accounting file format) into a concept programmers are familiar with (a programming language).</p>
<p>A minimalist language design culture is enough to grasp several interesting concepts about executing code, which can be quite handy when processing data:</p>
<h4>1. Compile to Bytecode</h4>
<p>Interpreters don&#8217;t execute a string of characters. They tokenize that string, turn the tokens into an abstract syntax tree representing operations, functions and variables, then turn that syntax tree into a sequence of small, executable operations. That sequence is then fed into a virtual machine (or further compiled to machine code) to perform the actual operations.</p>
<p>If the input data for your algorithm is very complex, you can begin on the other side: what will the algorithm <strong>do</strong> with the data? Will it be inserting the data into a database? Constructing a data object from bits and pieces? What you are looking for is a set of atomic operations you can apply to generate the result. Implement these operations, then start working on a translation algorithm to turn the input data into such operations.</p>
<p>There are several common and friendly representations for such atomic bytecode:</p>
<p><strong>Instruction lists</strong> are executed in order. This is your classic assembler listing, without the jumps. A typical &#8220;parse file and insert into database&#8221; algorithm would generate such an instruction list, and every instruction would be an INSERT, DELETE or UPDATE. Works best when you can read the data and generate the instructions in the right order: if you cannot get the list in the right order from the start, consider another approach.</p>
<p><strong>Dependency graphs</strong> work like makefiles: you have several instruction lists floating around with relationships between them, indicating that one list has to be executed before another. A topological sort of the graph results in a single classic instruction list you can execute. A multi-file import, where some files contain data needed in other files, can be the way to go.</p>
<p><strong>Nested scopes</strong> are the typical extension to instruction lists: every item in a list can be either an instruction, or another list, possibly tagged with some data. This could be a conditional (if this condition is true, execute this list), a loop (though it is best to avoid these) or a context (a &#8220;polygon&#8221; scope contains &#8220;insert vertex&#8221; operations that apply to that polygon). You can even allow variables in a let-in fashion (of which the polygon example above is just a special case) ! Note that nested scopes can be easily represented as XML.</p>
<h4>2. Static Analysis</h4>
<p>A side-effect of compiling to bytecode is that you get to process the entire file before you actually perform the intended operations. This makes a rollback easier if you notice that there&#8217;s an error on the last line of the file: if you make sure that no atomic operation in your target language can fail due to bad input (such as incorrect data values), then you can check your input data for correctness without doing anything to your program state.</p>
<p>Even better, if your compilation process is cheap (linearly traverse a file for parsing) and you have heuristics for predicting how much time and resources your individual instructions require, then you can try to accurately predict the needs of the entire process.</p>
<p>Static analysis also means you can optimize. If, for instance, you&#8217;re inserting data into a database and need to resolve names or keys frequently (such as &#8220;add this item to list #732&#8243;), you can easily construct a table of needed keys (that you can get in one query when the processing starts) using the dependency graph approach.You can also optimize resource allocation by using common register allocation techniques: sort your dependency graph to keep as few resources in memory as possible at any given time.</p>
<h4>3. Caching</h4>
<p>Try to perform most of the processing offline.</p>
<p>For instance, if you frequently &#8220;apply&#8221; one file to another, such as a nearly-constant &#8220;list of categories&#8221; file used to resolve the &#8220;category&#8221; key in a daily object import, you can benefit from compiling the nearly-constant file to an easily loaded, easily applied format.</p>
<p>You see a cached dictionary that maps keys to categories? I see a DSL that allows dictionary literals as part of the language, and a source file that contains a literal mapping keys to categories, with an interpreter that can apply constant propagation to dictionaries.</p>
<p>Another benefit is when applying changes to mission-critical software. Inserting lots of data into a web database can create a heavy load on the server and make the site unavailable to visitors. It might therefore be preferrable to pre-compile the imported data into requests through a process that keeps a light load on the server, then run the requests.</p>
<p>Besides, with proper nested scoping, you can slice an import into several transactions. This keeps the lock count low, allows spreading the transactions over time to reduce the load, and lets you resume the import process if, for some reason, it gets interrupted.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/01/interesting-rates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>December 2009 PDF Vulnerability</title>
		<link>http://www.nicollet.net/2010/01/december-2009-pdf-vulnerability/</link>
		<comments>http://www.nicollet.net/2010/01/december-2009-pdf-vulnerability/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 21:01:07 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PDF]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=1242</guid>
		<description><![CDATA[All file formats follow the same evolution.

They start by grouping together some static content, with some nifty features for presenting and editing that data. Think text files, bitmaps, RTF documents&#8230; The file format is reasonably easy to understand, and the reader/writer is so simple that it would take a bad programmer to create vulnerabilities.
Then, they [...]]]></description>
			<content:encoded><![CDATA[<p>All file formats follow the same evolution.</p>
<ol>
<li>They start by grouping together some static content, with some nifty features for presenting and editing that data. Think text files, bitmaps, RTF documents&#8230; The file format is reasonably easy to understand, and the reader/writer is so simple that it would take a bad programmer to create vulnerabilities.</li>
<li>Then, they start including plug-ins that let them handle more and more types of contents. This lets you include an image inside an HTML page or an Excel spreadsheet in a Word document. This relies on many plugins for getting things right. It sometimes happens that a given plugin contains a security fault that can then be exploited, for instance Internet Explorer had <a href="http://www.microsoft.com/technet/security/Bulletin/MS05-025.mspx" target="_blank">an issue with images in PNG format</a>. The user would visit a page, that page would display an image, and the computer would be contaminated.</li>
<li>Finally, they need to become interactive, so they include a scripting language of some sort. Excel has a macro system that uses Visual Basic, HTML includes Javascript&#8230;</li>
</ol>
<p>The PDF format followed the same process to end up where it is now. In addition to any static document data (text, vector and raster images) and extended content (flash animations, videos, reader extension signatures) a PDF also contains short JavaScript that let authors create interactive documents. This means a PDF document on your desktop can:</p>
<ul>
<li>Accept user input (such as checkboxes or text fields). The input can be saved to the disk if the reader supports it and allows it (Acrobat Reader, used by the vast majority of computer users, only allows saving a file if its author purchased a reader extensions license and signed the PDF file with it).</li>
<li>Change its layout at will, for instance displaying a &#8220;spouse&#8221; page only if the &#8220;spouse&#8221; checkbox was ticked.</li>
<li>Be cryptographically signed, and display information about who signed it. This kind of signature is actually accepted as valid legal proof in many countries.</li>
<li>Compute a scannable bar code from user input, so that it can be printed, then scanned on the other side with reduced error rates.</li>
<li>Send data over the internet. It can even send itself as an attachment to an email.</li>
</ul>
<p>Needless to say, with all these features, there are inevitably going to be some exploitable security issues in the mix. Being a popular program, like Acrobat Reader, only increases the number of black hat hackers looking for vulnerabilities. One of these is the recent <a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-4324" target="_blank">CVE-2009-4324</a> from December 2009. There are many types of vulnerabilities, their common feature being that they end up executing arbitrary operations on the computer (as opposed to the safe operations Acrobat Reader normally allows). These operations are usually to download or install trojans, so that the attacker can gain complete control over the computer.</p>
<p>CVE-2009-4324 is of the <em>use-after-free</em> kind. In short:</p>
<ul>
<li>it creates a resource (which uses some memory),</li>
<li>it <strong>frees</strong> (destroys) the resource to recycle its memory,</li>
<li>it writes something to that memory,</li>
<li>it attempts to <strong>use</strong> the resource</li>
</ul>
<p>Normally, the program should stop at step four and say &#8220;you can&#8217;t use the resource, it&#8217;s been destroyed&#8221;. A bug can cause it to believe that the resource is still there. The programmer probably assumed that the memory still contained a valid resource and did defend against the memory containing <em>something else</em>&#8230; and accessing that as if it were a valid resource executes some code that the attacker wanted to execute. <em>Bingo</em>.</p>
<p>In the case of CVE-2009-4324, this happens as part of the <a href="http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Acrobat9_HTMLHelp&amp;file=JS_API_AcroJS.88.549.html#1962571" target="_blank">Doc.media.newPlayer</a> method which, for performance reasons, was not completely implemented in Javascript—a bug in some Javascript code can cause the document to misbehave, but it cannot do anything that the Javascript couldn&#8217;t do on its own. Those parts that were written in a lower-level language, with access to the computer, contained the exploited bug.</p>
<p>The bug causes the processor to start executing code at a different memory location. In an ideal hacker world, that location would be precisely where some nasty code is present. Buffer overflows, when used to rewrite pieces of the stack, do allow such deterministic jumps. However, CVE-2009-4324 only allows a jump to an undetermined location.</p>
<p>The hacker solution is to use heap spray. The basic idea is that you have a short piece of code you want to execute (the <strong>payload</strong>). You create a block from that payload by adding no-ops (machine instructions that say &#8220;skip me&#8221;) before the payload. Then, you create lots of these blocks in memory, and trigger the exploit.</p>
<p>The exploit causes the computer to jump to an undetermined memory location. If it falls within the no-op section of any of the blocks you&#8217;ve created, you win: the computer skips over the no-ops, reaches the payload and executes it. If not, the program will crash. Too bad&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/01/december-2009-pdf-vulnerability/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
