<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Henley Edition]]></title><description><![CDATA[Music, Math, and the Modern Web]]></description><link>http://my-ghost-blog.com/</link><generator>Ghost 0.11</generator><lastBuildDate>Tue, 04 Jun 2024 20:38:39 GMT</lastBuildDate><atom:link href="http://my-ghost-blog.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Sunset Walk]]></title><description><![CDATA[<p><a href="http://henleyedition.com/content/images/2021/05/sunset-walk.jpeg"><img src="http://henleyedition.com/content/images/2021/05/sunset-walk.jpeg#cover" alt="Sunset Walk" title=""></a></p>

<blockquote>
  <p>May our love be like a sunset walk,<br>
  Arranged in steps and saccades,<br>
  And arcing marble paths.</p>
  
  <p>I stop you at a tree that holds the sky,<br>
  Shimmering like never before.<br>
  We nestle in the spectacle<br>
  Of soft light clattering through its leaves.</p>
  
  <p>I ask you for your hand and</p></blockquote>]]></description><link>http://my-ghost-blog.com/sunset-walk/</link><guid isPermaLink="false">76139c22-70f0-458d-b0f6-b849100add59</guid><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Wed, 19 May 2021 17:20:00 GMT</pubDate><media:content url="http://my-ghost-blog.com/content/images/2021/05/sunset-walk.jpeg" medium="image"/><content:encoded><![CDATA[<img src="http://my-ghost-blog.com/content/images/2021/05/sunset-walk.jpeg" alt="Sunset Walk"><p><a href="http://henleyedition.com/content/images/2021/05/sunset-walk.jpeg"><img src="http://henleyedition.com/content/images/2021/05/sunset-walk.jpeg#cover" alt="Sunset Walk" title=""></a></p>

<blockquote>
  <p>May our love be like a sunset walk,<br>
  Arranged in steps and saccades,<br>
  And arcing marble paths.</p>
  
  <p>I stop you at a tree that holds the sky,<br>
  Shimmering like never before.<br>
  We nestle in the spectacle<br>
  Of soft light clattering through its leaves.</p>
  
  <p>I ask you for your hand and all its digits,<br>
  And all the spaces in between,<br>
  And find in it a new shape after all these years.<br></p>
</blockquote>]]></content:encoded></item><item><title><![CDATA[To Those Leaving Their Old Lives Behind]]></title><description><![CDATA[<p>Six months into a graduate program at a music conservatory in Ohio, I made the hardest decision of my life. I had spent the previous 12 years training to become a professional cellist. It was the only thing I had ever known. All of my friends were classical musicians. Some</p>]]></description><link>http://my-ghost-blog.com/to-those-leaving-their-old-lives-behind/</link><guid isPermaLink="false">7cb5aa85-32f7-4e6b-9a9a-91acb09ccf08</guid><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Tue, 10 May 2016 00:38:56 GMT</pubDate><content:encoded><![CDATA[<p>Six months into a graduate program at a music conservatory in Ohio, I made the hardest decision of my life. I had spent the previous 12 years training to become a professional cellist. It was the only thing I had ever known. All of my friends were classical musicians. Some were beginning to win major auditions around the country. I was surrounded by people more stubborn and more successful than me, and despite knowing that I had made the right choice in dropping out, everything around me was a reminder of my failure.</p>

<p>Over the next two years, I bounced from project to project, started running, tried several diets, read a bunch of books on music and philosophy and meditated frequently. I flirted with Musicology, and later, Music Journalism. I started writing in-depth music reviews and posted them to my blog. I was accepted into NYU for a self-designed degree in music scholarship, but the cost was prohibitive. I couldn’t stay in Cleveland as my friends all graduated and left. I left for Austin a month later, to start over from scratch.</p>

<p>In December 2013, I was looking over my roommate’s shoulder at his solutions to Project Euler problems, written in JavaScript. It looked exciting. I recalled making rudimentary websites in Junior High, before music completely took over my life. I picked up a little Ruby and started from Problem 1...</p>

<p>Finding a second passion is different than the first. I had been here before and was guarded against the waning interest that had smothered every previous endeavor. But I kept going, picking up JavaScript, CSS, and enough PHP to power through a WordPress theme for my blog. The learning curve was exhilarating and it wasn’t stopping. I subscribed to countless blogs on web design and development and I actually read them. I was becoming more savvy, started getting real Twitter followers and stars on GitHub. I fashioned my music blog into one about web development, and people were interested in what I was writing. I couldn’t believe it. After so long projecting my passions into the world, finally one responded. I was falling in love with the web.</p>

<p>Over 4 years have passed since I dropped out of conservatory. But I have found myself a new mountain with an even higher summit and people there cheering me on. I am lucky to have stumbled blindly into this profession that is so full of vitality, and I am proud of and humbled by my experience so far. When I left the classical music world, I took a dive into the unknown. My only insurance was my own resolve. Like the opening to the William Tell Overture, a lone cello projecting into the silence, awaiting its symphony.</p>

<p>Sincerely, <br>
Evan</p>

<iframe width="420" height="315" src="//www.youtube.com/embed/xoBE69wdSkQ" frameborder="0" allowfullscreen></iframe>]]></content:encoded></item><item><title><![CDATA[Implicit Code Splitting and Chunk Loading with React Router and Webpack]]></title><description><![CDATA[<p>In this post, we'll be refactoring React Router's <a href="https://github.com/reactjs/react-router/tree/master/examples/huge-apps">"huge apps" example</a>, using Webpack's <a href="https://github.com/webpack/bundle-loader">bundle-loader</a> to eliminate nearly all of the example's code-splitting boilerplate, and addressing how to use this technique in a project with universal rendering. This post assumes you have experience with React, React Router, Babel/ES6, and Webpack.</p>]]></description><link>http://my-ghost-blog.com/implicit-code-splitting-with-react-router-and-webpack/</link><guid isPermaLink="false">8b375327-6a76-45ef-9e7d-059f00d055a2</guid><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Thu, 10 Mar 2016 22:58:13 GMT</pubDate><content:encoded><![CDATA[<p>In this post, we'll be refactoring React Router's <a href="https://github.com/reactjs/react-router/tree/master/examples/huge-apps">"huge apps" example</a>, using Webpack's <a href="https://github.com/webpack/bundle-loader">bundle-loader</a> to eliminate nearly all of the example's code-splitting boilerplate, and addressing how to use this technique in a project with universal rendering. This post assumes you have experience with React, React Router, Babel/ES6, and Webpack.</p>

<p>You can find the complete <a href="https://github.com/echenley/react-router-huge-apps-refactor/tree/before">original</a> and <a href="https://github.com/echenley/react-router-huge-apps-refactor/tree/after">refactored</a> code on GitHub.</p>

<h2 id="theoriginal">The Original</h2>

<p>The original code uses Webpack's <a href="https://webpack.github.io/docs/code-splitting.html"><code>require.ensure</code> API</a> directly. By design, <code>require.ensure</code> cannot work with dynamic module paths, which leads to a lot of repetitive code (the React Router team split this code into tree of route files). Because of this limitation, routing logic is now scattered throughout the routes folder at various depths, and a commented representation of the routes is necessary to understand what's going on at a glance. The <code>src/</code> directory looks like this:</p>

<pre><code>├── components
├── routes
│   ├── Calendar
│   │   ├── components
│   │   │   └── Calendar.js
│   │   └── index.js
│   ├── Course
│   │   ├── components
│   │   │   ├── Course.js
│   │   │   ├── Dashboard.js
│   │   │   └── Nav.js
│   │   └── routes
│   │       ├── Announcements
│   │       │   ├── components
│   │       │   │   ├── Announcements.js
│   │       │   │   ├── Sidebar.js
│   │       │   ├── routes
│   │       │   │   └── Announcement
│   │       │   │       ├── components
│   │       │   │       │   └── Announcement
│   │       │   │       └── index.js
│   │       │   └── index.js
│   │       ├── Assignments
│   │       │   ├── components
│   │       │   │   ├── Assignments.js
│   │       │   │   ├── Sidebar.js
│   │       │   ├── routes
│   │       │   │   └── Assignment
│   │       │   │       ├── components
│   │       │   │       │   └── Assignment
│   │       │   │       └── index.js
│   │       │   └── index.js
│   │       └── Grades
│   │           ├── components
│   │           │   └── Grades.js
│   │           └── index.js
│   ├── Grades
│   │   ├── components
│   │   │   └── Grades.js
│   │   └── index.js
│   ├── Messages
│   │   ├── components
│   │   │   └── Messages.js
│   │   └── index.js
│   └── Profile
│       ├── components
│       │   └── Profile.js
│       └── index.js
├── stubs
└── app.js
</code></pre>

<p>We can do better than that.</p>

<h2 id="therefactor">The Refactor</h2>

<p>We can use Webpack's own <a href="https://github.com/webpack/bundle-loader">bundle-loader</a> to get around the limitations of raw <code>require.ensure</code> and greatly simplify our code. Bundle loader abstracts away the <code>require.ensure</code> logic that bloated and obscured our code. When a module is run through bundle-loader, a chunk will be created for it and its dependencies, and a function wrapper is returned instead of the original module. When the function wrapper is invoked, it will ajax in the module and pass it to a callback function.</p>

<p>We can eliminate all of the <code>index.js</code> files througout the <code>routes/</code> directory and flatten the structure where it makes sense. All of our routing logic will be moved to <code>app.js</code>. This results in a massively simplified <code>src/</code> directory:</p>

<pre><code>├── components
├── routes
│   ├── Calendar.js
│   ├── Course
│   │   ├── components
│   │   │   ├── Dashboard.js
│   │   │   └── Nav.js
│   │   ├── routes
│   │   │   ├── Announcements
│   │   │   │   ├── routes
│   │   │   │   │   └── Announcement.js
│   │   │   │   ├── Announcements.js
│   │   │   │   └── Sidebar.js
│   │   │   ├── Assignments
│   │   │   │   ├── routes
│   │   │   │   │   └── Assignment.js
│   │   │   │   ├── Assignments.js
│   │   │   │   └── Sidebar.js
│   │   │   └── Grades.js
│   │   └── Course.js
│   ├── Grades.js
│   ├── Messages.js
│   └── Profile.js
├── stubs
└── app.js
</code></pre>

<p>Once we've updated the file structure, we can direct webpack to run route components through bundle-loader. Since we don't want to split every single file in <code>routes/</code> (specifically the files in <code>components/</code> directories), we will need to write a regex to match the right files. In this particular app, we know route components are any files matching <code>routes/*.js</code> or <code>routes/SOMETHING/*.js</code>. Any files matching <code>routes/SOMETHING/components/*.js</code> should NOT be included:</p>

<pre><code class="language-javascript">// NOTE: this assumes you're on a Unix system. You will
// need to update this regex and possibly some other config
// to get this working on Windows (but it can still work!)
var routeComponentRegex = /routes\/([^\/]+\/?[^\/]+).js$/  
</code></pre>

<pre><code class="language-javascript">module.exports = {  
  // ...rest of config...
  modules: {
    loaders: [
      // make sure to exclude route components here
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: routeComponentRegex,
        loader: 'babel'
      },
      // run route components through bundle-loader
      {
        test: routeComponentRegex,
        include: path.resolve(__dirname, 'src'),
        loaders: ['bundle?lazy', 'babel']
      }
    ]
  }
  // ...rest of config...
}
</code></pre>

<p>Now, in <code>app.js</code>, we can simply import our route components like normal:</p>

<pre><code class="language-javascript">// Webpack is configured to create ajax wrappers around each of these modules.
// Webpack will create a separate chunk for each of these imports (including
// any dependencies)
import Course from './routes/Course/Course'  
import AnnouncementsSidebar from './routes/Course/routes/Announcements/Sidebar'  
import Announcements from './routes/Course/routes/Announcements/Announcements'  
import Announcement from './routes/Course/routes/Announcements/routes/Announcement'  
import AssignmentsSidebar from './routes/Course/routes/Assignments/Sidebar'  
import Assignments from './routes/Course/routes/Assignments/Assignments'  
import Assignment from './routes/Course/routes/Assignments/routes/Assignment'  
import CourseGrades from './routes/Course/routes/Grades'  
import Calendar from './routes/Calendar'  
import Grades from './routes/Grades'  
import Messages from './routes/Messages'  
</code></pre>

<p>As mentioned earlier, these are not the route components themselves, but function wrappers that will load the correct chunk when called.</p>

<p>We will need to use React Router's <code>route.getComponent</code> to load these chunks asynchronously. First, we must set up a function which recieves the ajax wrapper, and returns a function which will load the module when the route is requested:</p>

<pre><code class="language-javascript">function lazyLoadComponent(lazyModule) {  
  return (location, cb) =&gt; {
    lazyModule(module =&gt; cb(null, module))
  }
}
</code></pre>

<p>Since this project uses <code>route.getComponents</code> as well, we will need another function:</p>

<pre><code class="language-javascript">function lazyLoadComponents(lazyModules) {  
  return (location, cb) =&gt; {
    const moduleKeys = Object.keys(lazyModules);
    const promises = moduleKeys.map(key =&gt;
      new Promise(resolve =&gt; lazyModules[key](resolve))
    )

    Promise.all(promises).then(modules =&gt; {
      cb(null, modules.reduce((obj, module, i) =&gt; {
        obj[moduleKeys[i]] = module;
        return obj;
      }, {}))
    })
  }
}
</code></pre>

<p>Now, your routes can be defined all at once as JSX:</p>

<pre><code class="language-javascript">render(  
  &lt;Router history={ browserHistory }&gt;
    &lt;Route path="/" component={ App }&gt;
      &lt;Route path="calendar" getComponent={ lazyLoadComponent(Calendar) } /&gt;
      &lt;Route path="course/:courseId" getComponent={ lazyLoadComponent(Course) }&gt;
        &lt;Route path="announcements" getComponents={ lazyLoadComponents({
          sidebar: AnnouncementsSidebar,
          main: Announcements
        }) }&gt;
          &lt;Route path=":announcementId" getComponent={ lazyLoadComponent(Announcement) } /&gt;
        &lt;/Route&gt;
        &lt;Route path="assignments" getComponents={ lazyLoadComponents({
          sidebar: AssignmentsSidebar,
          main: Assignments
        }) }&gt;
          &lt;Route path=":assignmentId" getComponent={ lazyLoadComponent(Assignment) } /&gt;
        &lt;/Route&gt;
        &lt;Route path="grades" getComponent={ lazyLoadComponent(CourseGrades) } /&gt;
      &lt;/Route&gt;
      &lt;Route path="grades" getComponent={ lazyLoadComponent(Grades) } /&gt;
      &lt;Route path="messages" getComponent={ lazyLoadComponent(Messages) } /&gt;
      &lt;Route path="profile" getComponent={ lazyLoadComponent(Calendar) } /&gt;
    &lt;/Route&gt;
  &lt;/Router&gt;,
  document.getElementById('example')
)
</code></pre>

<p>That's it! We've eliminated a ton of files and boilerplate code with one webpack loader.</p>

<h2 id="serverrendering">Server Rendering</h2>

<p>Since Webpack only creates these Ajax wrappers for the client bundle, you will need to make sure the server requires the files synchronously. This can be handled by adding a little function and using it in place of <code>lazyLoadComponent()</code>:</p>

<pre><code class="language-javascript">function loadComponent(module) {  
  return __CLIENT__
    ? lazyLoadComponent(module)
    : (location, cb) =&gt; cb(null, module);
}
</code></pre>

<p>All universal apps need some sort of global which allows you to check whether the code is running on the client or the server. This function will immediately resolve the module normally on the server and lazy load the element on the client. It's as simple as that!</p>]]></content:encoded></item><item><title><![CDATA[pinkyPromise: JavaScript Promises in 45 Lines of Code]]></title><description><![CDATA[<p><em>Disclaimer: these are not full-featured promises and don't follow any official <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promises</a> <a href="https://promisesaplus.com/">spec</a>. However, the concepts are the same, and it helps explain what is going on behind the scenes. This method is intended to be especially concise and relatively easy to understand (though still quite challenging).</em></p>

<p>What does it</p>]]></description><link>http://my-ghost-blog.com/pinkypromise-javascript-promises-in-45-lines-of-code/</link><guid isPermaLink="false">74eb83fa-6fce-41d9-a418-a94b1db7c609</guid><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Sun, 07 Jun 2015 22:10:00 GMT</pubDate><content:encoded><![CDATA[<p><em>Disclaimer: these are not full-featured promises and don't follow any official <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promises</a> <a href="https://promisesaplus.com/">spec</a>. However, the concepts are the same, and it helps explain what is going on behind the scenes. This method is intended to be especially concise and relatively easy to understand (though still quite challenging).</em></p>

<p>What does it take to go from this:</p>

<pre><code class="language-javascript">// mock async function
function incrementAsync(n, cb) {  
    setTimeout(function() {
        cb(n + 1);
    }, 100);
}

var n0 = 1;

incrementAsync(n0, function(n1) {  
    incrementAsync(n1, function(n2) {
        incrementAsync(n2, function(n) {
            console.log(n); // =&gt; 4
        });
    });
});
</code></pre>

<p>To this?</p>

<pre><code class="language-javascript">// wrap incrementAsync() and return a promise
var incrementAsyncPromise = function(n) {  
    var promise = pinkyPromise();

    incrementAsync(n, function(ret) {
        promise.resolve(ret);
    });

    return promise;
};

var n0 = 1;

incrementAsyncPromise(n0)  
    .then(incrementAsyncPromise)
    .then(incrementAsyncPromise)
    .then(function(n) {
        console.log(n); // =&gt; 4
    });
</code></pre>

<p>Or, even better, to this?</p>

<pre><code class="language-javascript">var incrementAsyncPromise = pinkyPromise(incrementAsync);

var n0 = 1;

incrementAsyncPromise(n0)  
    .then(incrementAsyncPromise)
    .then(incrementAsyncPromise)
    .then(function(n) {
        console.log(n); // =&gt; 4
    });
</code></pre>

<h2 id="45linesofcode">45 Lines of Code</h2>

<h3 id="step1">Step 1</h3>

<p>We’ll need <code>pinkyPromise()</code> to return an object with two methods: <code>.then</code> and <code>.resolve</code>.</p>

<pre><code class="language-javascript">function pinkyPromise() {  
    return {
        then: function() {},
        resolve: function() {}
    };
}
</code></pre>

<h3 id="step2">Step 2</h3>

<p>Every time <code>.then</code> is called, push the callback into a queue and return the same object.</p>

<pre><code class="language-javascript">function pinkyPromise() {  
    var queue = [];

    return {
        then: function(cb) {
            if (cb) {
                // add cb to queue
                queue.push(cb);
            }
            return this;
        },
        resolve: function() {}
    };
}
</code></pre>

<p>That's already 14 lines. Almost a third of the way there!</p>

<h3 id="step3">Step 3</h3>

<p>Set up your <code>resolve</code> function to accept a single parameter: the value to return.</p>

<pre><code class="language-javascript">function pinkyPromise() {  
    var queue = [];

    function resolve(ret) {

    }

    return {
        then: function(cb) {
            if (cb) {
                // add cb to queue
                queue.push(cb);
            }
            return this;
        },
        resolve: resolve
    };
}
</code></pre>

<h3 id="step4">Step 4</h3>

<p>There are three scenarios that could happen when <code>.resolve</code> is called.</p>

<ol>
<li>There are no more callbacks to resolve, in which case, just return.  </li>
<li><code>ret</code> is a promise.  </li>
<li><code>ret</code> is not a promise.</li>
</ol>

<pre><code class="language-javascript">function pinkyPromise() {  
    var queue = [];

    function resolve(ret) {
        if (!queue.length) {
            return;
        } else if (ret &amp;&amp; ret.then) {
            // ret is a promise
        } else {
            // ret is not a promise
        }
    }

    return {
        then: function(cb) {
            if (cb) {
                // add cb to queue
                queue.push(cb);
            }
            return this;
        },
        resolve: resolve
    };
}
</code></pre>

<p>24 lines! This is where it gets fun.</p>

<h3 id="step5">Step 5</h3>

<p>If <code>ret</code> isn't a promise, then lets send it to the oldest callback and resolve the new return value.</p>

<pre><code class="language-javascript">function pinkyPromise() {  
    var queue = [];

    function resolve(ret) {
        if (!queue.length) {
            return;
        } else if (ret &amp;&amp; ret.then) {
            // ret is a promise
        } else {
            // ret is not a promise
            var newRet = queue.shift()(ret);
            resolve(newRet);
        }
    }

    return {
        then: function(cb) {
            if (cb) {
                // add cb to queue
                queue.push(cb);
            }
            return this;
        },
        resolve: resolve
    };
}
</code></pre>

<h3 id="step6">Step 6</h3>

<p>If <code>ret</code> is a promise, then we'll call its <code>then</code> method and resolve within the same scope!</p>

<pre><code class="language-javascript">function pinkyPromise() {  
    var queue = [];

    function resolve(ret) {
        if (!queue.length) {
            return;
        } else if (ret &amp;&amp; ret.then) {
            // ret is a promise
            ret.then(resolve);
        } else {
            // ret is not a promise
            var newRet = queue.shift()(ret);
            resolve(newRet);
        }
    }

    return {
        then: function(cb) {
            if (cb) {
                // add cb to queue
                queue.push(cb);
            }
            return this;
        },
        resolve: resolve
    };
}
</code></pre>

<h3 id="step7">Step 7</h3>

<p>The following is now possible:</p>

<pre><code class="language-javascript">var incrementAsyncPromise = function(n) {  
    var promise = pinkyPromise();

    incrementAsync(n, function(ret) {
        promise.resolve(ret);
    });

    return promise;
};
</code></pre>

<p>But I want to be able to simply pass in <code>incrementAsync</code> rather than explicitly wrap it. Since most async functions accept the callback as the final argument, we can abstract the above into a function called <code>promisify</code>. We'll allow a <code>fn</code> argument to be passed into <code>pinkyPromise</code>, and instead of returning the promise object, we'll return the promisified function:</p>

<pre><code class="language-javascript">function pinkyPromise(fn) {  
    var queue = [];

    function promisify(fn) {
        // converts fn w/ callback to return promise
        return function() {
            var promise = pinkyPromise();
            var args = Array.prototype.slice.call(arguments);

            // add promise.resolve as final argument
            args.push(promise.resolve);

            fn.apply(this, args);

            return promise;
        };
    }

    function resolve(ret) {
        if (!queue.length) {
            // no more callbacks
            return;
        } else if (ret &amp;&amp; ret.then) {
            // ret is a promise
            ret.then(resolve);
        } else {
            // ret is not a promise
            var newRet = queue.shift()(ret);
            resolve(newRet);
        }
    }

    // if fn, return promisified fn
    // otherwise return a promise
    return fn ? promisify(fn) : {
        then: function(cb) {
            if (cb) {
                // add cb to queue
                queue.push(cb);
            }
            return this;
        },
        resolve: resolve
    };
}
</code></pre>

<h3 id="thatsit">That's it!</h3>

<p>Congratulations! You've just solved Callback Hell&#8482; with straight up functional programming prowess.</p>

<p>Check it out <a href="https://github.com/echenley/pinkyPromise">on GitHub</a>.</p>

<p>If you're interested in a more thorough look at promises, Matt Greer's <a href="http://www.mattgreer.org/articles/promises-in-wicked-detail/">JavaScript Promises...In Wicked Detail</a> was extremely helpful as I was beginning to wrap my head around them. He goes into much, much more detail, including rejecting promises. Highly recommended.</p>

<p>Also check out James Coglan's very insightful article <a href="https://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional-nodes-biggest-missed-opportunity/">Callbacks are imperative, promises are functional: Node’s biggest missed opportunity</a>.</p>]]></content:encoded></item><item><title><![CDATA[Building an App with React and RefluxJS]]></title><description><![CDATA[<p>A couple of months ago, I learned React by writing a game called <a href="http://henleyedition.com/flip-a-reactjs-game/">Flip</a>. Since then, React and the Flux architecture have attracted a lot of attention in the web developer community. Because of React's superior DOM performance, and the scalable nature of Flux’s one-directional data flow, many in</p>]]></description><link>http://my-ghost-blog.com/building-an-app-using-react-and-refluxjs/</link><guid isPermaLink="false">133862c7-0026-408d-b004-59d46096ed05</guid><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Wed, 03 Dec 2014 22:47:58 GMT</pubDate><content:encoded><![CDATA[<p>A couple of months ago, I learned React by writing a game called <a href="http://henleyedition.com/flip-a-reactjs-game/">Flip</a>. Since then, React and the Flux architecture have attracted a lot of attention in the web developer community. Because of React's superior DOM performance, and the scalable nature of Flux’s one-directional data flow, many in the industry suspect that React+Flux may become the "next big thing" in front end web development.</p>

<p>Facebook doesn’t provide a framework for Flux, only how to make one from scratch. So I began searching for implementations. Surprisingly, there are already a few good (though somewhat poorly-named) options: jFlux, Fluxy, Fluxxor, and finally, Reflux. Of them, Reflux appeared to have the most backers and the most elegant API. I was also won over by Krawaller’s explanations of the <a href="http://blog.krawaller.se/posts/react-js-architecture-flux-vs-reflux/">overarching philosophy</a> behind Reflux and how using Reflux can dramatically <a href="http://blog.krawaller.se/posts/reflux-refinement/">simplify a Flux application</a>.</p>

<p>Reflux has a small and simple codebase of around 13kb minified. The API is clearly defined and often highly intuitive. It took me some time to acclimate to the “Flux way” of thinking, during which I found that <a href="https://github.com/spoike/refluxjs/issues/112">old ways of thinking</a> can get you into <a href="https://github.com/spoike/refluxjs/issues/120">frustrating situations</a>. Luckily, considering the age of Flux, there are a lot of resources available. Throughout the process of building my app, I found Krawaller’s posts, Facebook's <a href="https://facebook.github.io/flux/docs/overview.html">overview of Flux</a>, and the solid <a href="https://github.com/spoike/refluxjs">Reflux README</a> to be indispensable references.</p>

<p>Over the past month, I’ve been hacking away at a Reddit-like demo app using React+RefluxJS+Firebase, and while it’s still a work in progress, I think it’s turning out to be quite a good looking project. Here’s what I learned.</p>

<h2 id="whatilearned">What I Learned</h2>

<h3 id="onestoreonecomponent">One Store, One Component</h3>

<p>Initially, I thought that I should create a Store for each type of data: <code>userStore</code>, <code>postStore</code>, and <code>commentStore</code>. This doesn’t work well in Reflux. Unlike other Flux implementations, Reflux publishers (Actions and Stores) can only ever emit one type of event. It’s possible to use Actions to persuade a Store to emit different data, but it’s unnecessarily difficult to orchestrate. It also makes stores more difficult to test. This is an intentional limitation of Reflux. By removing name strings from events, Reflux eliminates the need for a global dispatcher, drastically simplifying application data flow.</p>

<p>This problem is better solved by separating Stores by component rather than data type. In React News, I have a Store for each view (<code>singleStore</code>, <code>postsStore</code>, and <code>profileStore</code>), one for the login form (<code>loginStore</code>). I kept the <code>userStore</code>, but it is exclusively syced to my top level component and user data is passed down via props.</p>

<p>Since Stores are only supposed to emit one type of event, there are not many reasons for multiple components to listen to the same Store. But there are some exceptions. In addition to my top level component, my login component also needs to know when a login event fires so it can reset its form. The data doesn’t matter, only that the event fired. It can safely listen for an update from <code>userStore</code> and then reset its form.</p>

<pre><code class="language-javascript">var Login = React.createClass({

    mixins: [Reflux.listenTo(userStore, 'resetForm')],

    resetForm: function() {
        this.setState({
            submitted: false,
        });
        this.refs.email.getDOMNode().value = '';
        this.refs.password.getDOMNode().value = '';
        this.refs.submit.getDOMNode().disabled = false;
    },

    // etc...
});
</code></pre>

<h3 id="singlefileforactions">Single File For Actions</h3>

<p>Similarly to Stores, I tried splitting my Actions into separate files: <code>userActions</code>, <code>postActions</code>, and <code>commentActions</code>. But I found that sometimes a <code>postAction</code> would need to call a <code>commentAction</code>, or vice versa, and circular dependencies started happening. So I moved all of my Actions into one file and that was that.</p>

<h3 id="actionscallingactionsvsstorescallingactionsvsstorescallingstores">Actions calling Actions vs. Stores calling Actions vs. Stores calling Stores</h3>

<p>In the real world, sometimes Actions need to be fired once an async request completes. There is a <a href="https://github.com/spoike/refluxjs/issues/57">discussion to be had</a> about whether it’s kosher to initiate an Action from a Store, say, right before it triggers, or if it’s better to move API requests to the Action’s <code>.preEmit()</code> method and call other Actions from there. I prefer the latter, as it better maintains one-directional data flow:</p>

<pre><code class="language-javascript">actions.addComment.preEmit = function(comment) {  
    commentsRef.push(comment, function(error) {
        if (error === null) {
            actions.updateCommentCount(comment.postId, 1);
        }
    });
};
</code></pre>

<h3 id="flexibilityintherefluxpubsubmodel">Flexibility in the Reflux PubSub Model</h3>

<p>As Krawaller states in <a href="http://blog.krawaller.se/posts/the-reflux-data-flow-model/">The Reflux data flow model</a>:</p>

<blockquote>
  <p>At its heart, Reflux is really just a PubSub library. That is, we have a Publisher API for objects who transmit events, and a Subscriber API for objects who want to listen to such events.</p>
</blockquote>

<table>  
    <thead>
        <th></th>
        <th>Publisher</th>
        <th>Subscriber</th>
    </thead>
    <tbody style="text-align: center">
        <tr>
            <td style="text-align: right">View Component</td>
            <td>&times;</td>
            <td>&#x2713;</td>
        </tr>
        <tr>
            <td style="text-align: right">Store</td>
            <td>&#x2713;</td>
            <td>&#x2713;</td>
        </tr>
        <tr>
            <td style="text-align: right">Action</td>
            <td>&#x2713;</td>
            <td>&times;</td>
        </tr>
    </tbody>
</table>

<p>The fact that any Subscriber can listen to any Publisher means there is some degree of flexibility. This flexibility is sometimes convenient: for simple UI events, rather than passing props down several component layers or creating another Store, I just use an Action:</p>

<pre><code class="language-javascript">var SinglePost = React.createClass({

    addComment: function(e) {
        e.preventDefault();

        if (!this.props.user.isLoggedIn) {
            actions.showLoginOverlay();
            return;
        }

        // submit comment...
    },

    // render, etc...

});
</code></pre>

<p>And at the top level, I can listen to the Action directly:</p>

<pre><code class="language-javascript">var ReactNews = React.createClass({

    mixins: [
        Reflux.listenTo(actions.showLoginOverlay, 'showLoginOverlay')
    ],

    showLoginOverlay: function() {
        this.setState({
            showOverlay: true
        });
    }

    // etc...
});
</code></pre>

<p>If it were any more complex, I might rather move all this state to a Store, but for my needs, this is sufficient.</p>

<h2 id="summingup">Summing Up</h2>

<p>Reflux recently reached v0.2.0, but it’s already a powerful tool for building Flux applications. For those who are looking for examples of Reflux applications, you’re welcome to check out my code <a href="https://github.com/echenley/react-news">on GitHub</a>. The live demo is <a href="http://henleyedition.com/reactnews">available here</a>.</p>

<p>You can log in with: <br>
Email: reactnews@example.com <br>
Password: henleyedition1</p>]]></content:encoded></item><item><title><![CDATA[Flip - A ReactJS Game]]></title><description><![CDATA[<p>Building upon my experience with the <a href="http://my-ghost-blog.com/reactjs-slide-puzzle/">ReactJS Slide Puzzle</a>, I thought I'd take the concept of a React-based game one step further. Flip is not very practical, and uses a lot of potentially buggy CSS3 and ES5 methods, but I mean, it's just a game. Besides, it shows some of</p>]]></description><link>http://my-ghost-blog.com/flip-a-reactjs-game/</link><guid isPermaLink="false">7746b893-2bbd-497c-ba69-62cc4588150b</guid><category><![CDATA[programming]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Tue, 16 Sep 2014 22:04:56 GMT</pubDate><content:encoded><![CDATA[<p>Building upon my experience with the <a href="http://my-ghost-blog.com/reactjs-slide-puzzle/">ReactJS Slide Puzzle</a>, I thought I'd take the concept of a React-based game one step further. Flip is not very practical, and uses a lot of potentially buggy CSS3 and ES5 methods, but I mean, it's just a game. Besides, it shows some of what's possible using React. React has been a real pleasure to use, despite some minor workflow issues related to JSX (as it matures, I imagine it will become easier to use).</p>

<p>This is still a work in progress, so sorry for any bugs! The full source is available <a href="https://github.com/echenley/flip">on my github</a>. Click below to play!</p>

<div><a href="http://henleyedition.com/static/flip/"><img src="http://my-ghost-blog.com/content/images/2014/Sep/flip-screenshot-2000px.jpg" alt="Flip - A ReactJS Game"></a></div>]]></content:encoded></item><item><title><![CDATA[ReactJS Slide Puzzle]]></title><description><![CDATA[<p>I put together a simple 3X3 slide puzzle as a first attempt at <a href="http://facebook.github.io/react/">React.js</a>. I was inspired after running through Brian Barnett's great <a href="http://w.brianbar.net/2014/08/tic-tac-react-part-1/">Tic Tac React tutorial</a>, and therefore mine shares much of the same code. I really recommend his post if you're interested in learning about React.</p>

<p>By</p>]]></description><link>http://my-ghost-blog.com/reactjs-slide-puzzle/</link><guid isPermaLink="false">1aa02ad0-a810-419f-8a28-c1797ff25c95</guid><category><![CDATA[programming]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Fri, 22 Aug 2014 06:22:06 GMT</pubDate><content:encoded><![CDATA[<p>I put together a simple 3X3 slide puzzle as a first attempt at <a href="http://facebook.github.io/react/">React.js</a>. I was inspired after running through Brian Barnett's great <a href="http://w.brianbar.net/2014/08/tic-tac-react-part-1/">Tic Tac React tutorial</a>, and therefore mine shares much of the same code. I really recommend his post if you're interested in learning about React.</p>

<p>By default, React uses a XML-like syntax called <a href="http://facebook.github.io/react/docs/jsx-in-depth.html">JSX</a>, which has already been compiled to plain JavaScript below. You can view the original, uncompiled source <a href="https://github.com/echenley/reactjs-slide-puzzle/">on GitHub</a>.</p>

<p data-height="587" data-theme-id="0" data-slug-hash="ijLyp" data-default-tab="result" data-user="echenley" class="codepen">See the Pen <a href="http://codepen.io/echenley/pen/ijLyp/">ijLyp</a> by Evan Henley (<a href="http://codepen.io/echenley">@echenley</a>) on <a href="http://codepen.io">CodePen</a>.</p>  

<script async src="//codepen.io/assets/embed/ei.js"></script>]]></content:encoded></item><item><title><![CDATA[Making inheritance make sense with Object.create()]]></title><description><![CDATA[<blockquote>
  <p>JavaScript itself is conflicted about its prototypal nature. In a prototypal system, objects inherit from objects. JavaScript, however, lacks an operator that performs that operation. Instead it has a new operator...<cite><a href="http://javascript.crockford.com/prototypal.html">Prototypal Inheritance in JavaScript</a>, Douglas Crockford</cite></p>
</blockquote>

<p>The goal is to create a new object with a given prototype link.</p>]]></description><link>http://my-ghost-blog.com/making-inheritance-make-sense-with-object-create/</link><guid isPermaLink="false">a82c7893-c5a2-4217-a21d-6607c708f1f2</guid><category><![CDATA[programming]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Tue, 19 Aug 2014 21:21:02 GMT</pubDate><content:encoded><![CDATA[<blockquote>
  <p>JavaScript itself is conflicted about its prototypal nature. In a prototypal system, objects inherit from objects. JavaScript, however, lacks an operator that performs that operation. Instead it has a new operator...<cite><a href="http://javascript.crockford.com/prototypal.html">Prototypal Inheritance in JavaScript</a>, Douglas Crockford</cite></p>
</blockquote>

<p>The goal is to create a new object with a given prototype link. The status quo goes something like this:</p>

<pre><code class="language-javascript">function Person(name) {  
    this.name = name;
}

Person.prototype = { species: 'human' };

var finn = new Person('Finn');  
console.log(finn);          // { name: 'Finn' }  
console.log(finn.species);  // human

var fiona = new Person('Fiona');  
console.log(fiona);         // { name: 'Fiona' }  
console.log(fiona.species); // human  
</code></pre>

<p>See that fancy <code>new</code> operator? If you aren't already familiar with it, good luck understanding what's going on here. What does <code>this</code> refer to? What does <code>Person()</code> return? What is this <code>prototype</code> property that's added to <code>Person</code> and how is <code>finn</code> linked to it?</p>

<p>The pattern for creating objects with the <code>new</code> operator has always seemed really strange to me, like all the rules of JavaScript are suddenly suspended. A bunch of magic happens and poof&mdash;you've got yourself an object and somehow <code>Person.prototype</code> is its prototype. Wait, what? No wonder people are confused about prototypal inheritance&mdash;none of it is ever explicitly coded!</p>

<blockquote>
  <p>This indirection was intended to make the language seem more familiar to classically trained programmers, but failed to do that, as we can see from the very low opinion Java programmers have of JavaScript.<cite><a href="http://javascript.crockford.com/prototypal.html">Prototypal Inheritance in JavaScript</a>, Douglas Crockford</cite></p>
</blockquote>

<p>The reality is that this paradigm sucks, and there's a better way to create objects with much less magic.</p>

<p>ECMAScript 5 (released in 2009) made <code>Object.create()</code> available as an alternative to the <code>new</code> syntax. You pass it any object (we'll call ours <code>personProto</code>) and it returns a new object with <code>personProto</code> as its prototype. The <code>new</code> confusion is no longer necessary; we can rename <code>Person()</code> to the more descriptive <code>newPerson()</code> and lose the <code>this</code>:</p>

<pre><code class="language-javascript">var personProto = { species: 'human' };

function newPerson(name) {  
    var person = Object.create(personProto);
    person.name = name;
    return person;
}

var finn = newPerson('Finn');  
console.log(finn);          // { name: 'Finn' }  
console.log(finn.species);  // human

var fiona = newPerson('Fiona');  
console.log(fiona);         // { name: 'Fiona' }  
console.log(fiona.species); // human  
</code></pre>

<p>Ah, suddenly it all makes sense! You define a function that when called creates an object with a specified prototype, assigns that object whatever properties you want, and finally returns it. It does the exact same thing as the first example, except without the hand-waving. This is essentially a native and better-looking implementation of Crockford's abstraction:</p>

<pre><code class="language-javascript">function object(o) {  
    function F() {}
    F.prototype = o;
    return new F();
}
</code></pre>

<blockquote>
  <p>It takes an old object as a parameter and returns an empty new object that inherits from the old one. If we attempt to obtain a member from the new object, and it lacks that key, then the old object will supply the member. Objects inherit from objects. What could be more object oriented than that?<cite><a href="http://javascript.crockford.com/prototypal.html">Prototypal Inheritance in JavaScript</a>, Douglas Crockford</cite></p>
</blockquote>

<p><a href="http://kangax.github.io/compat-table/es5/">Browser compatibility</a> is actually pretty great at this point. If you need to support legacy browsers, you can include an <a href="https://github.com/es-shims/es5-shim">ES5 shim</a>.</p>

<p>I don't know what this means for <code>new</code>, if it is going obsolete or if there's some important use-case I'm overlooking. The least you can say is that <code>Object.create()</code> is a good addition to the language, and a reaffirmation of JavaScript's simple, prototypal nature.</p>]]></content:encoded></item><item><title><![CDATA[The Downside to Ajaxing WordPress]]></title><description><![CDATA[<p>"Hijax" is a term used to describe a progressive enhancement in which internal site links are "hijacked" by JavaScript in order to load the content dynamically. It reveals to developers a whole new world of <a href="http://tympanus.net/Tutorials/MediumStylePageTransition/">interactivity control</a>. It's a fancy and futuristic world&mdash;a world not without a gotcha</p>]]></description><link>http://my-ghost-blog.com/the-downside-to-ajaxing-wordpress/</link><guid isPermaLink="false">52ba97e4-602d-4d2b-bcc5-25c981b90942</guid><category><![CDATA[programming]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Thu, 07 Aug 2014 21:39:36 GMT</pubDate><content:encoded><![CDATA[<p>"Hijax" is a term used to describe a progressive enhancement in which internal site links are "hijacked" by JavaScript in order to load the content dynamically. It reveals to developers a whole new world of <a href="http://tympanus.net/Tutorials/MediumStylePageTransition/">interactivity control</a>. It's a fancy and futuristic world&mdash;a world not without a gotcha or two.</p>

<p>Sometimes Hijax is referred to as "Ajaxing" or "Ajaxifying", but these are less specific terms. It's important from the start to understand that <em>Hijax is a specific variety of Ajax</em>, and thus the two terms are not strictly interchangeable. I will explain both over the course of this article.</p>

<p>I am not the first to fall victim to the siren song of Ajax. In 2011, an older style of <del>Hijax</del> Ajax called "Hashbang URLs" <a href="http://www.webmonkey.com/2011/02/gawker-learns-the-hard-way-why-hash-bang-urls-are-evil/">brought down Gawker</a>, who were just trying to be cool. Similarly, I realized during my most recent project that I, too, was in over my head, spending more time constructing stopgaps to ensure that arbitrary third-party plugins would work than I was spending on anything else.</p>

<p>Maybe you've been there and you're familiar with the perils. Maybe not. Either way, before you begin steering your ship towards <em>Sirenum ajaxuli</em>, let my experience serve as a warning: strap yourself to the mast and consider the cons of Ajaxing your WordPress theme.</p>

<h2 id="whatisajax">What is Ajax?</h2>

<p>For those who aren't familiar with it, Ajax is a simple but powerful (and increasingly common) front-end technique in which JavaScript makes a server request in the background. Then, instead of loading a whole new page, the server returns its data to the JavaScript, which can process it or load it into the DOM. Meanwhile, the client can continue without interruption. Ajax is like sending the intern to Starbucks so you can keep working.</p>

<p>So, if Ajax allows for an uninterrupted browsing experience, why don't developers use it for everything? Well, it turns out that Ajax does have its share of consequences depending on what you're trying to accomplish. Ultimately for this project, three major issues caused me to renege on full-site Hijax in favor of a more targeted approach.</p>

<h2 id="issue1specificinformationishardtocomeby">Issue #1 - Specific information is hard to come by</h2>

<p>Stick some combination of "ajaxify"/"ajax"/"hijax" into the search bar and you'll quickly discover that there's no standardized terminology for any of this, meaning even if there is pertinent information out there, you'll never find it beneath heaps of articles about plugins and forms and whatever else. Maybe I'm naive, but <a href="http://codex.wordpress.org/AJAX_in_Plugins">WordPress' native implementation of Ajax</a> shows up in search results so consistently that I began to question my understanding that it was irrelevant (it was) and wasted a bunch of time as a result.</p>

<p>Yes, it turns out that Ajax has tons of uses, and adding sex-appeal via Hijax is just one of them. A couple common uses are <a href="http://domscripting.com/presentations/xtech2006/examples/contact/">form validation</a>, <a href="http://domscripting.com/presentations/xtech2006/examples/cart/">shopping carts</a>, and <a href="http://handsontable.com/demo/ajax.html">saving drafts</a> on the fly, but really, Ajax can be considered for anything where you need to swap data asynchronously between client and server.</p>

<p>The side effect of its broad appeal is that it's sort of difficult to find the right information for the right kind of Ajax. Specifically, good information on how to properly implement Hijax is surprisingly lacking, which brings me to my next point...</p>

<h2 id="issue2whatinformationthereisisobsolete">Issue #2 - What information there is, is obsolete</h2>

<p>Ajax is a burgeoning and rapidly changing paradigm in web development. When you do find Hijax-relevant resources, even from a year or two ago, you have to be careful of out of date information. For the basics, CSS-Tricks has a <a href="http://css-tricks.com/video-screencasts/81-ajaxing-a-wordpress-theme/">great screencast</a> on "Ajaxing" a WordPress theme.</p>

<p>Unfortunately it's from 2010 and uses the outdated "hashbang" or fragment identifier technique that was fashionable at the time (the same one that got Gawker in trouble). You'll find plenty of articles on this technique, but it's pretty flawed, and nowadays there's a better alternative in the modern <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history">History API</a>, which does all the good stuff <a href="http://isolani.co.uk/blog/JavaScript/BreakingTheWebWithHashBangs">without breaking the internet</a>.</p>

<p>Luckily, it is fairly easy to adapt the CSS-Tricks code to use it. You will still need to provide a fallback for browsers that don't support the History API (IE9), but since you're not cutting up URLs, that's as simple as a redirect:</p>

<pre><code class="language-javascript">if (typeof history.pushState === 'undefined') {  
    // Refresh the page to the new URL if pushState not supported
    location.href = url;
}
</code></pre>

<p>So as you start massaging that code into your theme, you suddenly realize...</p>

<h2 id="issue3allyourjavascriptwidgetsandpluginsdontworkanymore">Issue #3 - All your JavaScript widgets and plugins don't work anymore</h2>

<p>Honestly, implementing Hijax isn't that difficult, even without a library like jQuery. The problem lies in the fact that managing JavaScript and CSS resources becomes much more difficult when your site runs on Ajax.</p>

<p>Many WordPress plugins count on specific JavaScript being executed when the page is loaded, but Ajax throws a wrench into that. Unless you have full control over what users can and cannot add to their site (hahaha), you're going to have to resort to one of two options:</p>

<p>Option 1 - <strong>Specifically add code to reload known widgets</strong>. The operative word being "known". On Henley Edition, I use something like this:</p>

<pre><code class="language-javascript">glassApp.pageSetup.reload = function() {  
    // do all the normal page setup
    glassApp.pageSetup.init();
    // re-scan for code blocks
    Prism.highlightAll();
};
</code></pre>

<p>Option 2 - Hack something together to <strong>parse the GET data for script tags and <a href="http://technify.me/user-experience/javascript/executing-javascript-in-an-ajax-response/">execute them manually</a></strong>, which just sounds like an awful idea from the get-go. You might be tempted to do <a href="http://blog.devlpr.net/2012/04/29/how-to-get-script-tags-with-jquery-find-from-ajax-result">really gross things</a> that will almost certainly get you into trouble. Maybe store loaded resources in an array so as not to load the same script/stylesheet more than once? You might also need to remove certain scripts from page to page, lest your site crumple to its knees.</p>

<p>If you're a tricky son of a gun, you might be able to make it work, but you can see we're not in Kansas anymore. It was around this point that I began questioning whether this enhancement was really worth the hassle.</p>

<h2 id="summingup">Summing up</h2>

<p>Moral of the story: <em>don't try to add Hijax to a public WordPress theme</em>. Because third-party scripts generally need to be hard-coded into the theme for Hijax to work properly, compatibility with JavaScript plugins is pretty limited.</p>

<p>If you do have control, though, I say go for it. The responsiveness of a well-tailored Ajax-driven website is a wonderful thing, and once you know when to use it, you'll want to implement it in every project.</p>]]></content:encoded></item><item><title><![CDATA[Code Snippet: Re-enable Ctrl/Cmd-click when using e.preventDefault()]]></title><description><![CDATA[<p>In Windows and OSX, pressing control or command while clicking a link opens it in a new tab. Using <code>event.preventDefault()</code> on anchor tags breaks this native behavior, but you can use this code to restore it.</p>

<pre><code class="language-javascript">// allow command-click and control-click to open new tab
if (event.metaKey || event.ctrlKey)</code></pre>]]></description><link>http://my-ghost-blog.com/allow-ctrl-command-click-using-event-preventdefault/</link><guid isPermaLink="false">d65b4711-2287-416a-a8f8-71b9bd7b40fc</guid><category><![CDATA[programming]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Tue, 05 Aug 2014 23:34:40 GMT</pubDate><content:encoded><![CDATA[<p>In Windows and OSX, pressing control or command while clicking a link opens it in a new tab. Using <code>event.preventDefault()</code> on anchor tags breaks this native behavior, but you can use this code to restore it.</p>

<pre><code class="language-javascript">// allow command-click and control-click to open new tab
if (event.metaKey || event.ctrlKey) {  
    return;
} else {
    event.preventDefault();
}
</code></pre>]]></content:encoded></item><item><title><![CDATA[Recursion: Nature's Cheat Code]]></title><description><![CDATA[<p>In his famous 1979 book <u>Gödel, Escher, Bach: An Eternal Golden Braid</u>, Douglas Hofstadter coined "Hofstadter's Law" to describe when computers would best humans in chess:</p>

<blockquote>  
<strong>Hofstadter's Law</strong>: It always takes longer than you expect, even when you take into account Hofstadter's Law.  
<cite>Douglas Hofstadter, <u>Gödel, Escher, Bach: An Eternal</u></cite></blockquote>]]></description><link>http://my-ghost-blog.com/recursion-natures-cheat-code/</link><guid isPermaLink="false">328f1c6c-5531-4c10-8f02-1dc95baf2d88</guid><category><![CDATA[programming]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Thu, 03 Jul 2014 23:27:52 GMT</pubDate><content:encoded><![CDATA[<p>In his famous 1979 book <u>Gödel, Escher, Bach: An Eternal Golden Braid</u>, Douglas Hofstadter coined "Hofstadter's Law" to describe when computers would best humans in chess:</p>

<blockquote>  
<strong>Hofstadter's Law</strong>: It always takes longer than you expect, even when you take into account Hofstadter's Law.  
<cite>Douglas Hofstadter, <u>Gödel, Escher, Bach: An Eternal Golden Braid</u></cite>  
</blockquote>

<p>The statement is an instance of recursion, where an object contains a reference to itself. Throughout <u>G.E.B.</u>, Hofstadter outlines a theory in which consciousness is the inevitable result of "<a href="http://en.wikipedia.org/wiki/Strange_loop">strange loops</a>"&mdash;or complex, hierarchical, recursive structures&mdash;happening within our own brains.</p>

<p>Recursion can clearly have humorous qualities. A hidden punchline, for instance. In a <a href="http://xkcd.com/917/">nod to Hofstadter</a>, Randall Munroe of XKCD created:</p>

<blockquote>
  <p>I'm So Meta, Even This Acronym</p>
</blockquote>

<p>The powerful nature of recursion has been known to mathematicians for hundreds of years. Take for example the equation:</p>

<blockquote>  
$f_n = f_{n-1} + f_{n-2}$
</blockquote>

<p>If we let $f_0 = 1$ and $f_1 = 1$, this equation renders the <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci sequence</a>, a mathematical concept that has fascinated artists, scientists and mathematicians for ages, and which is found <a href="https://www.youtube.com/watch?v=ahXIMUkSXX0">over and over again in nature</a>.</p>

<blockquote>  
$f_0 = 1$<br>
$f_1 = 1$<br>
$f_2 = f_0 + f_1 = 1 + 1 = 2$<br>
$f_3 = f_1 + f_2 = 1 + 2 = 3$<br>
$f_4 = f_2 + f_3 = 2 + 3 = 5$
</blockquote>

<p>The beauty of recursive structures lies in the disconnect between their simplicity and their extraordinary power. Take for instance the <a href="http://en.wikipedia.org/wiki/Mandelbrot_set">Mandelbrot set</a>, a manifestation of a simple recursive equation:</p>

<blockquote>  
$z_{n+1} = z_n^2 + c$
</blockquote>

<p>It seems easy enough for Fibonacci, but things can quickly get out of hand when trying to construct a recursive algorithm. In computer science education, programmers are taught not only to understand recursion, but also to <a href="http://imgur.com/yfckHO5">"trust" it</a>. Attempting to trace the logic down more than a couple levels will lead ultimately to madness. Our job as programmers is simply to set up the scaffolding, and trust that if it works for simple input, then it should work for more complex input.</p>

<p>Let's try an example from <a href="https://projecteuler.net/problem=31">Project Euler</a>.</p>

<h2 id="theproblem">The Problem</h2>

<p>In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:</p>

<blockquote>
  <p>1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).</p>
</blockquote>

<p>It is possible to make £2 in the following way:</p>

<blockquote>
  <p>1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p</p>
</blockquote>

<p>How many different ways can £2 be made using any number of coins?</p>

<h2 id="planofattack">Plan of Attack</h2>

<p>How would you go about solving this problem without a computer? Most of the time, if you can think of a systematic way of doing it manually, you can make the computer do it for you.</p>

<p>To make the problem more managable, let's see if we can make something work with just three coins: 200p (2£), 100p (1£), and 50p.</p>

<p>Recursion is not just an abstract concept; we use it naturally all the time in problem solving. In fact, one of the most natural ways of solving this problem is actually recursive. I set it up here with nested lists to show the logic visually. We'll work our way down from the highest value coin (200p) to the lowest (50p).</p>

<p>Imagine you have a bowl of coins in front of you.</p>

<ol>
<li>Take a 200 <br>
<ol><li>Subtotal (200) = 200</li>
<li>Add 1 to combos (0+1=1), go back</li></ol></li>
<li>Take a 100 <br>
<ol><li>Subtotal (100) &lt; 200</li>
<li>Take a 100
<ol><li>Subtotal (200) = 200</li>
<li>Add 1 to combos (1+1=2), go back</li></ol></li>
<li>Take a 50
<ol><li>Subtotal (150) &lt; 200</li>
<li>Take a 50
<ol><li>Subtotal (200) &lt; 200</li>
<li>Add 1 to combos (2+1=3), go back</li></ol></li>
<li>No more smaller coins, go back</li></ol></li>
<li>No more smaller coins, go back</li></ol></li>
<li>Take a 50 <br>
<ol><li>Subtotal (50) &lt; 200</li>
<li>Take a 50
<ol><li>Subtotal (100) &lt; 200</li>
<li>Take a 50
<ol><li>Subtotal (150) &lt; 200</li>
<li>Take a 50
<ol><li>Subtotal (200) = 200</li>
<li>Add 1 to combos (3+1=4), go back</li></ol></li>
<li>No more smaller coins, go back</li></ol></li>
<li>No more smaller coins, go back</li></ol></li>
<li>No more smaller coins, go back</li></ol></li>
<li>No more smaller coins  </li>
<li>Total = 4</li>
</ol>

<p>Notice how at each level of depth, we are applying the exact same rules as the level above it. That is recursion!</p>

<h2 id="thesolution">The Solution</h2>

<p>Though we'll be going through it step by step in this post, the truth is that programming is never a straightforward task. You will be jumping from one section of code to the other. Getting everything to work together requires a lot of tinkering, and tinkering takes time.</p>

<p>So here is the complete javascript program we're building. Take a look and see if you can understand how it all works together.</p>

<pre><code class="language-javascript">var coins = [200,100,50,20,10,5,2,1],  
    target = 200,
    combos = 0;

function add_coin(coin,subtotal) {  
    var sub_combos = 0;
    subtotal += coins[coin];
    if (subtotal &gt; target) return 0;
    if (subtotal === target) return 1;
    for (var c = coin; c &lt; coins.length; c++) {
        sub_combos += add_coin(c,subtotal);
    }
    return sub_combos;
}

for (var c = 0; c &lt; coins.length; c++) {  
    combos += add_coin(c,0);
}

console.log(combos);  
</code></pre>

<h2 id="breakingitdown">Breaking It Down</h2>

<p>First we'll set up an array of coins, the target value (200p) and a variable to hold the number of combinations we end up with.</p>

<pre><code class="language-javascript">var coins = [200,100,50,20,10,5,2,1],  
    target = 200,
    combos = 0;
</code></pre>

<p>We start by choosing each starting coin in succession, from highest value to lowest. We then call the function <code>add_coin()</code>, which returns the number of sub-combinations using each starting coin and add that value to <code>combos</code>. We have to send the function two parameters: (1) the current coin, and (2) the current subtotal. Since we are adding the first coin, the subtotal is 0.</p>

<pre><code class="language-javascript">for (var c = 0; c &lt; coins.length; c++) {  
    combos += add_coin(c,0);
}
</code></pre>

<p>Next, we'll set up a function which will systematically add coins one at a time, and eventually return the number of sub-combinations for that starting coin.</p>

<pre><code class="language-javascript">function add_coin(coin,subtotal) {  
    var sub_combos = 0;
    subtotal += coins[coin];

    // check the subtotal against the target
    // return 0 if we go over, or a 1 if we hit the target
    if (subtotal &gt; target) return 0;
    if (subtotal === target) return 1;

    // we're below the target, so choose next coin
    for (var c = coin; c &lt; coins.length; c++) {
        // call add_coin() again and add the result to sub_combos
        sub_combos += add_coin(c,subtotal);
    }
    // return the accumulated sub_combos once all coins have been tried
    return sub_combos;
}
</code></pre>

<ul>
<li><code>sub_combos</code> - holds the running total of sub-combinations in the current instance of <code>add_coin()</code></li>
<li><code>subtotal</code> - keeps track of the value of our current set of coins.</li>
</ul>

<p>It's important to understand that each instance of <code>add_coin()</code> has its very own <code>sub_combos</code>, which doesn't interact with any other level until it is returned.</p>

<p>Basically what is happening is that each time <code>add_coin()</code> is called, a new <code>sub_combos</code> is set up and the value of the new coin is added to <code>subtotal</code>. Unless <code>subtotal</code> matches or exceeds the <code>target</code>, it will call <code>add_coin()</code> again. When the <code>target</code> is reached, it will return a value to the level above it, increment that level's <code>sub_combos</code> and continue the process with the next coin, until all levels run out of smaller coins and return cascading to the top.</p>

<p>You can see here that we're only ever adding 1 to <code>sub_total</code>. That means that whatever the output is (SPOILER: it's 73682), <code>add_coin()</code> must have run at least that many times!</p>

<p>Another interesting thing to note is that since the function only adds a single coin, the number of coins you currently have is the same as the number of levels deep into the recursion you are. Since the maximum number of coins is 200 (200x1p), the program will go 200 levels deep!</p>

<h2 id="theoriginofcomplexity">The Origin of Complexity</h2>

<p>An algorithm is like a piece of music. In the same way that great music has <a href="https://www.youtube.com/watch?v=1v5-3_H_9xM">not a note too many</a>, beautiful algorithms are short and stylish. Recursion is a way to cheat, almost, a way to do more than you should be able to. The fact that meaningful recursion even exists can boggle the mind. </p>

<p>Boggling though it is, recursion is a fundamental mechanism of life itself. The origin of complexity. To go from sprout to spruce, you don't need DNA for every branch. You just need the right equation.</p>

<p>So when I'm building a recursive algorithm, I can't help but feel like I'm doing something really sneaky, like I'm stealing a tool from nature's toolshed, which, if my logic is sound, makes me Prometheus, and nature? Well, I'm sure nature has something in store for me.</p>

<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>  

<script type="text/x-mathjax-config">MathJax.Hub.Config({tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}});</script>]]></content:encoded></item><item><title><![CDATA[Scratch Style Guide]]></title><description><![CDATA[<p>Welcome to Scratch! This is your guide to writing beautiful blog posts. All of Scratch's default formatting options are summed up right here.</p>

<h2 id="tableofcontents">Table of contents</h2>

<ul>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#headings">Headings</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#text">Text</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#blockquotes">Blockquotes</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#lists">Lists</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#media">Media</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#syntaxhighlighting">Syntax Highlighting</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#tables">Tables</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#helperclasses">Helper Classes</a></li>
</ul>

<h2 id="headings">Headings</h2>

<p>In Scratch, <code>&lt;h1&gt;</code> tags are reserved for site and post titles.</p>]]></description><link>http://my-ghost-blog.com/glass-style-guide/</link><guid isPermaLink="false">b884ec86-6b70-480b-b1fb-985b0753c039</guid><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Thu, 26 Jun 2014 05:51:18 GMT</pubDate><content:encoded><![CDATA[<p>Welcome to Scratch! This is your guide to writing beautiful blog posts. All of Scratch's default formatting options are summed up right here.</p>

<h2 id="tableofcontents">Table of contents</h2>

<ul>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#headings">Headings</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#text">Text</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#blockquotes">Blockquotes</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#lists">Lists</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#media">Media</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#syntaxhighlighting">Syntax Highlighting</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#tables">Tables</a></li>
<li><a href="http://my-ghost-blog.com/glass-style-guide/#helperclasses">Helper Classes</a></li>
</ul>

<h2 id="headings">Headings</h2>

<p>In Scratch, <code>&lt;h1&gt;</code> tags are reserved for site and post titles. They do not have any special formatting.</p>

<h2 id="headingtext">## Heading Text</h2>

<p>Sustainable Helvetica food truck, 3 wolf moon beard Truffaut art party McSweeney's raw denim banjo Kickstarter disrupt freegan four loko.</p>

<h3 id="headingtext">### Heading Text</h3>

<p>Master cleanse cray next level, art party Bushwick skateboard High Life meh drinking vinegar squid kogi letterpress quinoa.</p>

<h4 id="headingtext">#### Heading Text</h4>

<p>Butcher asymmetrical sriracha, meh kale chips Bushwick narwhal food truck.</p>

<h5 id="headingtext">##### Heading Text</h5>

<p>Blue Bottle banjo drinking vinegar, mustache next level organic American Apparel photo booth cardigan.</p>

<h6 id="headingtext">###### Heading Text</h6>

<p>Freegan master cleanse farm-to-table, street art pug Odd Future disrupt typewriter Cosby sweater wolf Banksy actually Thundercats.</p>

<h2 id="text">Text</h2>

<p>This is a paragraph. <strong>Some sentences are bolded</strong>. <em>Some are italicized</em>. You can even add inline code blocks by using backticks <code>`&lt;p&gt;code block&lt;/p&gt;`</code> in the markdown editor. Inline links <a href="http://my-ghost-blog.com/glass-style-guide/#">like this one</a> can be added using <code>[text](http://the-url.com)</code>. Scratch supports more HTML tags than you'll ever need.</p>

<p><strong>Markdown</strong></p>

<pre class="language-markup wrap-text"><code>This is a paragraph. **Some sentences are bolded**. _Some are italicized_. You can even add inline code blocks by using backticks `` `&lt;p>code block&lt;/p>` `` in the markdown editor. Inline links [like this one](#) can be added using `[text](http://the-url.com)`. Scratch has support for more html tags than you'll ever think to use.</code></pre>

<h2 id="blockquotes">Blockquotes</h2>

<h3 id="normalblockquote">Normal Blockquote</h3>

<blockquote>
  <p>Banksy Schlitz deep v, cred selfies artisan semiotics Austin PBR biodiesel mlkshk retro kitsch. Tofu readymade Cosby sweater paleo Wes Anderson Williamsburg, cliche deep v viral four loko next level meggings tousled. You probably haven't heard of them hella flexitarian, Marfa meh kitsch iPhone jean shorts.</p>
</blockquote>

<p><strong>Markdown</strong></p>

<pre><code>&gt; Banksy Schlitz deep v, cred selfies artisan semiotics Austin PBR biodiesel mlkshk retro kitsch. Tofu readymade Cosby sweater paleo Wes Anderson Williamsburg, cliche deep v viral four loko next level meggings tousled. You probably haven't heard of them hella flexitarian, Marfa meh kitsch iPhone jean shorts.
</code></pre>

<h3 id="pullquote">Pullquote</h3>

<p>Austin 8-bit Schlitz, occupy bespoke leggings fashion axe cliche literally American Apparel trust fund craft beer fap shabby chic. Wayfarers synth typewriter, shabby chic before they sold out squid put a bird on it gentrify ethical.</p>

<blockquote class="pullquote">Dreamcatcher pug deep v blog seitan. Quinoa locavore skateboard bitters photo booth.</blockquote>

<p>Slow-carb cray polaroid, hashtag selvage trust fund Vice salvia crucifix fixie mustache Schlitz pop-up American Apparel. Pork belly food truck hella messenger bag. Scenester ennui asymmetrical bitters disrupt.</p>

<p><strong>Markdown</strong></p>

<pre><code class="language-markup">&lt;blockquote class="pullquote"&gt;Dreamcatcher pug deep v blog seitan. Quinoa locavore skateboard bitters photo booth.&lt;/blockquote&gt;  
</code></pre>

<h2 id="lists">Lists</h2>

<h3 id="numberedlist">Numbered List</h3>

<ol>
<li>Put on silly hat  </li>
<li>Run around screaming wildly  </li>
<li>????  </li>
<li>Profit</li>
</ol>

<p><strong>Markdown</strong></p>

<pre><code>1. Put on silly hat  
2. Run around screaming wildly  
3. ????  
4. Profit  
</code></pre>

<h3 id="unorderedlist">Un-ordered list</h3>

<ul>
<li>Milk</li>
<li>Apples</li>
<li>Tortilla Chips</li>
</ul>

<p><strong>Markdown</strong></p>

<pre><code>* Milk
* Apples
* Tortilla Chips
</code></pre>

<h3 id="nestedlists">Nested Lists</h3>

<ol>
<li>Fruit <br>
<ul><li>Apple</li>
<li>Banana</li>
<li>Bread</li></ul></li>
<li>Vegetables <br>
<ul><li>Potato
<ul><li>Idaho</li>
<li>Red</li>
<li>Yukon Gold</li></ul></li>
<li>Cheddar</li>
<li>Ketchup</li></ul></li>
<li>Protein <br>
<ul><li>Lengthy list items wrap nicely, so no matter what&mdash;even if they're super-rambling, talking about this or that, or that or this&mdash;even then, they still look clean.</li>
<li>Beans</li></ul></li>
</ol>

<p><strong>Markdown</strong></p>

<pre><code>1. Fruit  
    * Apple
    * Banana
    * Bread
2. Vegetables  
    * Potato
        * Idaho
        * Red
        * Yukon Gold
    * Cheddar
    * Ketchup
3. Protein  
    * Lengthy list items wrap nicely, so no matter what&amp;mdash;even if they're super-rambling, talking about this or that, or that or this&amp;mdash;even then, they still look clean.
    * Beans
</code></pre>

<hr>

<h2 id="media">Media</h2>

<h3 id="imagewithcaption">Image with Caption</h3>

<div class="caption">  
<img src="http://i.imgur.com/b4y3Omc.jpg" alt="">
Image by <a href="http://www.morguefile.com/creative/Archbob">Archbob</a>, via <a href="http://www.morguefile.com/">morguefile</a>.  
</div>

<pre><code class="language-markup">&lt;div class="caption"&gt;  
    ![image alt](/path/to/image.jpg)
    Image by &lt;a href="http://www.morguefile.com/creative/AcrylicArtist"&gt;AcrylicArtist&lt;/a&gt;, via &lt;a href="http://www.morguefile.com/"&gt;morguefile&lt;/a&gt;.
&lt;/div&gt;  
</code></pre>

<h3 id="linkedimage">Linked Image</h3>

<div class="caption">  
<a href="http://imgur.com/2J7YwIG">  
<img src="http://placekitten.com/500/300" alt="">
</a>  
Image by <a href="http://www.morguefile.com/creative/unageek">unageek</a>, via <a href="http://www.morguefile.com/">morguefile</a>.  
</div>

<pre><code>[![image alt](/path/to/image.jpg)](http://example.com)
</code></pre>

<h3 id="video">Video</h3>

<p>All you need to do is copy in the embed code from YouTube and Scratch does the rest!</p>

<iframe width="420" height="315" src="//www.youtube.com/embed/_OBlgSz8sSM" frameborder="0" allowfullscreen></iframe>

<pre><code>&lt;iframe width="420" height="315" src="//www.youtube.com/embed/_OBlgSz8sSM" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;  
</code></pre>

<h2 id="syntaxhighlighting">Syntax Highlighting</h2>

<p>For the programmers/bloggers out there, Scratch comes installed with the lightweight and wonderful Prism.js, which provides syntax highlighting on code blocks.</p>

<p>The markdown for a highlighted code block is:</p>

<pre><code>```language-markup
&lt;div class="your-code"&gt;
    &lt;p&gt;This is a great paragraph&lt;/p&gt;
&lt;/div&gt;
```
</code></pre>

<p>Some examples:</p>

<pre><code class="language-javascript">var coins = [200,100,50,20,10,5,2,1],  
    target = 200,
    combos = 0;

function add_coin(coin,subtotal) {  
    var sub_combos = 0;
    subtotal += coins[coin];
    if (subtotal &gt; target) return 0;
    if (subtotal === target) return 1;
    for (var c = coin; c &lt; coins.length; c++) {
        sub_combos += add_coin(c,subtotal);
    }
    return sub_combos;
}

for (var c = 0; c &lt; coins.length; c++) {  
    combos += add_coin(c,0);
}

console.log(combos);  
</code></pre>

<pre><code class="language-markup">&lt;div class="content"&gt;  
  &lt;p&gt;&lt;em&gt;HTML&lt;/em&gt; syntax highlighting&lt;/p&gt;
&lt;/div&gt;  
</code></pre>

<pre><code class="language-scss">a {  
    text-decoration: none;
    color: #f00;
    &amp;:hover {
        text-decoration: underline;
    }
}
</code></pre>

<pre><code class="language-javascript">function update_title(new_title) {  
    var $title = $('title');
    $title.html(new_title);
}
</code></pre>

<pre><code>If no &lt;em&gt;language&lt;/em&gt; is specified, then no syntax &lt;strong&gt;highlighting&lt;/strong&gt;.  
</code></pre>

<h2 id="tables">Tables</h2>

<table>  
  <thead>
    <tr>
      <th>Numbers</th>
      <th>Letters</th>
      <th>HTML</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>A</td>
      <td><strong>Looks</strong></td>
    </tr>
    <tr>
      <td>2</td>
      <td>B</td>
      <td><em>Pretty</em></td>
    </tr>
    <tr>
      <td>3</td>
      <td>C</td>
      <td><del>Nice</del> AWESOME</td>
    </tr>
  </tbody>
</table>

<pre><code class="language-markup">&lt;table&gt;  
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Numbers&lt;/th&gt;
      &lt;th&gt;Letters&lt;/th&gt;
      &lt;th&gt;HTML&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;A&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Looks&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;B&lt;/td&gt;
      &lt;td&gt;&lt;em&gt;Pretty&lt;/em&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;C&lt;/td&gt;
      &lt;td&gt;&lt;del&gt;Nice&lt;/del&gt; AWESOME&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;  
</code></pre>

<h2 id="helperclasses">Helper classes</h2>

<pre><code class="language-scss">.align-left {
    float: left;
}

.align-right {
    float: right;
}

.hidden {
    display: none !important;
    visibility: hidden !important;
}
</code></pre>]]></content:encoded></item><item><title><![CDATA[Counterpoint - Hacking the WordPress Loop]]></title><description><![CDATA[<p>Early on in every web developer's career, there comes a time when the Google teat runneth dry. All of a sudden, your good, clean, best-practiced code is in danger of mutating into cascades of if-statements and ugly hacks, just like your own brain. </p>

<p>Stop. Backspace that sentence and a half</p>]]></description><link>http://my-ghost-blog.com/counterpoint-hacking-the-wordpress-loop/</link><guid isPermaLink="false">a6ea0a7c-3afe-4bc2-9bb9-dab125baa7e7</guid><category><![CDATA[programming]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Fri, 23 May 2014 19:30:45 GMT</pubDate><content:encoded><![CDATA[<p>Early on in every web developer's career, there comes a time when the Google teat runneth dry. All of a sudden, your good, clean, best-practiced code is in danger of mutating into cascades of if-statements and ugly hacks, just like your own brain. </p>

<p>Stop. Backspace that sentence and a half you've typed into the search bar and face the facts, man: Google has failed you. It's time to brandish your machete and start hacking.</p>

<h2>Meet Counterpoint</h2>

<p>Counterpoint is the project that's taken up the majority of my life for the past 3 months. It is a full-scale WordPress theme (which handles the blog's visual presentation), and is currently undergoing a review process before it is accepted into the WordPress Theme Directory, so anyone creating a new WordPress blog can use it as their theme, free of charge.</p>

<p>The development process was pretty intense, and I learned a ridiculous amount along the way. All in all, the code spans 39 files totaling 11 megabytes. And that doesn't even count all the debugged and rewritten code, which is where most of my time was spent.</p>

<p>It's not perfect. There are still plenty of things about it, visual or otherwise, which give me the heebie-jeebies. But it's really become something of a companion: as Counterpoint evolves, new coding challenges arise, pushing me to further my skills. As my skills develop, I test them out on Counterpoint, and the cycle continues.</p>

<p>During my journey I've been helped by an army of codices, blog posts, and even real-life humans. This post is an opportunity to give back, in whatever small way, so that when others confront similar issues, my solution is available as a reference.</p>

<h2>The Goal</h2>

<p>OKAY. At the top of my theme's blog index, I want to display the most recent sticky post (for the non-bloggers out there, you can mark a post "sticky" to make it appear at the top of your blog). The sticky spans the entire width of the content area. After that, I want all other posts to display normally, with a user-defined number of posts per page.</p>

<p>So, if the user sets their posts-per-page to 6, there will be a single sticky and six more posts on the front page---for a total of 7---and 6 normal posts on each subsequent page.</p>

<p>The reason for this is that I chose to display in 2 columns, and I don't want a big open space at the bottom-right side of the page. Because stickies stretch the entire width of both columns, taking up the space of two regular posts, it is necessary to ensure that the front page gets served an even number of posts following the sticky.</p>

<p><img src="http://my-ghost-blog.com/content/images/2014/Sep/counterpoint1.jpg " image="" of="" the="" big="" ugly="" gap="" at="" bottom="" homepage""="" alt="Image of the big ugly gap at the bottom of the homepage"></p>

<p>Otherwise this happens.</p>

<h2>The Problem</h2>

<p>Of course, I wouldn't be writing this post if it was trivial.</p>

<p>I'm not going to get too deep into the nitty-gritty on this post, but if you're interested in <a href="http://blog.teamtreehouse.com/wordpress-loop-beginners-guide" title="A Comprehensive Beginners Guide to the WordPress Loop | Team Treehouse Blog">a more detailed explanation of the WordPress loop</a>, there are plenty of good resources out there. For now, what you need to know is that "the loop" is what grabs all your blog posts via a <em>query</em>, which can be given different arguments to retrieve the exact posts you need.</p>

<p>The problem lies in the way WordPress handles sticky posts. If the sticky post is already supposed to appear on the front page, the usual behavior is to simply move it to the top. However, if the sticky post doesn't naturally appear on the front page, it will be added to the front page IN ADDITION TO appearing in its natural position. Let me rephrase that: sticky posts will appear either once OR twice depending on its position in the query.</p>

<p>It gets even more complicated. When a sticky is drawn from outside the front page, it doesn't count towards the posts-per-page limit. This means we'll end up displaying a different number of posts depending on where the sticky came from. Theoretically, even with posts-per-page set at 6, the front page could have any number of additional posts, depending on the number of stickies that were prepended to the query.</p>

<p>It's an interesting solution to avoiding duplicate material on the front page, but as you can see it does lead to some frustrating design issues:</p>

<ul>  
<li>If I try setting posts-per-page to an odd number to avoid the space at the end of the page, every subsequent page has the gap.</li>  
<li>If I set posts-per-page to an even number, the design breaks when the sticky post is taken from the front page.  
</li></ul>

<p>We can see that the normal loop is not going to help us here. No matter our settings, there is going to be a gap somewhere, and as a perfectionist, I cannot let that happen.</p>

<h2>The Solution</h2>

<p>The solution is two loops. The first loop displays the most recent sticky. The second displays the rest. However, if the sticky is from the front page, we get that silly duplication like this:</p>

<p><img src="http://my-ghost-blog.com/content/images/2014/Sep/counterpoint2.jpg " example="" of="" a="" duplicated="" sticky="" post""="" alt="Example of a duplicated sticky post"></p>

<p>If it's such a problem, why don't I just skip that post in the second loop, thereby removing the duplicate? Unfortunately, to get a theme accepted into the WordPress Theme Archive, the natural behavior of duplicating a sticky in its normal, non-front-page position is REQUIRED. We'll have to be more clever than that.</p>

<p>Let's get started.</p>

<pre><code class="language-php">/* Loop #1 - for stickies
========================== */

// get an array of stickies
$stickies = get_option('sticky_posts');
// get the first one, or set it to false if none
$first_sticky = $stickies ? end($stickies) : false;
// get the posts_per_page variable (set by user)
$ppp = get_option('posts_per_page');


//  if a sticky exists and it's the front page...
if ( $first_sticky &amp;&amp; is_front_page() &amp;&amp; !is_paged() ) {

    // query the most recent sticky post
    $most_recent_sticky_post = new WP_Query( 'p=' . $first_sticky );

    // and display it
    while ($most_recent_sticky_post-&gt;have_posts()) : $most_recent_sticky_post-&gt;the_post();

        // code to display the post

    endwhile;

}
wp_reset_postdata();  
</code></pre>

<p>This is easy enough. Get the first sticky, query it, and display it. Then use <code>wp_reset_postdata()</code> to make sure subsequent queries are unaffected.</p>

<p>Before moving on to the main query, we first need to determine where the sticky came from. Sadly, this was one of those instances where google was not much help. My sketchy solution was to do an extra query and search for the sticky in the first 'n' posts, where 'n' is the user-defined posts-per-page. The result is stored in the variable <code>$front_page_sticky</code>. It's convoluted, but to my knowledge, it is the only way to do what I want.</p>

<pre><code class="language-php">$front_page_sticky = false;

// only do this if there's a sticky in the first place
if ( $first_sticky ) {

    // so here's the junk query
    $junk_query = new WP_Query(array(
        // ignore normal sticky behavior
        'ignore_sticky_posts' =&gt; 1
    ));

    // loop through the posts in $junk_query
    foreach($junk_query-&gt;posts as $post_num=&gt;$junk_post) {

        // if it comes across the $first_sticky within the first page of posts...
        if ($post_num &lt; $ppp &amp;&amp; $junk_post-&gt;ID === $first_sticky) {
            // set this to true, then quit
            $front_page_sticky = true;
            break;

        // if there's no match, leave $front_page_sticky false...
        } elseif ($post_num &gt;= $ppp) {
            break;
        }
    }
    wp_reset_postdata();
}
</code></pre>

<p>Cool. Now we have all the variables we need to set up our query arguments (we'll store them in a variable called <code>$cp_args</code>). Because every page of our results runs this same code, it's vital to make sure that it's served a specialized query for each page. Based on our desired behavior, there are two situations which require us to alter the default query:</p>

<ol>  
<li>if there is a front-page sticky</li>  
<li>if we're not on the front page</li>  
</ol>

<p>Since these are not mutually exclusive, we'll check each with separate if-statements, adding the appropriate arguments to <code>$cp_args</code>.</p>

<pre><code class="language-php">// ignore sticky behavior no matter what
$cp_args = array(
    'ignore_sticky_posts' =&gt; 1
);

// if there is a front-page sticky, skip it in the query
if ( $front_page_sticky ) {  
    $cp_args['post__not_in'] = array($first_sticky);
}

// if we're not on the front page, set an offset so we don't get the same posts as the front page
if ( is_paged() ) {  
    $cp_args['offset'] = ($wp_query-&gt;query_vars['paged'] - 1) * $ppp;
}
</code></pre>

<p>All done! Now we can run the query.</p>

<pre><code class="language-php">// now for the main query
$main_query = new WP_Query($cp_args);

while ($main_query-&gt;have_posts()) : $main_query-&gt;the_post();

    // code to display the post

endwhile;  
wp_reset_postdata();  
</code></pre>

<h2>One Last Thing</h2>

<p>Any time we're not on the main blog index (for searches and archive pages), stickies don't apply, so I just want to do a basic query. For that, I'm going to wrap everything in:</p>

<pre><code class="language-php">if ( is_home() ) {

    // all of the previous code

} else {

    // run the default query if is_home() returns false
    // (i.e. search and archive pages)
    while (have_posts()) : the_post();

        // code to display the post

    endwhile;
}
</code></pre>

<h2>Reflection</h2>

<p>The programming community is extremely open with its intellectual property. Pretty much any and all new technologies and techniques are piously shared with the rest of the community, such that anyone skilled in Google-fu will discover it's almost hard NOT to find a wholesale solution to your exact problem, right there on the front page.</p>

<p>It makes sense. There's always bigger and more interesting problems to solve down the line, and it's lost productivity every time we reinvent the wheel---intentionally or otherwise. This culture of openness allows us to live and die on the bleeding edge. It's no wonder why so many programmers are passionate about open source projects---it's not just philosophy, it's the <em>only game in town</em>. As new programmers cut their teeth, they stand not on the shoulders of giants, but on those multitudes of code-pushing peons who surfaced for just a moment to ask a poorly-phrased question on a public forum.</p>

<hr>

<p>Music. Math. Computers. As I move on to the next big thing, I am more and more sure that each step forward in programming is also a step towards self-actualization. In the set of variations so complete and sophisticated as one's life, the theme is often difficult to discern. But we can pick up on common aesthetic motifs, and in doing so, sometimes we get a glimpse of the whole composition. Eventually the threads will all come together, like the Finale of Beethoven's 3rd Symphony, a sonic boom of unity and perfect counterpoint.</p>]]></content:encoded></item><item><title><![CDATA[Gesualdo: Moro, lasso, al mio duolo]]></title><description><![CDATA[<p>The early hours of the morning are host to some of the more sublime experiences in an introvert's life. As the rest of the world goes to sleep, as the stress of the day fades away and the air in the room grows still, it becomes possible to corral, through</p>]]></description><link>http://my-ghost-blog.com/gesualdo-moro-lasso-al-mio-duolo/</link><guid isPermaLink="false">f31705d9-41fb-4a48-b500-8067fc0cbd2b</guid><category><![CDATA[Music]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Mon, 07 Apr 2014 07:30:01 GMT</pubDate><content:encoded><![CDATA[<p>The early hours of the morning are host to some of the more sublime experiences in an introvert's life. As the rest of the world goes to sleep, as the stress of the day fades away and the air in the room grows still, it becomes possible to corral, through music or poetry or some small act of creation, this ineffable sensation of eternity, of lineage and deep connection to the past. So we close our eyes, embrace it, and the common experience of silence fastens us to the timeline of Man, through Proust and Nietzsche, through Bach and Luther, through Galileo and Monteverdi, and so on, back to Earth's earliest storytellers.</p>

<p>One such figurehead of darkness is also one of the most fascinating figures in all of musicology. Carlo Gesualdo was an Italian nobleman infamous for murdering his first wife and her lover upon discovering them in an act of adultery. Depressed, guilty, and socially isolated, Gesualdo found expression through his compositions, which were arguably the most ecstatic and brazenly chromatic of the Renaissance, even the entire 17th century. Progressions of the sort found in his music were not seen again for 200 years.</p>

<iframe width="420" height="315" src="//www.youtube.com/embed/-_F1OuMeVSw" frameborder="0" allowfullscreen></iframe>

<p>Gesualdo's music is egoless, terrifying, and gorgeous. It's the mote of dust that you can't quite grasp. It's sleep paralysis. It's the realization that you're ultimately alone. It's absurdity. It's more than you or I can take.</p>

<blockquote>Moro, lasso, al mio duolo,<br>  
E chi può darmi vita,<br>  
Ahi, che m'ancide e non vuol darmi aita!<br>  
O dolorosa sorte,<br>  
Chi dar vita mi può,<br>  
Ahi, mi dà morte!</blockquote>

<blockquote>I die, alas, in my suffering<br>  
And she who could give me life,<br>  
Alas, kills me and will not help me.<br>  
O sorrowful fate,<br>  
She who could give me life,<br>  
Alas, gives me death.</blockquote>]]></content:encoded></item><item><title><![CDATA[On Math, Music, and the Poetry of Change]]></title><description><![CDATA[<p><img src="http://my-ghost-blog.com/content/images/2014/Jun/pascals-triangle-1.png#cover" alt="pascals triangle"></p>

<p>For two years since I turned my back on the masters degree program at the Cleveland Institute of Music, I felt as though I'd been stuck in a vicious pirouette, wobbling---NAY---<em>nutating</em> like a dreidel on a narrow outcrop above existential despair. So this past summer I wrenched myself free</p>]]></description><link>http://my-ghost-blog.com/shuffle-off-this-musical-coil-on-math-music-and-the-poetry-of-change/</link><guid isPermaLink="false">a82870f8-f972-4deb-aa0a-72f5b595d17b</guid><category><![CDATA[Music]]></category><category><![CDATA[programming]]></category><dc:creator><![CDATA[Evan Henley]]></dc:creator><pubDate>Thu, 30 Jan 2014 07:30:11 GMT</pubDate><content:encoded><![CDATA[<p><img src="http://my-ghost-blog.com/content/images/2014/Jun/pascals-triangle-1.png#cover" alt="pascals triangle"></p>

<p>For two years since I turned my back on the masters degree program at the Cleveland Institute of Music, I felt as though I'd been stuck in a vicious pirouette, wobbling---NAY---<em>nutating</em> like a dreidel on a narrow outcrop above existential despair. So this past summer I wrenched myself free of Cleveland's desolation in the hope that some ill-advised change would effect a spiritual hard reset. On my second day in Austin, I went to a nearby coffeeshop and happened upon one of my favorite poets, Anis Mojgani, who was working on his laptop in the corner. His raspy "welcome to Austin, best of luck" and the impression of his oddly-shaped hand traced into my notebook were the good omen which validated my decision to move back south.</p>

<p>That said, for the first time since I created this blog in late November of 2012, this is not a post about music. Fuck that. I'm going to write about math.</p>

<p>Frankly, this should have been called <a href="http://my-ghost-blog.com/current-obsessions-mozart-the-string-quartets-hagen-quartet/">Current Obsessions</a>, as it's more true now than ever, but I couldn't relinquish the Shakespeare pun. When my roommate Lyle (AKA <a href="http://lobsterhandstech.wordpress.com/">lobsterhands</a>) announced that he was starting a degree in Computer Science, I watched over his shoulder as he showed me his code. This toggled in me a primordial boolean switch, causing a long-dormant passion for programming to emerge volcano-like from this <a href="http://www.poemhunter.com/poem/the-floor/">teetering bulb</a> of a man, and for the past month, I've spent like, 4-10 hours a day coding. Notably, this is an amount of time I almost never dedicated to cello practice.</p>

<p><a href="http://projecteuler.net/about">Project Euler</a> is a set of mathematical challenges intended to be solved with some sort of computer programming. To begin chipping away at the 400-something problems, I chose to use Ruby, a beautiful object-oriented language designed with readability and productivity in mind, and whose subtleties I have just barely begun to fathom. Many websites (e.g. Hulu) are built on implementations of Ruby.</p>

<p>Late last night I sat down to work out <a href="http://projecteuler.net/problem=15">Problem 15</a>:</p>

<blockquote><strong>Lattice Paths</strong>. Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

<img src="http://my-ghost-blog.com/content/images/2014/Sep/lattice-paths.gif" alt="lattice paths">

How many such routes are there through a 20×20 grid?</blockquote>

<p>You're not really supposed to share solutions, but a) this is more of a procedural explanation, b) my way isn't necessarily the quickest or the most intuitive, and besides, c) nobody reads my blog. So I'm going for it. I started by brute forcing my way to find the number of routes through the first few cells, then did some fiddling with formulas to determine the number of possible routes to each intersection in a given row. It looked like this, but messier:</p>

<p><img src="http://my-ghost-blog.com/content/images/2014/Jun/screenshot-2014-01-30-at-3-03-31-am.png" alt=""></p>

<p>The numbers correspond to the intersection to their bottom-right. Noting also that each intersection was the sum of the intersections above it and to the left---e.g. <code>35 = (15 + 20)</code>, <code>56 = (21 + 35)</code>, etc.---I made a recursive formula to find a given spot, but so many calculations meant it took AGES to come to an answer. Then, at approximately 4 a.m., after a stupid amount of intuition-driven scribbles, I stumbled upon an interesting relationship between any number on the top-right side of the grid and the number diagonally down and left. To find the answer for a 5x5 grid, all one needed to do was make <code>x = 5 * 2</code>, and work your way down and to the left, multiplying like so:</p>

<pre><code class="language-ruby">10  * (9/2) = 45  
45  * (8/3) = 120  
120 * (7/4) = 210  
210 * (6/5) = 252  
</code></pre>

<p>And that was that. There are 252 possible routes through a 5x5 grid. Thus, a 20x20 (or larger!) grid could be solved by hand:</p>

<pre><code class="language-ruby">40  * (39/2) = 780  
780 * (38/3) = 9880  
9880 * (37/4) = 91390  
.
.
.
etc.  
</code></pre>

<p>...or by a neat little Ruby program:</p>

<pre><code class="language-ruby">def lattice(gridsize)  
  total = gridsize * 2  # sets total at 2 * 20 = 40
  n = (total - 1)       # numerator = 40-1 = 39
  d = 2.to_f            # denominator = 2
  while n &amp;gt; d
    total *= (n / d)    # multiplies total by n / d
    n -= 1
    d += 1
  end
  total.to_i
end

gridsize = 20  
p lattice(gridsize)     # calls function, prints result  
</code></pre>

<p>What I later found out is that this problem is basically <a href="http://en.wikipedia.org/wiki/Pascal%27s_triangle">Pascal's Triangle</a> and my solution is in essence the factorial expression for <a href="http://en.wikipedia.org/wiki/Binomial_coefficient#Factorial_formula">binomial coefficients</a>:</p>

<p><img src="http://my-ghost-blog.com/content/images/2014/Jun/c80e0b1eec6d52e229fdafa91191f49d.png" alt="binomial coefficients formula"></p>

<p>Plugging in 5, we can see that the equations are equal:</p>

<p><img src="http://my-ghost-blog.com/content/images/2014/Jun/my_eq1.png" alt="my equation"></p>

<p><img src="http://my-ghost-blog.com/content/images/2014/Jun/their_eq1.png" alt="their equation"></p>

<p>That said, I'm not sure exactly why this works, but it's all pretty neat.</p>

<hr>

<p>Now, basking in the post-coital contentment of a good math session, I realize that I am a lucky man. As Russell Edson might have said, the last couple years certainly pulled at the difficult head. The shame of quitting was (and is) real, but sometimes change beckons, and with it comes opportunity for salvation. Eventually I stopped spinning and found my balance, and as I backed away from the outcrop, I watched as the land, like Paschal's Triangle, opened up around me, and now suddenly, just as in older times, I am free to roam.</p>]]></content:encoded></item></channel></rss>