<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-7117612757607239790</atom:id><lastBuildDate>Wed, 01 Feb 2012 19:26:00 +0000</lastBuildDate><category>Microsoft Office</category><category>jQuery</category><category>Javascript</category><category>C</category><category>Gosu</category><category>YouTube</category><category>Security</category><category>Java</category><category>Syntax Highlighting</category><category>Mercurial</category><category>XNA</category><category>Game Development</category><category>ASP.NET</category><category>Farseer Physics Engine</category><category>C#</category><category>Haskell</category><category>Windows Phone 7</category><category>Vim</category><category>Electronics</category><category>Other</category><category>Mathematics</category><category>Arduino</category><category>Genetic Algorithms</category><category>Brainfuck</category><category>Ruby</category><category>Linux</category><category>Projects</category><category>Google Chrome Extensions</category><category>Ubuntu</category><category>Networks</category><category>Scheme</category><category>Facebook</category><category>LaTeX</category><category>Meta</category><title>Andreas Grech's Blog</title><description>Coffee, a pack of cigs and a keyboard</description><link>http://blog.dreasgrech.com/</link><managingEditor>noreply@blogger.com (Andreas Grech)</managingEditor><generator>Blogger</generator><openSearch:totalResults>98</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Knowledge-aholic" /><feedburner:info uri="knowledge-aholic" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>Knowledge-aholic</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-8066805116088819491</guid><pubDate>Wed, 01 Feb 2012 09:47:00 +0000</pubDate><atom:updated>2012-02-01T20:26:00.231+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><title>Creating POJOs in JavaScript</title><description>&lt;a href="http://en.wikipedia.org/wiki/Plain_Old_Java_Object" target="_blank"&gt;POJO&lt;/a&gt; stands for Plain Old Java Object, but in our case, it will be JavaScript instead of Java...&lt;i&gt;Plain Old JavaScript Objects&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
Sometimes in your code, you would need to create objects that are just containers for members (in OOP terms, these objects are usually referred to as &lt;i&gt;classes&lt;/i&gt;).&lt;br /&gt;
&lt;br /&gt;
As an example:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;var dog = function (name, age) {
 return {
       name: name,
       age: age
 };
};
&lt;/pre&gt;Now you can obviously write all this by hand, but you don't have to because you can write a function that makes use of JavaScript's &lt;a href="http://en.wikipedia.org/wiki/Type_system#Dynamic_typing" target="_blank"&gt;dynamic&lt;/a&gt; nature to do it for you:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;var pojo = function () {
    var members = arguments;

    return function () {
        var obj = {}, i = 0, j = members.length;
        for (; i &amp;lt; j; ++i) {
            obj[members[i]] = arguments[i];
        }

        return obj;
    };
};
&lt;/pre&gt;And this is how it can be used:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;var dog = pojo('name', 'age'), // create the POJO
    fido = dog('Fido', 2); // create an 'instance' of the POJO

// fido.name -&amp;gt; 'Fido'
// fido.age  -&amp;gt; 2

&lt;/pre&gt;The &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;pojo&lt;/span&gt; function is pretty straightforward.  First we grab a reference to the &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;arguments&lt;/span&gt; object (which contains the names of the members that we want to be in our object; &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;['name', 'age']&lt;/span&gt;) and then return a function which will serve as the initializer for our POJO object.&lt;br /&gt;
&lt;br /&gt;
Once the inner initializer function is invoked from the outside (&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;dog('Fido', 2)&lt;/span&gt;), we iterate through the member names we got from the initial &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;arguments&lt;/span&gt; object to create a new object (&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;obj&lt;/span&gt;) containing the member names and the values of the actual arguments that were passed to the inner function as their respective values.&lt;br /&gt;
&lt;br /&gt;
If you only want a single 'instance' of the POJO, you can get away with a one-liner:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;var fido = pojo('name', 'age')('Fido', 2);
&lt;/pre&gt;&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : "Please",
  name : "No More White Horses",
  link : 'http://grooveshark.com/s/No+More+White+Horses/3zyJBi?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-8066805116088819491?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/C6fqEzscvl8" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/C6fqEzscvl8/creating-pojos-in-javascript.html</link><author>noreply@blogger.com (Andreas Grech)</author><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2012/02/creating-pojos-in-javascript.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-7118643702561291305</guid><pubDate>Thu, 26 Jan 2012 21:16:00 +0000</pubDate><atom:updated>2012-01-26T22:16:47.404+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">YouTube</category><title>Bulk converting from YouTube-MP3.org</title><description>&lt;h4&gt;[Update]&lt;/h4&gt;Following an email conversation I had with Philip Matesanz, the owner of Youtube-MP3, I've decided to take down my github repository because of worries that my tool could be used to flood their server with requests.&lt;br /&gt;
&lt;br /&gt;
&lt;hr/&gt;&lt;a href="http://www.youtube-mp3.org/" target="_blank"&gt;YouTube-MP3.org&lt;/a&gt; is a free service which lets you convert YouTube videos to MP3s.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://www.youtube-mp3.org/" imageanchor="1" style="margin-left:1em; margin-right:1em" target="_blank"&gt;&lt;img border="0" src="http://3.bp.blogspot.com/-6I_UJlDyjYQ/Tm-0eikDCjI/AAAAAAAABDo/U515WnEb-kU/s1600/youtube-mp3.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
It's a great service, but you if you have many YouTube videos you want to convert, it can be a bit tedious to do them one by one while waiting for each one to complete and then download manually; and that's what I aimed to fix.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;Bulk downloading&lt;/h4&gt;I wrote this application which takes a text file that is filled with YouTube links as input and which then starts relaying those links to the YouTube-MP3 service for conversion and downloading.&lt;br /&gt;
&lt;br /&gt;
The text file needs to be structured as follows i.e. a YouTube link on each line:&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;http://www.youtube.com/watch?v=eslhuSEC_QU
http://www.youtube.com/watch?v=A7x_z6tG4yY
http://www.youtube.com/watch?v=MLxPknwiNoc
http://www.youtube.com/watch?v=WYV7qYyHKIs
http://www.youtube.com/watch?v=4f1K4HNnQWo
http://www.youtube.com/watch?v=SEsKwOrejec
http://www.youtube.com/watch?v=f4CwlUSSTzk
http://www.youtube.com/watch?v=G6ZsvYA-YTo
http://www.youtube.com/watch?v=tK7b3Y42w3k
http://www.youtube.com/watch?v=0ppTcHjvtsU
http://www.youtube.com/watch?v=8ZjADBfqOR4
http://www.youtube.com/watch?v=DW3ZpytL2Nk
http://www.youtube.com/watch?v=CsdzJTW7SUk
&lt;/pre&gt;&lt;br /&gt;
The process converting/downloading works in iterations.  Those videos which fail to convert/download during one iteration are moved to the next iteration so that the conversion/download can be tried again.  This is because YouTube-MP3 restricts its API usage to 10 conversion/downloads per hour.  Between each iteration, there is an interval during which the program is halted to wait until the iteration starts.&lt;br /&gt;
&lt;br /&gt;
The make the application more efficient, it converts/downloads videos simultaneously, rather than sequentially.  This means that the total running time of the program is equivalent to the longest-running job's time, not to the sum of all the job's times.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;Usage&lt;/h4&gt;&lt;pre&gt;Usage: BulkYoutubeMP3Console.exe [options] &amp;lt;Youtube links file&amp;gt;

Options:
  -p, --path=VALUE           The download path
  -t, --time=VALUE           The waiting time in minutes between the
                               iterations.  Minimum: 10 minutes
  -x, --proxy=VALUE          Use if you want to use a proxy for downloading.
                               Format =&gt; &lt;host&gt;:&lt;port&gt; (default 80)


&lt;/pre&gt;&lt;br /&gt;
You can find the source of app from &lt;strike&gt;&lt;a target="_blank" href="https://github.com/dreasgrech/bulk-youtube-mp3"&gt;https://github.com/dreasgrech/bulk-youtube-mp3&lt;/a&gt;&lt;/strike&gt;&lt;br /&gt;
&lt;br /&gt;
The following is an example run:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-XYIwL2o4HdQ/TncUW1gNzDI/AAAAAAAABDw/GfChssslxj8/s1600/BulkYoutubeMP3Console.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="238" width="400" src="http://2.bp.blogspot.com/-XYIwL2o4HdQ/TncUW1gNzDI/AAAAAAAABDw/GfChssslxj8/s400/BulkYoutubeMP3Console.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : "Mike D'Abo",
  name : "Handbags and Gladrags",
  link : 'http://grooveshark.com/s/Handbags+And+Gladrags/3JOq0X?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-7118643702561291305?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/oTNLtdUhu-g" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/oTNLtdUhu-g/bulk-converting-from-youtube-mp3org.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-6I_UJlDyjYQ/Tm-0eikDCjI/AAAAAAAABDo/U515WnEb-kU/s72-c/youtube-mp3.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2012/01/bulk-converting-from-youtube-mp3org.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-6619020320440847347</guid><pubDate>Thu, 26 Jan 2012 20:29:00 +0000</pubDate><atom:updated>2012-01-26T21:29:28.004+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><category domain="http://www.blogger.com/atom/ns#">Projects</category><category domain="http://www.blogger.com/atom/ns#">jQuery</category><title>Promoting your Chrome extension with a yellow infobar</title><description>This is a jQuery plugin I wrote which emulates Chrome's infobar for promoting a Google Chrome extension.&lt;br /&gt;
&lt;br /&gt;
The following are Chrome's infobar and the one I wrote for the plugin, respectively:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-ebZzuawFr8o/TxXHk0MfupI/AAAAAAAABGA/7hHJ-AOQQZk/s1600/chromebar.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-ebZzuawFr8o/TxXHk0MfupI/AAAAAAAABGA/7hHJ-AOQQZk/s1600/chromebar.png" width="750" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-sYWQSpyEes8/TxXHk4JpAqI/AAAAAAAABGI/pomc_m-pl2M/s1600/bar_default.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://4.bp.blogspot.com/-sYWQSpyEes8/TxXHk4JpAqI/AAAAAAAABGI/pomc_m-pl2M/s1600/bar_default.png" width="750" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;h4&gt;Demo&lt;/h4&gt;I've set up a small demo of the plugin here: &lt;a href="http://www.dreasgrech.com/upload/extinfobar/" target="_blank"&gt;http://www.dreasgrech.com/upload/extinfobar/&lt;/a&gt;.&lt;br /&gt;
&lt;h4&gt;Download&lt;/h4&gt;&lt;i&gt;&lt;a href="http://blog.jquery.com/2011/12/08/what-is-happening-to-the-jquery-plugins-site/" target="_blank"&gt;Until the jQuery plugins page is restored&lt;/a&gt;, you're gonna have to download this plugin directly from github.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
You can get the full source of the plugin from &lt;a href="https://github.com/dreasgrech/ChromeExtInfoBar" target="_blank"&gt;https://github.com/dreasgrech/ChromeExtInfoBar&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
These are all the images that you need:&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-qPoY3rqYXM8/TyGqg82TpMI/AAAAAAAABGs/HO6q_I_aWmY/s1600/button_click.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="25" width="3" src="http://2.bp.blogspot.com/-qPoY3rqYXM8/TyGqg82TpMI/AAAAAAAABGs/HO6q_I_aWmY/s1600/button_click.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-WrYIeZyHw54/TyGqhEQZuWI/AAAAAAAABG0/GUv--z4rgbs/s1600/button_gradient.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="25" width="3" src="http://1.bp.blogspot.com/-WrYIeZyHw54/TyGqhEQZuWI/AAAAAAAABG0/GUv--z4rgbs/s1600/button_gradient.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-yvhCr8lguZw/TyGqhNjn70I/AAAAAAAABHE/jFmass5x-hQ/s1600/close.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="10" width="10" src="http://3.bp.blogspot.com/-yvhCr8lguZw/TyGqhNjn70I/AAAAAAAABHE/jFmass5x-hQ/s1600/close.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-b5bliVBhDIc/TyGqhfW5xAI/AAAAAAAABHQ/BNUGNTcrX3U/s1600/close_hover.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="10" width="10" src="http://2.bp.blogspot.com/-b5bliVBhDIc/TyGqhfW5xAI/AAAAAAAABHQ/BNUGNTcrX3U/s1600/close_hover.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-89W83ukn4qg/TyGqhuNE7cI/AAAAAAAABHc/cgN4qP9gKTM/s1600/defaulticon.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="20" width="20" src="http://2.bp.blogspot.com/-89W83ukn4qg/TyGqhuNE7cI/AAAAAAAABHc/cgN4qP9gKTM/s1600/defaulticon.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-eGrkIkN1mS4/TyGquUiJQfI/AAAAAAAABHo/Yc0wJcoukHE/s1600/gradient_bar.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="35" width="5" src="http://2.bp.blogspot.com/-eGrkIkN1mS4/TyGquUiJQfI/AAAAAAAABHo/Yc0wJcoukHE/s1600/gradient_bar.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;h4&gt;Usage&lt;/h4&gt;The simplest way to use the plugin is to simply invoke it using just your Chrome extension ID:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;$.fn.extInfobar({
    id: 'nbilgjjflfiiijecdjpnbganoiafneph'
});
&lt;/pre&gt;&lt;br /&gt;
You can also specify a custom message to be displayed on the infobar, as opposed to the default message:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;$.fn.extInfobar({
    id: 'nbilgjjflfiiijecdjpnbganoiafneph',
    message: 'This is my custom message I want to show on the infobar'
});
&lt;/pre&gt;&lt;br /&gt;
There are three other optional parameters you can pass; &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;redirectIfInstallFails&lt;/span&gt;, &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;rememberClose&lt;/span&gt; and &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;rememberRedirect&lt;/span&gt;.  All three default to &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;true&lt;/span&gt; if unspecified.&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;$.fn.extInfobar({
    id: 'nbilgjjflfiiijecdjpnbganoiafneph',
    message: 'This is my custom message I want to show on the infobar',
    redirectIfInstallFails: false,
    rememberClose: false,
    rememberRedirect: false
});
&lt;/pre&gt;&lt;br /&gt;
&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;redirectIfInstallFails&lt;/span&gt; specifies whether the plugin should redirect the user to the extension's Chrome Webstore page if the installation happens to fail or if the site you're using the plugin on is not verified (more info on that below).&lt;br /&gt;
&lt;br /&gt;
When the user clicks on the close button, the action is remembered via &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;localStorage&lt;/span&gt; so that the bar is not displayed again for him but the &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;rememberClose&lt;/span&gt; parameter allows you to override this functionality; so if you set it to &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;false&lt;/span&gt;, the bar will keep appearing on subsequent page visits even if the user closed it.&lt;br /&gt;
&lt;br /&gt;
The last parameter, &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;rememberRedirect&lt;/span&gt;, is used to save the action of the plugin redirecting the user to the extension's Chrome Webstore; by default, the action is saved which means that once a user is redirected to the Chrome Webstore page, the bar will not be shown to him on subsequent visits to your page, but you can of course override this functionality by setting &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;rememberRedirect&lt;/span&gt; to false.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;How it works&lt;/h4&gt;The plugin makes use of Chrome's &lt;a href="http://code.google.com/chrome/webstore/docs/inline_installation.html" target="_blank"&gt;inline installation&lt;/a&gt; functionality, but note that this only works if your extension's website is &lt;a href="http://support.google.com/webmasters/bin/answer.py?hl=en&amp;amp;answer=35179" target="_blank"&gt;verified&lt;/a&gt; and this plugin is invoked from the same domain as the verified site.&lt;br /&gt;
&lt;br /&gt;
When you click on the 'Install' button on the infobar, and the context meets the two aforementioned criteria, the following modal dialog will pop up:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://4.bp.blogspot.com/-RQy2O5TLX-c/TxhsAra7kcI/AAAAAAAABGY/eylKuusDj50/s1600/inlineinstall.png" /&gt;&lt;/div&gt;&lt;br /&gt;
Otherwise, the user will be redirected directly to the extension's page on the &lt;a href="https://chrome.google.com/webstore/" target="_blank"&gt;Chrome Webstore&lt;/a&gt; (unless the &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;redirectIfInstallFails&lt;/span&gt; option is explicitly set to false).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Procol Harum',
  name : "Repent Walpurgis",
  link : 'http://grooveshark.com/s/Repent+Walpurgis/31S0Tn?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-6619020320440847347?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/xiuwo8oWaEE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/xiuwo8oWaEE/promoting-your-chrome-extension-with.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-ebZzuawFr8o/TxXHk0MfupI/AAAAAAAABGA/7hHJ-AOQQZk/s72-c/chromebar.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2012/01/promoting-your-chrome-extension-with.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-5025889989828882953</guid><pubDate>Thu, 26 Jan 2012 18:23:00 +0000</pubDate><atom:updated>2012-01-26T19:23:47.684+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><category domain="http://www.blogger.com/atom/ns#">Facebook</category><title>Making Facebook's Graph API work in Internet Explorer</title><description>I've encountered several issues while trying to get Facebook's Graph API work in IE.&lt;br /&gt;
&lt;br /&gt;
As for my general setup, I was using jQuery's &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;getJSON&lt;/span&gt; and a typical call looked something like the following:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;$.getJSON('https://graph.facebook.com/13601226661?access_token=' + accessToken, function (response) {
    callback(response);
});
&lt;/pre&gt;&lt;br /&gt;
The first problem was that I was getting a &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;No Transport&lt;/span&gt; when making a call to https://graph.facebook.com. The issue here was due to the fact that IE uses &lt;a href="http://msdn.microsoft.com/en-us/library/ie/cc288060(v=vs.85).aspx" target="_blank"&gt;&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;XDomainRequest&lt;/span&gt;&lt;/a&gt; and I ultimately resolved it by using the following workaround: &lt;a href="https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js" target="_blank"&gt;https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
This is because &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;XDomainRequest&lt;/span&gt; is currently &lt;a href="http://bugs.jquery.com/ticket/8283" target="_blank"&gt;not supported&lt;/a&gt; in jQuery.&lt;br /&gt;
&lt;br /&gt;
&lt;hr /&gt;&lt;br /&gt;
After including the xdr.js file, I started getting a different problem.  Internet Explorer now started saying "&lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;Access is denied&lt;/span&gt;" whenever I make the AJAX call.&lt;br /&gt;
&lt;br /&gt;
After some reading,  I found out from &lt;a href="http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx" target="_blank&amp;quot;"&gt;here&lt;/a&gt; that:&lt;br /&gt;
&lt;br /&gt;
&lt;center&gt;&lt;blockquote style="width: 600px"&gt;7) Requests must be targeted to the same scheme as the hosting page.&lt;/blockquote&gt;&lt;/center&gt;&lt;br /&gt;
Essentially this means that "[...]&amp;nbsp;&lt;i&gt;if your AJAX page is at http://example.com, then your target URL must also begin with HTTP. Similarly, if your AJAX page is at https://example.com, then your target URL must also begin with HTTPS&lt;/i&gt;".&lt;br /&gt;
&lt;br /&gt;
And of course, I was making calls from &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;http&lt;/span&gt; (my domain) to &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;https&lt;/span&gt; (graphs.facebook), and that goes against the aforementioned point #7.&lt;br /&gt;
&lt;br /&gt;
So what I first tried was to make a call to http://graphs.facebook.com instead (i.e. using &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;http&lt;/span&gt; instead of &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;https&lt;/span&gt;), and that works...but only when not using an &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;access_token&lt;/span&gt; in your request; and I needed to include my token in all the requests.&lt;br /&gt;
&lt;br /&gt;
And the solution to this problem was &lt;a href="http://en.wikipedia.org/wiki/JSONP" target="_blank&amp;quot;"&gt;jsonp&lt;/a&gt;.  With jsonp, IE allows the cross-domain requests.  I'm not going to go into the details of jsonp in this post, and luckily, jQuery supports it natively since all you need to do is include &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;callback=?&lt;/span&gt; as part of your request.  This means that my calls now changed as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;$.getJSON('https://graph.facebook.com/13601226661?access_token=' + accessToken + '&amp;amp;callback=?', function (response) {
    callback(response);
});
&lt;/pre&gt;&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Ramases',
  name : "Life Child",
  link : 'http://grooveshark.com/s/Life+Child/2g4xA0?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-5025889989828882953?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/ZNhIrmOP3S4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/ZNhIrmOP3S4/making-facebooks-graph-api-work-in.html</link><author>noreply@blogger.com (Andreas Grech)</author><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2012/01/making-facebooks-graph-api-work-in.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-3277463600844572918</guid><pubDate>Mon, 09 Jan 2012 19:31:00 +0000</pubDate><atom:updated>2012-01-11T12:17:58.457+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><category domain="http://www.blogger.com/atom/ns#">Projects</category><category domain="http://www.blogger.com/atom/ns#">Google Chrome Extensions</category><title>Paste and Go - A Google Chrome extension</title><description>A functionality in browsers, specifically Google Chrome and Mozilla Firefox, which I find extremely comfortable is "Paste and Go".&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-l-iv23wH3UQ/Tws4ZwneAVI/AAAAAAAABFo/RZRmJaLooMk/s1600/PasteGoChrome.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="152" src="http://3.bp.blogspot.com/-l-iv23wH3UQ/Tws4ZwneAVI/AAAAAAAABFo/RZRmJaLooMk/s320/PasteGoChrome.png" width="187" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
This pastes in your clipboard contents in the address bar and submits it automatically at one go, which is a step less than pressing Paste and then submitting manually.&lt;br /&gt;
&lt;br /&gt;
Because I like this functionality a lot, I decided to try and emulate it for input textboxes on websites with a Google Chrome extension.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-fCtX-Iniv7A/Tws8YdmC73I/AAAAAAAABF0/09U1CqEg8uQ/s1600/PasteAndGoScreen1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="200" src="http://1.bp.blogspot.com/-fCtX-Iniv7A/Tws8YdmC73I/AAAAAAAABF0/09U1CqEg8uQ/s320/PasteAndGoScreen1.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;h4&gt;Download&lt;/h4&gt;The extension is published at &lt;a href="https://chrome.google.com/webstore/detail/nbilgjjflfiiijecdjpnbganoiafneph" target="_blank"&gt;https://chrome.google.com/webstore/detail/nbilgjjflfiiijecdjpnbganoiafneph&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
And the source: &lt;a href="https://github.com/dreasgrech/PasteAndGo" target="_blank"&gt;https://github.com/dreasgrech/PasteAndGo&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;How it works&lt;/h4&gt;When invoking it (Right Click -&amp;gt; Paste and Go), the extension grabs reference to the input text box where you right clicked, clears its value and pastes in the contents of your clipboard.&lt;br /&gt;
&lt;br /&gt;
It then searches for the closest &amp;lt;form&amp;gt; to your text box with jQuery's &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;&lt;a href="http://api.jquery.com/closest/" target="_blank"&gt;closest&lt;/a&gt;&lt;/span&gt; function and if it finds a form, it submits it.&lt;br /&gt;
&lt;br /&gt;
Note that &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;closest&lt;/span&gt; only traverses &lt;b&gt;up&lt;/b&gt; the DOM tree, so it will not find &amp;lt;form&amp;gt;s which are either below (in the tree) or adjacent (siblings) to your input text box.&lt;br /&gt;
&lt;br /&gt;
If no &amp;lt;form&amp;gt; is found, another approach is taken.  This time, the extension searches for the closest button to your input text box and if it finds one, it clicks it.  This time though, I couldn't use jQuery's &lt;span style="font-family: 'Courier New', Courier, monospace;"&gt;closest&lt;/span&gt; since, most of the time, submit buttons in &amp;lt;form&amp;gt;s are placed after the input text box.  Therefore, I wrote this function to find the 'closest' button:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;var getClosestButton = function (el) {
        var buttons;
        while ((el = el.parent()).length) {
            buttons = el.find(":button, input[type=submit]"); // :button -&gt; "input[type=button], button"

            if (buttons.length) {
                return buttons.eq(buttons.length - 1);
            }
        }
};
&lt;/pre&gt;&lt;br /&gt;
Once a button is found, a click event is simulated on it.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;A word of caution&lt;/h4&gt;This extension may not always work as expected.  This is because it assumes that the first &amp;lt;form&amp;gt; it finds closest (upwards only) to your input box is the correct form which needs to be submitted, or that the 'closest' button that's found near your input box is the button that needs to be clicked...and the extension may not always find the &lt;i&gt;correct&lt;/i&gt; button or submit the correct form; although the later is very rarely an issue.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;Therefore, use it at your own risk.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
Here are some of the places where it worked successfully:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Facebook&lt;/li&gt;
&lt;li&gt;docs.jquery.com&lt;/li&gt;
&lt;li&gt;Stackoverflow&lt;/li&gt;
&lt;li&gt;Twitter&lt;/li&gt;
&lt;li&gt;Google&lt;/li&gt;
&lt;li&gt;Yahoo!&lt;/li&gt;
&lt;li&gt;Bing&lt;/li&gt;
&lt;li&gt;YouTube&lt;/li&gt;
&lt;li&gt;The Pirate Bay&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
And here are some of the sites in which it didn't work as expected:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Grooveshark&lt;/li&gt;
&lt;li&gt;Gmail&lt;/li&gt;
&lt;li&gt;CodePlex&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;center&gt;&lt;i&gt;Where did you try it, and did it work as expected?&lt;/i&gt;&lt;/center&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Steamhammer',
  name : "I Wouldn't Have Thought",
  link : 'http://grooveshark.com/s/I+Wouldn+t+Have+Thought/3yI0Ve?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-3277463600844572918?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/mBiFzeDgqts" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/mBiFzeDgqts/paste-and-go-google-chrome-extension.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-l-iv23wH3UQ/Tws4ZwneAVI/AAAAAAAABFo/RZRmJaLooMk/s72-c/PasteGoChrome.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2012/01/paste-and-go-google-chrome-extension.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-896054437697825189</guid><pubDate>Wed, 30 Nov 2011 03:20:00 +0000</pubDate><atom:updated>2011-12-06T04:37:26.585+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">XNA</category><category domain="http://www.blogger.com/atom/ns#">Projects</category><category domain="http://www.blogger.com/atom/ns#">C#</category><title>Conway's Game of Life in XNA</title><description>The following video demonstrates an implementation of &lt;a target="_blank" href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life"&gt;Conway's Game of Life&lt;/a&gt; I once wrote in in XNA.&lt;br /&gt;
&lt;br /&gt;
&lt;center&gt;&lt;iframe width="640" height="360" src="http://www.youtube.com/embed/0TxuIamXrnk?hd=1" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;/center&gt;&lt;br /&gt;
&lt;br /&gt;
Unfortunately, I currently don't have the source code for this online but I'll post it once I stop procrastinating.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Episode Six',
  name : "Mr. Universe",
  link : 'http://grooveshark.com/s/Episode+Six+Mr+Universe/3Q9bzc?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-896054437697825189?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/-uN-Z7AnlHY" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/-uN-Z7AnlHY/conways-game-of-life-in-xna.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://img.youtube.com/vi/0TxuIamXrnk/default.jpg" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/11/conways-game-of-life-in-xna.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-5925033192957725533</guid><pubDate>Mon, 07 Nov 2011 20:39:00 +0000</pubDate><atom:updated>2011-11-27T21:42:28.165+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><title>Cheating at a typing test with JavaScript</title><description>So I just found this website called &lt;a href="http://speedtest.10-fast-fingers.com/" target="_blank"&gt;10fastfingers&lt;/a&gt; and it has a typing game that measures your speed in WPM.  I played with it for a while to see how fast I could really type but after I got bored keying in random words in a text box, I decided to spice things up a bit...by cheating; because hey, why not?&lt;br /&gt;
&lt;br /&gt;
&lt;center&gt;&lt;iframe width="640" height="480" src="http://www.youtube.com/embed/kC4n_lqFB64?hd=1" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;/center&gt;&lt;br /&gt;
&lt;br /&gt;
And so, I wrote two scripts to do the typing for me; sort of like secretaries.  The first one just completes the test instantly, which guarantees that all the words available in the test are "typed in".  The second one takes its time with a delay between each word, but it's more fun to look at because you actually get to see the words which are being completed.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;The instant one&lt;/h4&gt;&lt;pre class="javascript" name="code"&gt;var words = document.getElementById('wordlist').innerHTML.split(/\|/),
    input = document.getElementById('inputfield'),
    pressEvent = document.createEvent("KeyboardEvent"),
    pressSpace = function () {
        pressEvent.initKeyEvent("keyup", true, true, window, false, false, false, false, 32, false);
        input.dispatchEvent(pressEvent);
    },
    go = function () {
        var i = 0,  j = words.length;
        for (; i &amp;lt; j; ++i) {
            input.value += words[i];
            pressSpace();
        }
    };

go();
&lt;/pre&gt;&lt;br /&gt;
This script is not very entertaining since it finishes the test almost instantly because it's using a for loop to go through the words.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;Putting a delay&lt;/h4&gt;&lt;pre class="javascript" name="code"&gt;var words = document.getElementById('wordlist').innerHTML.split(/\|/),
    input = document.getElementById('inputfield'),
    timer = document.getElementById('timer'),
    pressEvent = document.createEvent("KeyboardEvent"),
    pressSpace = function () {
        pressEvent.initKeyEvent("keyup", true, true, window, false, false, false, false, 32, false);
        input.dispatchEvent(pressEvent);
    },
    go = function (delay) {
        var current = 0,
            worker = setInterval(function () {
                if (current == words.length || timer.className) {
                    clearInterval(worker);
                    return;
                }
                input.value += words[current++];
                pressSpace();
            }, delay);
    };

go(60000 / words.length);
&lt;/pre&gt;&lt;br /&gt;
This is a very slightly modified version of the first script which inserts a delay between each word that's "typed in".  The delay, in milliseconds, is specified as an argument to the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;go&lt;/span&gt; function.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;Running the scripts&lt;/h4&gt;To run the scripts, open Firefox, head over to to http://speedtest.10-fast-fingers.com/, launch &lt;a target="_blank" href="http://getfirebug.com/"&gt;Firebug&lt;/a&gt; and paste the script in the console.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-S5G5vo0_Fzc/Trg_JMQHEPI/AAAAAAAABFU/AroRH5t5xW4/s1600/firebugscript.png" /&gt;&lt;/div&gt;&lt;br /&gt;
Now press CTRL+ENTER and watch the magic happen.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Luv Machine',
  name : "Witches Wand",
  link : 'http://grooveshark.com/s/Witches+Wand/39uajD?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-5925033192957725533?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/fb8-jMK31tU" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/fb8-jMK31tU/cheating-at-typing-test-with-javascript.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://img.youtube.com/vi/kC4n_lqFB64/default.jpg" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/11/cheating-at-typing-test-with-javascript.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-2239930139002081258</guid><pubDate>Wed, 26 Oct 2011 16:20:00 +0000</pubDate><atom:updated>2011-10-26T18:20:25.625+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><category domain="http://www.blogger.com/atom/ns#">Google Chrome Extensions</category><title>A Chrome extension for plotting graphs with Wolfram|Alpha</title><description>This weekend I got round to writing a Google Chrome extension that aids you in plotting graphs from &lt;a href="http://www.wolframalpha.com/" target="_blank"&gt;Wolfram|Alpha&lt;/a&gt;.  The extension simply takes the parameters you input, constructs a url to Wolfram|alpha and then opens a new tab with that url.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-r4wqOWSbi_8/TqcahY7Vb3I/AAAAAAAABE0/EMGIunTjtRA/s1600/wolframalphagraphplotter_extension.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="320" width="275" src="http://4.bp.blogspot.com/-r4wqOWSbi_8/TqcahY7Vb3I/AAAAAAAABE0/EMGIunTjtRA/s320/wolframalphagraphplotter_extension.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
If you wanna give it a go, I published it on the &lt;a href="https://chrome.google.com/webstore/detail/enkdigeebkhbghenenmdddiglhnkkfcf" target="_blank"&gt;Chrome Web Store&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
I've also put the source up at github:  &lt;a href="https://github.com/dreasgrech/wolframalpha-graphplotter" target="_blank"&gt;https://github.com/dreasgrech/wolframalpha-graphplotter&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'The Pretty Things',
  name : "Sickle Clowns",
  link : 'http://grooveshark.com/s/Sickle+Clowns/2gMdgz?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-2239930139002081258?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/jsysR03arEA" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/jsysR03arEA/chrome-extension-for-plotting-graphs.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-r4wqOWSbi_8/TqcahY7Vb3I/AAAAAAAABE0/EMGIunTjtRA/s72-c/wolframalphagraphplotter_extension.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/10/chrome-extension-for-plotting-graphs.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-5382123165419829300</guid><pubDate>Sun, 09 Oct 2011 11:43:00 +0000</pubDate><atom:updated>2011-10-09T13:43:51.104+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Mathematics</category><title>Finding a function's inverse with Wolfram|Alpha</title><description>To check my answers when calculating the inverse of functions, I've found this handy widget from Wolfram|Alpha which does the job:&lt;br /&gt;
&lt;br /&gt;
&lt;script type="text/javascript" id="WolframAlphaScriptd08726019e4a2a15cb1d49092e4d0522" src="http://www.wolframalpha.com/widget/widget.jsp?id=d08726019e4a2a15cb1d49092e4d0522&amp;theme=green&amp;output=lightbox"&gt;&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Fuzzy Duck',
  name : "Mrs. Prout",
  link : 'http://grooveshark.com/s/Mrs+Prout/3EjHMy?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-5382123165419829300?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/hRb0fBAry6U" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/hRb0fBAry6U/finding-functions-inverse-with.html</link><author>noreply@blogger.com (Andreas Grech)</author><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/10/finding-functions-inverse-with.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-4799231284088188638</guid><pubDate>Wed, 05 Oct 2011 17:50:00 +0000</pubDate><atom:updated>2011-10-05T19:57:03.174+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Mathematics</category><title>A Function Transformations reference sheet</title><description>Since I never miss a change to procrastinate, I decided to spend some time compiling a "cheat sheet" for function transformations.  &lt;br /&gt;
&lt;br /&gt;
I've included the following 8 transformations:&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;A constant added to or subtracted from a function shifts its graph vertically.&lt;/li&gt;
&lt;li&gt;A constant added to or subtracted from a function's input shifts its graph horizontally.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Multiplying a function by a constant stretches or squishes the function vertically.&lt;/li&gt;
&lt;li&gt;Multiplying a function's input by a constant stretches or squishes the function horizontally.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Multiplying a function by a negative number causes its graph to reflect over the x-axis.&lt;/li&gt;
&lt;li&gt;Multiplying a function's input by a negative number causes its graph to reflect over the y-axis.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Taking the absolute value of a function moves all the points on its graph above the x-axis.&lt;/li&gt;
&lt;li&gt;Taking the absolute value of a function's input causes the left side of the graph to clone the right side.&lt;/li&gt;
&lt;/ol&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a target="_blank" href="http://dreasgrech.com/upload/functiontransformations/Function%20transformation%20graphs%20cheat%20sheet.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="566" width="400" src="http://dreasgrech.com/upload/functiontransformations/Function%20transformation%20graphs%20cheat%20sheet.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'New York Rock &amp; Roll Ensemble',
  name : "Gravedigger",
  link : 'http://grooveshark.com/s/Gravedigger/2fmb4e?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-4799231284088188638?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/Nc1cz94Qn9o" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/Nc1cz94Qn9o/function-transformations-reference.html</link><author>noreply@blogger.com (Andreas Grech)</author><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/10/function-transformations-reference.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-3676071879335940625</guid><pubDate>Sun, 02 Oct 2011 18:48:00 +0000</pubDate><atom:updated>2011-10-20T01:30:24.116+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><title>A State Manager in JavaScript</title><description>The following is an implementation for a state manager written in JavaScript.  More than one state can be "on" at one moment but mutual exclusivity rules can be set up to allow certain states to not be "on" at the same time i.e. if one of the states is switched on while the other is already on, the latter will be switched off since they can't be both on at the same time.&lt;br /&gt;
&lt;br /&gt;
It also supports two hooks which can be used if you want to be notified when states are changed.&lt;br /&gt;
&lt;br /&gt;
It's implemented with a &lt;a href="http://en.wikipedia.org/wiki/Fluent_interface" target="_blank"&gt;fluent interface&lt;/a&gt; to allow for method-chaining.&lt;br /&gt;
&lt;br /&gt;
The source is here: &lt;a href="https://github.com/dreasgrech/statemanager-js" target="_blank"&gt;https://github.com/dreasgrech/statemanager-js&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
I've set up a simple demo to show how it can be used.  You can view it here: &lt;a target="_blank" href="http://dreasgrech.com/upload/statemanager-js/demo.html"&gt;http://dreasgrech.com/upload/statemanager-js/demo.html&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a target="_blank" href="http://dreasgrech.com/upload/statemanager-js/demo.html" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://4.bp.blogspot.com/-_ESp2ghKMNQ/ToNsy95vCrI/AAAAAAAABD4/octsWOkkHic/s1600/statemanager-js.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;h4&gt;Basic Usage&lt;/h4&gt;&lt;pre class="javascript" name="code"&gt; 
var state = stateManager();
state.turnOn("state 1", "state 2");

state.on("state 1"); // true
state.on("state 2"); // true
state.on("state 3"); // false

state.toggle("state 2"); // "state 2" is now off
state.on("state 2"); // false
&lt;/pre&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;toggle&lt;/span&gt; returns the new state after it's been toggled.&lt;br /&gt;
&lt;h4&gt;Mutual Exclusivity&lt;/h4&gt;&lt;pre class="javascript" name="code"&gt; 
var state = stateManager();

state.mutex("state 1", "state 3"); // "state 1" and "state 2" now cannot be both on at the same time
state.mutex("state 2", "state 3"); // "state 2" and "state 3" now cannot be both on at the same time

state.turnOn("state 1");
state.turnOn("state 3"); // "state 1" will now be turned off since 1 and 3 are mutually exclusive
state.turnOn("state 1"); // turning "state 1" on, but switching "state 3" off for the same reason
state.turnOn("state 2"); // if "state 3" was on at this point, it would have been switched off
&lt;/pre&gt;&lt;h4&gt;Hooks&lt;/h4&gt;&lt;pre class="javascript" name="code"&gt; 
var state = stateManager();

state.onStateChanged(function (state, value) { // The global event; fires every time a state changes
  console.log(state + " is now " + value);
});

state.onStateChanged("state 1", function (value) { // The event that will only fire when "state 1" changes
  console.log("[Custom hook] state 1 has been changed.  New value: " + value); 
});

state.turnOn("state 1");
state.turnOn("state 3", "state 2"); 
state.toggle("state 1"); 
state.turnOn("state 2"); 
&lt;/pre&gt;Output:&lt;br /&gt;
&lt;pre&gt;state 1 is now 1
[Custom hook] state 1 has been changed. New value: 1
state 3 is now 1
state 2 is now 1
state 1 is now 0
[Custom hook] state 1 has been changed. New value: 0
&lt;/pre&gt;Note that the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;onStateChanged&lt;/span&gt; event fires only when a state changes.  For example, if you &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;turnOn("state 2")&lt;/span&gt; while &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;"state 2"&lt;/span&gt; is already on, the event will not fire.  The same goes for when a state is off and you try to &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;turnOff&lt;/span&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Soft Machine',
  name : "Why Are We Sleeping?",
  link : 'http://grooveshark.com/s/Why+Are+We+Sleeping/3HrbBb?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-3676071879335940625?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/Fi-l1pwol9o" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/Fi-l1pwol9o/state-manager-in-javascript.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-_ESp2ghKMNQ/ToNsy95vCrI/AAAAAAAABD4/octsWOkkHic/s72-c/statemanager-js.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/10/state-manager-in-javascript.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-6276379701935151357</guid><pubDate>Sat, 01 Oct 2011 12:17:00 +0000</pubDate><atom:updated>2011-10-01T14:17:24.680+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><category domain="http://www.blogger.com/atom/ns#">Mathematics</category><title>Function composition in JavaScript</title><description>Function composition is the application of a result of a function as input to another function.  Say we have the following three functions:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-HgDCstjj1zk/ToZbj2T-J2I/AAAAAAAABEA/zwqZnw0MN_8/s1600/functioncomposition-1.png"/&gt;&lt;/div&gt;&lt;br /&gt;
Composing functions &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;f&lt;/span&gt;, &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;g&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;h&lt;/span&gt; respectively means that we pass the output from function &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;h&lt;/span&gt; as the input to function &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;g&lt;/span&gt; and then passing the output from &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;g&lt;/span&gt; as the input to function &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;f&lt;/span&gt;.  Mathematically, it would be represented as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" height="19" src="http://1.bp.blogspot.com/-59d1kWuAkck/Tobri-BVxUI/AAAAAAAABEY/6B43G_1cEbQ/s1600/functioncomposition-2.png" width="100" /&gt;&lt;/div&gt;&lt;br /&gt;
That's essentially the same as:&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" height="19" src="http://3.bp.blogspot.com/-RRkJ8Qd3Gfw/TobrPtnonjI/AAAAAAAABEQ/Z6kEwlwVk9M/s1600/functioncomposition-3.png" width="79" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;hr/&gt;&lt;br /&gt;
Functions in JavaScript are first class citizens.  This means that they can be stored in variables and data structures, passed as an argument to functions and also returned from functions.  This means that we can easily implement function composition in JavaScript with a very trivial function:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;Function.prototype.compose || (Function.prototype.compose = function (f) {
    var g = this;
    return function () {
        return g(f.apply(null, arguments));
    };
});
&lt;/pre&gt;&lt;br /&gt;
Here's an example of how we can use it by composing three functions that represent the three polynomials mentioned at the start of the post:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;var f = function (x) {
    return x*x - x + 5;
}, g = function (x) {
    return x*x + 3*x - 2;
}, h = function (x) {
    return x*x*x - 2*(x*x) + x -1;
};
&lt;/pre&gt;&lt;br /&gt;
Composing them together would then be:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;var composed = f.compose(g).compose(h);
&lt;/pre&gt;&lt;br /&gt;
The result of the&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;composed&lt;/span&gt;&amp;nbsp;function is now the same as the result of &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;f(g(h(x)))&lt;/span&gt;:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;composed(x) === f(g(h(x))); // true
&lt;/pre&gt;&lt;hr/&gt;If we had a function &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;f&lt;/span&gt; and its inverse &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;f&lt;sup&gt;-1&lt;/sup&gt;&lt;/span&gt; and we compose them, we should get the original input &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;x&lt;/span&gt;:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;var f = function (x) {
    return (x + 2) / 3 - x;
}, f_inverse = function (x) {
    return (2 - 3*x) / 2;
};

(f.compose(f_inverse)(x) || f_inverse.compose(f)(x) || x) === x;  // true
&lt;/pre&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" height="79" src="http://4.bp.blogspot.com/-M8kkOuWIPz4/TocAKZsBvrI/AAAAAAAABEg/KivnfyFK3mA/s1600/functioncomposition-4.png" width="153" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" height="20" src="http://1.bp.blogspot.com/-C1tPXMyD-io/TocAKje9OqI/AAAAAAAABEo/4T8Dyo7W4bk/s1600/functioncomposition-5.png" width="245" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Black Widow',
  name : "In Ancient Days",
  link : 'http://grooveshark.com/s/In+Ancient+Days/2BBHkS?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-6276379701935151357?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/ViNcEaCjdYc" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/ViNcEaCjdYc/function-composition-in-javascript.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-HgDCstjj1zk/ToZbj2T-J2I/AAAAAAAABEA/zwqZnw0MN_8/s72-c/functioncomposition-1.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/10/function-composition-in-javascript.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-5467304361341102119</guid><pubDate>Thu, 29 Sep 2011 17:13:00 +0000</pubDate><atom:updated>2011-09-29T19:13:34.484+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><title>JavaScript helpers: Iterating an array while skipping select elements</title><description>&lt;pre class="javascript" name="code"&gt;	
Array.prototype.iterate || (Array.prototype.iterate = function (callback, ignore) {
  var i = 0, j = this.length;
    for (; i &amp;lt; j; ++i) {
        if (ignore &amp;amp;&amp;amp; ignore(this[i], i)) {
          continue;
        } 
        
        callback(this[i], i);
    }
});
&lt;/pre&gt;&lt;h4&gt;Usage&lt;/h4&gt;Here's how we can use it to iterate over a couple of numbers, skipping over the even ones:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;	
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

arr.iterate(function (el) {
  console.log(el);
}, function (el) {
  return !(el % 2);
});
&lt;/pre&gt;&lt;br /&gt;
Output:&lt;br /&gt;
&lt;pre&gt;1
3
5
7
9
&lt;/pre&gt;&lt;br /&gt;
Here's another example, this time involving objects:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;	
var queen = function (reference) {
    return {
        ref: reference
    };
}, arr = [queen("Aragon"), queen("Boleyn"), queen("Seymour"), queen("Cleves"), queen("Howard"), queen("Parr")];

arr.iterate(function (el, i) {
  console.log(i, el.ref);  
}, function (q) {
  return q.ref === "Boleyn"  || q.ref === "Howard";
});
&lt;/pre&gt;Output (the queens who died with their heads on):&lt;br /&gt;
&lt;pre&gt;0 Aragon
2 Seymour
3 Cleves
5 Parr
&lt;/pre&gt;&lt;br /&gt;
If no &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ignore&lt;/span&gt; function is passed as the second parameter of the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;iterate&lt;/span&gt; method, no elements are skipped:&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;	
var arr = ["Mr. Albert Show", "Fusion Orchestra", "Fuzzy Duck", "Minotaurus"];

arr.iterate(function (el, i) {
  console.log(el);  
});
&lt;/pre&gt;Output&lt;br /&gt;
&lt;pre&gt;Mr. Albert Show
Fusion Orchestra
Fuzzy Duck
Minotaurus
&lt;/pre&gt;&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'The Human Instinct',
  name : "Black Sally",
  link : 'http://grooveshark.com/s/Black+Sally/3sewo8?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-5467304361341102119?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/7JZMZahhbBk" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/7JZMZahhbBk/javascript-helpers-iterating-array.html</link><author>noreply@blogger.com (Andreas Grech)</author><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/09/javascript-helpers-iterating-array.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-1340239738055294744</guid><pubDate>Sat, 17 Sep 2011 20:42:00 +0000</pubDate><atom:updated>2011-09-17T22:42:17.664+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">YouTube</category><category domain="http://www.blogger.com/atom/ns#">C#</category><title>Finding a YouTube video title by scraping</title><description>I was recently writing a tool in C# and I needed a way to get a YouTube video title.  I could have used the &lt;a href="http://code.google.com/apis/youtube/overview.html"&gt;YouTube API&lt;/a&gt; but I wasn't bothered about setting everything up and going through the documentation, so I decided to &lt;a href="http://en.wikipedia.org/wiki/Web_scraping" target="_blank"&gt;scrape&lt;/a&gt; the title off the video page itself.&lt;br /&gt;
&lt;br /&gt;
For this, I first wrote a very simple way to execute a GET request and return the response (&lt;i&gt;Removed all forms of error checking for brevity&lt;/i&gt;):&lt;br /&gt;
&lt;pre name="code" class="csharp"&gt;public static string ExecuteGETRequest(string url)
{
    var request = (HttpWebRequest)WebRequest.Create(url);

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        var reader = new StreamReader(response.GetResponseStream());

        return reader.ReadToEnd();
    }
}
&lt;/pre&gt;And here's the method that does the task at hand:&lt;br /&gt;
&lt;pre name="code" class="csharp"&gt;public static string GetYouTubeVideoTitle(string youtubeLinkUrl)
{
    string response = ExecuteGETRequest(youtubeLinkUrl),
             title = response.Substring(response.IndexOf("&amp;lt;title&amp;gt;\n") + 8);

    title = title.Substring(0, title.IndexOf("\n"));
    return title.Trim();
}
&lt;/pre&gt;&lt;h4&gt;Usage&lt;/h4&gt;&lt;pre name="code" class="csharp"&gt;var title = GetYouTubeVideoTitle("http://www.youtube.com/watch?v=TY9jN6hm3N0"); // "Wicked Lady - Ship of Ghosts (Part 1 of 2) 1972"
&lt;/pre&gt;&lt;b&gt;Be wary of using this method for extracting titles because it could potentially break in the future due to changes in how YouTube renders the page with HTML; but it may be useful for quick scripts.&lt;/b&gt;&lt;br /&gt;
&lt;h4&gt;Checking for link validity&lt;/h4&gt;If you want to make sure the given link actually points to a YouTube video, you can use something like this:&lt;br /&gt;
&lt;pre name="code" class="csharp"&gt;public static bool IsValidYoutubeLink(string youtubeLink)
{
    // Regular expression from http://www.regexlib.com/REDetails.aspx?regexp_id=2569
    return Regex.IsMatch(youtubeLink, @"^http://\w{0,3}.?youtube+\.\w{2,3}/watch\?v=[\w-]{11}");
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Sir Lord Baltimore',
  name : "Lady of Fire",
  link : 'http://grooveshark.com/s/Lady+Of+Fire/3lCiX3?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-1340239738055294744?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/Ql3vXtd5vgc" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/Ql3vXtd5vgc/finding-youtube-video-title-by-scraping.html</link><author>noreply@blogger.com (Andreas Grech)</author><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/09/finding-youtube-video-title-by-scraping.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-2560767060786164353</guid><pubDate>Sat, 10 Sep 2011 23:19:00 +0000</pubDate><atom:updated>2011-09-17T22:51:32.235+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">YouTube</category><category domain="http://www.blogger.com/atom/ns#">Projects</category><category domain="http://www.blogger.com/atom/ns#">C#</category><title>Generating a list of links for a user's YouTube uploads</title><description>This is a very simple application I just wrote to generate a list of all of the video upload links given a YouTube user.&lt;br /&gt;
&lt;h4&gt;Download&lt;/h4&gt;Since this was such a small project, I didn't see fit to have a github repository for it so I just uploaded it to my hosting server.&lt;br /&gt;
&lt;br /&gt;
Download the exe (release) file from: &lt;a href="http://dreasgrech.com/upload/youtubeuseruploads/YouTubeUserUploads.exe" target="_blank"&gt;http://dreasgrech.com/upload/youtubeuseruploads/YouTubeUserUploads.exe&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
And the source: &lt;a href="http://dreasgrech.com/upload/youtubeuseruploads/YouTubeUserUploads-source.zip" target="_blank"&gt;http://dreasgrech.com/upload/youtubeuseruploads/YouTubeUserUploads-source.zip&lt;/a&gt;&lt;br /&gt;
&lt;i&gt;It won't be the best code you'll ever see, but it does the job for the task at hand.&lt;/i&gt;&lt;br /&gt;
&lt;h4&gt;Usage&lt;/h4&gt;&lt;center&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;YouTubeUserUploads.exe &amp;lt;username&amp;gt; [file]&lt;/span&gt;&lt;/center&gt;&lt;br /&gt;
&lt;br /&gt;
If &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;[file]&lt;/span&gt; is not given, a file  &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;links.txt&lt;/span&gt; will be created in the current directory.&lt;br /&gt;
&lt;h4&gt;Demo&lt;/h4&gt;Here's an example run using my YouTube username:&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;C:\YouTubeUserUploads.exe agnt666 uploads.txt
Username: agnt666
Saving links to: uploads.txt

Processing...
Finished writing 3 links
&lt;/pre&gt;&lt;br /&gt;
That would create (or overwrite) a text file called links.txt and write the links to my three currently uploaded videos at the time of writing:&lt;br /&gt;
&lt;pre&gt;http://www.youtube.com/watch?v=rsXnEpWyeEg
http://www.youtube.com/watch?v=sxBiD7u7nx8
http://www.youtube.com/watch?v=Ri2SHGZaSqs
&lt;/pre&gt;&lt;h4&gt;Screenshots&lt;/h4&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-WXhag4gq3-Q/Tmv1yC-YapI/AAAAAAAABDI/Y1hf82Fv-rI/s1600/ytimg.png" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-CNTmL2Fd8g4/Tmv3FUozXTI/AAAAAAAABDg/88du9hSMTiI/s1600/ytimg.png" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://1.bp.blogspot.com/-0BShAmi_Jac/Tmv2QrYx0yI/AAAAAAAABDQ/qx8S5FydBgU/s1600/ytimg.png" /&gt;&lt;br /&gt;
&lt;/div&gt;&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Marillion',
  name : "Fugazi",
  link : 'http://grooveshark.com/s/Fugazi/3if0iS?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-2560767060786164353?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/Nl4Fy8EM168" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/Nl4Fy8EM168/generating-list-of-links-for-users.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-WXhag4gq3-Q/Tmv1yC-YapI/AAAAAAAABDI/Y1hf82Fv-rI/s72-c/ytimg.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/09/generating-list-of-links-for-users.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-3735052673746040969</guid><pubDate>Thu, 08 Sep 2011 15:26:00 +0000</pubDate><atom:updated>2011-09-08T17:26:49.013+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><category domain="http://www.blogger.com/atom/ns#">Game Development</category><category domain="http://www.blogger.com/atom/ns#">Projects</category><title>The Monty Hall game</title><description>After my &lt;a href="http://blog.dreasgrech.com/2011/09/simulating-monty-hall-problem.html" target="_blank"&gt;last post&lt;/a&gt; on simulating the Monty Hall problem, I decided to go a step further and actually write the game itself.  Since I wrote the simulation using JavaScript, I kept at it by writing the game using JavaScript by making use of the canvas element.&lt;br /&gt;
&lt;br /&gt;
You can play the game &lt;a target="_blank" href="http://dreasgrech.com/upload/montyhallgame/index.html"&gt;here&lt;/a&gt; and find the source on Github: &lt;a href="https://github.com/dreasgrech/The-Monty-Hall-Game" target="_blank"&gt;https://github.com/dreasgrech/The-Monty-Hall-Game&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
The code leaves much to be desired but since this was a quick weekend project (...although some tweaks did spill over to the rest of the week), I didn't worry too much about it.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;Screenshots&lt;/h4&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-ni3At1ft5gY/TmfJR2qxsWI/AAAAAAAABCs/URcg_LAn7P0/s1600/game1.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="300" width="400" src="http://2.bp.blogspot.com/-ni3At1ft5gY/TmfJR2qxsWI/AAAAAAAABCs/URcg_LAn7P0/s400/game1.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-oG5UJLL7RVA/TmfJR88h4gI/AAAAAAAABC0/_e9BwEWkiVE/s1600/game2.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="300" width="400" src="http://2.bp.blogspot.com/-oG5UJLL7RVA/TmfJR88h4gI/AAAAAAAABC0/_e9BwEWkiVE/s400/game2.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-8HzDrrbzrbw/TmfJR3g3ydI/AAAAAAAABC8/3egm42igoDI/s1600/game3.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="300" width="400" src="http://4.bp.blogspot.com/-8HzDrrbzrbw/TmfJR3g3ydI/AAAAAAAABC8/3egm42igoDI/s400/game3.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Birth Control',
  name : "Gamma Ray",
  link : 'http://grooveshark.com/s/Gamma+Ray/38OBxq?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-3735052673746040969?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/IyXLN2Dyxtg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/IyXLN2Dyxtg/monty-hall-game.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-ni3At1ft5gY/TmfJR2qxsWI/AAAAAAAABCs/URcg_LAn7P0/s72-c/game1.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/09/monty-hall-game.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-4233704762195889026</guid><pubDate>Sat, 03 Sep 2011 17:57:00 +0000</pubDate><atom:updated>2011-09-03T20:42:39.246+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><category domain="http://www.blogger.com/atom/ns#">Mathematics</category><title>Simulating the Monty Hall problem</title><description>You're on a game show and begin the game by having three doors in front of you.  Behind one of the doors, lies the prize.  You don't know which door is the winning door but the game show host knows.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" height="174" src="http://3.bp.blogspot.com/-jpmWCFIWtg4/TmI800j_NbI/AAAAAAAABBk/Zep1ZdE8bKY/s400/monty1.png" width="400" /&gt;&lt;/div&gt;&lt;br /&gt;
You now randomly choose the door which you think has the prize behind it, but the door doesn't open for the time being.  In this case, we are going to choose the middle door.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" height="174" src="http://1.bp.blogspot.com/-N7o717tGSVY/TmI9Kn5yJXI/AAAAAAAABBs/q-ep42LPtpY/s400/monty2.png" width="400" /&gt;&lt;/div&gt;&lt;br /&gt;
The game show host must now open one of the two remaining doors, and the door he chooses must not be the winning door.  For this example, the game show host opens the door on the right.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" height="174" src="http://1.bp.blogspot.com/-XlB7kwFco7E/TmI9uM30eLI/AAAAAAAABB0/lD_SegEkyiA/s400/monty3.png" width="400" /&gt;&lt;/div&gt;&lt;br /&gt;
The host now asks you if you want to stick with your first choice or switch to the remaining door.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" height="245" src="http://3.bp.blogspot.com/-wpHTN4CM_T8/TmI-DwtvpWI/AAAAAAAABB8/tjAkpwh-Qe0/s400/monty4.png" width="400" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;center&gt;&lt;b&gt;Is it to your advantage to change your choice?&lt;/b&gt;&lt;/center&gt; &lt;br /&gt;
&lt;br /&gt;
&lt;hr /&gt;&lt;br /&gt;
To test this out, I wrote some code using JavaScript to simulate playing a number of games and supplying me with the results of how many times it won when switching or not switching the chosen door upon given the choice.  The initial guesses are all random.&lt;br /&gt;
&lt;h4&gt;Results&lt;/h4&gt;The following is the output for 5 runs with 10,000 games each:&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;Playing 10000 games
Wins when not switching door 3317
Wins when switching door 6738

Playing 10000 games
Wins when not switching door 3376
Wins when switching door 6735

Playing 10000 games
Wins when not switching door 3287
Wins when switching door 6726

Playing 10000 games
Wins when not switching door 3298
Wins when switching door 6664

Playing 10000 games
Wins when not switching door 3302
Wins when switching door 6674
&lt;/pre&gt;&lt;br /&gt;
These results show how &lt;b&gt;the number of times you win when switching the door is approximately double the number of times you win when not switching the door&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
This may seem counter intuitive at first as you may think that there's a 1/3 chance of winning, but as you can see from the above results, that's actually not the case.  In fact, switching the door wins twice as often staying.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img imageanchor="1" src="http://2.bp.blogspot.com/-UAFrdYA5RXU/TmJJIqJnP0I/AAAAAAAABCM/WHLaIbeNx6g/s1600/probabilities.png" style="margin-left: 1em; margin-right: 1em;" /&gt;&lt;/div&gt;&lt;br /&gt;
The same goes for when initially choosing Door 2 or Door 3:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img imageanchor="1" src="http://1.bp.blogspot.com/-ipS4GUaIRCc/TmJLbXe_2XI/AAAAAAAABCc/5XqzKjOOZg0/s1600/probabilities.png" style="margin-left: 1em; margin-right: 1em;" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img imageanchor="1" src="http://1.bp.blogspot.com/-u5vjD6THs_U/TmJYQhsCBNI/AAAAAAAABCk/Jt81D8piyJ0/s1600/probabilities.png" style="margin-left: 1em; margin-right: 1em;" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div style="text-align: right;"&gt;&lt;i&gt;Adapted from [Vos Savant, 1990]&lt;/i&gt;&lt;/div&gt;&lt;br /&gt;
Notice how, irrespective of which door you initially choose, you always have 2/3 chance of winning if you then switch.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;The code&lt;/h4&gt;&lt;pre class="javascript" name="code"&gt;	var totalGames = 10000,
	    selectDoor = function () {
	        return Math.floor(Math.random() * 3); // Choose a number from 0, 1 and 2.
	    },
	    games = (function () {
	        var i = 0, games = [];

	        for (; i &amp;lt; totalGames; ++i) {
	            games.push(selectDoor()); // Pick a door which will hide the prize.
	        }

	        return games;
	    }()),
	    play = function (switchDoor) {
	        var i = 0, j = games.length, winningDoor, randomGuess, totalTimesWon = 0;

	        for (; i &amp;lt; j; ++i) {
	            winningDoor = games[i];
	            randomGuess = selectDoor();
	            if ((randomGuess === winningDoor &amp;amp;&amp;amp; !switchDoor) || 
	                (randomGuess !== winningDoor &amp;amp;&amp;amp; switchDoor)) 
	            {
	                /*
	                 * If I initially guessed the winning door and didn't switch,
	                 * or if I initially guessed a losing door but then switched,
	                 * I've won.
	                 *
	                 * The only time I lose is when I initially guess the winning door 
	                 * and then switch.
	                 */

	                totalTimesWon++;
	            }
	        }
	        return totalTimesWon;
	    };

	/*
	 * Start the simulation
	 */

	console.log("Playing " + totalGames + " games");
	console.log("Wins when not switching door", play(false));
	console.log("Wins when switching door", play(true));
&lt;/pre&gt;&lt;br /&gt;
I've added this piece of code to the Monty Hall problem at the &lt;a href="http://rosettacode.org/wiki/Monty_Hall_problem#JavaScript" target="_blank"&gt;Rosetta Code&lt;/a&gt; website.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Chicago',
  name : "25 or 6 to 4",
  link : 'http://grooveshark.com/s/25+Or+6+To+4/3K4m6f?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-4233704762195889026?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/XULlGU5h1Ro" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/XULlGU5h1Ro/simulating-monty-hall-problem.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-jpmWCFIWtg4/TmI800j_NbI/AAAAAAAABBk/Zep1ZdE8bKY/s72-c/monty1.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/09/simulating-monty-hall-problem.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-3840964384840359363</guid><pubDate>Fri, 26 Aug 2011 17:56:00 +0000</pubDate><atom:updated>2011-08-26T19:56:11.581+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><category domain="http://www.blogger.com/atom/ns#">Projects</category><title>Balls to the Canvas!</title><description>To play around a bit with the canvas element, I decided to write this:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-Z_d3-EyhzQM/TlfUPXLrJFI/AAAAAAAABBU/iGZgzpSGWOQ/s1600/canvasballs.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="198" src="http://2.bp.blogspot.com/-Z_d3-EyhzQM/TlfUPXLrJFI/AAAAAAAABBU/iGZgzpSGWOQ/s400/canvasballs.png" width="400" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-vM0ygIbE7HQ/TlfUP1nWdPI/AAAAAAAABBc/bNUVtw2lqXE/s1600/canvasballs2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="198" src="http://3.bp.blogspot.com/-vM0ygIbE7HQ/TlfUP1nWdPI/AAAAAAAABBc/bNUVtw2lqXE/s400/canvasballs2.png" width="400" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
You can increase or decrease the number of balls on screen using the UP and DOWN arrows respectively.&lt;br /&gt;
&lt;br /&gt;
&lt;center&gt;&lt;a target="_blank" href="http://dreasgrech.com/upload/balls/index.html"&gt;&lt;span class="Apple-style-span" style="font-size: large;"&gt;View it in action&lt;/span&gt;&lt;/a&gt;&lt;/center&gt;&lt;br /&gt;
&lt;br /&gt;
The source is here: &lt;a href="https://github.com/dreasgrech/balls" target="_blank"&gt;https://github.com/dreasgrech/balls&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;Some implementation details&lt;/h3&gt;&lt;h4&gt;The background&lt;/h4&gt;To implement the colorful background, I'm using a cylindrical-coordinate representation of the RGB color model, known as HSV (Hue Saturation Value).  Keeping the saturation and value to a constant 100 (max), I'm iterating through values 0-360 for the hue thus achieving the blending of colors.  When the hue reaches 360, I reset it back to 0 and the cycle starts over.&lt;br /&gt;
&lt;br /&gt;
The initial value of the hue is randomly chosen at the beginning.&lt;br /&gt;
&lt;h4&gt;Balls&lt;/h4&gt;All of the balls' attributes are randomly generated i.e. the initial position, size, color, speed and angle.&lt;br /&gt;
&lt;br /&gt;
Since collision detection is only applied once the balls hit the edges of the browser window and the edges are axes aligned, I'm simply inverting the part of the velocity's depending to which edge is hit.&lt;br /&gt;
&lt;br /&gt;
If the ball hits either the left or right edge, the x is inverted and if the ball hits the top or bottom edge, the y is inverted.&lt;br /&gt;
&lt;h4&gt;Resizing the window&lt;/h4&gt;I'm hooking to &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;window.onresize&lt;/span&gt; so that once the browser window is resized, I adjust the width of the canvas appropriately and also remove the balls that are now out of screen.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Vangelis',
  name : "The Dragon",
  link : 'http://grooveshark.com/s/The+Dragon/FCwsk?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-3840964384840359363?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/rUX314hzQBI" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/rUX314hzQBI/balls-to-canvas.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-Z_d3-EyhzQM/TlfUPXLrJFI/AAAAAAAABBU/iGZgzpSGWOQ/s72-c/canvasballs.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/08/balls-to-canvas.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-575724863246591743</guid><pubDate>Sat, 14 May 2011 18:59:00 +0000</pubDate><atom:updated>2011-05-14T20:59:22.178+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Mathematics</category><title>Solving systems of linear algebra with Wolfram Alpha</title><description>I recently needed to verify an answer to some problems I was solving at the time, and for that, I used &lt;a href="http://www.wolframalpha.com/input/?i=solve+2x%2By%3D3%2C+x-3y+%3D+9"&gt;Wolfram Alpha&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Say we want to graph the following system of equations:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://latex.codecogs.com/gif.latex?\begin{cases}%202x+y=3%20\\%20x-3y=9%20\end{cases}" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="55" src="http://latex.codecogs.com/gif.latex?\begin{cases}%202x+y=3%20\\%20x-3y=9%20\end{cases}" width="96" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
The syntax would be:&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;solve 2x + y = 3 , x - 3y = 0
&lt;/pre&gt;&lt;br /&gt;
The general format would be:&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;solve &amp;lt;equation 1&amp;gt;, &amp;lt;equation 2&amp;gt;, ... , &amp;lt;equation n&amp;gt;&lt;/pre&gt;&lt;br /&gt;
And the search engine will provide you with something like this:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-_MQCyMsV2Hk/Tc7QE9RnAYI/AAAAAAAAA-0/zoT_7CmZJco/s1600/wolframsystems.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="640" src="http://3.bp.blogspot.com/-_MQCyMsV2Hk/Tc7QE9RnAYI/AAAAAAAAA-0/zoT_7CmZJco/s640/wolframsystems.png" width="523" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-575724863246591743?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/UCfQOidudU4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/UCfQOidudU4/solving-systems-of-linear-algebra-with.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-_MQCyMsV2Hk/Tc7QE9RnAYI/AAAAAAAAA-0/zoT_7CmZJco/s72-c/wolframsystems.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/05/solving-systems-of-linear-algebra-with.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-3204044722736032370</guid><pubDate>Sat, 02 Apr 2011 10:04:00 +0000</pubDate><atom:updated>2011-04-02T12:04:51.933+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Brainfuck</category><title>Writing brainfuck in Bitmap format</title><description>Inspired by this &lt;a href="http://stackoverflow.com/questions/5508110/why-is-this-program-erroneously-rejected-by-three-c-compilers/5509538#5509538" target="_blank"&gt;beautiful answer&lt;/a&gt; from Stack Overflow, I decided I'd do something similar.&lt;br /&gt;
&lt;br /&gt;
The following is a bitmap image I drew in Paint visually showing a working brainfuck program:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://dreasgrech.com/upload/blog/geek.bmp" imageanchor="1"&gt;&lt;img border="0" height="20" src="http://dreasgrech.com/upload/blog/geek.bmp" width="300" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
Download the image, feed it to your &lt;a href="http://home.arcor.de/partusch/html_en/bfd.html" target="_blank"&gt;brainfuck compiler&lt;/a&gt; and then execute the compiled executable.&lt;br /&gt;
&lt;br /&gt;
If everything goes well, you should get something like this:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-VbMv9FcPr7c/TZb0KRLTjNI/AAAAAAAAA8M/dpF1956f6RQ/s1600/compiledbrainfuckbmp.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="135" src="http://1.bp.blogspot.com/-VbMv9FcPr7c/TZb0KRLTjNI/AAAAAAAAA8M/dpF1956f6RQ/s400/compiledbrainfuckbmp.png" width="268" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-3204044722736032370?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/6zyQyH9drqk" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/6zyQyH9drqk/writing-brainfuck-in-bitmap-format.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/-VbMv9FcPr7c/TZb0KRLTjNI/AAAAAAAAA8M/dpF1956f6RQ/s72-c/compiledbrainfuckbmp.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/04/writing-brainfuck-in-bitmap-format.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-8225696556621782789</guid><pubDate>Sun, 27 Mar 2011 13:26:00 +0000</pubDate><atom:updated>2011-04-02T12:36:10.434+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><title>Finding the Answer (ab)using JavaScript</title><description>This is my little tribute to Douglas Adams (and also my first go at obfuscation):&lt;br /&gt;
&lt;br /&gt;
&lt;center&gt;&lt;br /&gt;
&lt;pre&gt;vI=0x2A;(o=eval)((r=unescape)("%5F%5f%"+vI/+(+vI+'')[1]%6+"D%36%3b"))+o(r("%"+__+"1\
%6"+(ww=String["fromCharCode"])(69)+"%73%77%65%72%3D")+((~~[]+011&gt;&gt;!~~~(J=Math)[""]+
(Jan=isNaN)(+/\//[+[]*+-"1"]+""[-1])*~!-+(___=__/2)+2^!+!J['round'](![H=undefined]+1
+o((J+1).substr(!+(B=alert)+-!B+7&lt;&lt;.9-1,!/^/.$-~255&gt;&gt;(2*!o('('+(F='function(')+'ema\
cs){if((dreas=vI)&gt;emacs){always=1}}(vI-5))')-~1*1-(+!(function(){o(arguments[__['co\
nstructor'].prototype*9]+"='"+arguments[0]+"'")}('$'+__))))*2)+"Magnum/* */"[!+''+7]
+".PI")^!H*!Jan(Jan)-+2+1))&lt;&lt;(!0x0-[010][dreas%2]/2+(4&amp;4)+o("'.'+o(((1|__^4*2)+\"\"\
)[1])")&lt;&lt;+!+(c=NaN)&lt;&lt;1^~+!c*-___+(+J['floor'](~2)^-4))|/**/!![,]["le"+($$$=(parseInt
+2))[2]+"g"+$$$[4]+"h"]/**/*(o("o('~1+010+/*~*/~([][0,+$6[1]+2]-always|!{a:1}[0]+24\
&lt;&lt;1)%15&lt;&lt;~!J.ceil.call.apply(J.ceil,[1..toString()])+1')")+0xE^3&lt;&lt;1)&gt;&gt;+!o('('+F+'){\
_:if(!(_=!1)){return}}())')&gt;&gt;!null+_));o(r(["%42",(o+'')[13],answer,(r+'')[18],ww(59
)].                                   join                                    ('')))
&lt;/pre&gt;&lt;/center&gt;&lt;br /&gt;
&lt;br /&gt;
If the layout screwed up, here's how it should look like:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-9xysbAOb3ng/TY86mKBSETI/AAAAAAAAA7o/_tKZ6aNIuDY/s1600/ObfuscatedAnswer.png" imageanchor="1"&gt;&lt;img border="0" height="102" src="http://4.bp.blogspot.com/-9xysbAOb3ng/TY86mKBSETI/AAAAAAAAA7o/_tKZ6aNIuDY/s400/ObfuscatedAnswer.png" width="400" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;a href="http://jsfiddle.net/aTpwf/" target="_blank"&gt;Click here&lt;/a&gt; to run it.&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Why?&lt;/h2&gt;&lt;br /&gt;
&lt;i&gt;tl;dr: it was fun.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
Now basically, the code does 'nothing' except alert the number 42.  Actually, the majority of the code is doing a calculation to come up with the number 42, and then alert it.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Removing a single character from the above code will either invalidate the output or invalidate the code itself with a syntax error&lt;/b&gt; (except from that redundant whitespace on the last line)...and that was actually quite tricky to do (&lt;i&gt;and may not have fully achieved since it wasn't the plan from the beginning&lt;/i&gt;), but was part of the fun in creating this.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;I was actually writing a script that would run through my code removing a single character each time and then running (eval) the script, but I didn't finish it because as it turns out, complicating shit can be pretty fun so I switched back to this.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
But the major part of the fun was finding creative ways of complicating things.  Yup, complicating things!  It felt refreshingly good trying to, for a change, obscure the code as much as possible &lt;i&gt;given that every character is needed for the ultimate outcome&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;How?&lt;/h2&gt;&lt;br /&gt;
For example, let's say I had a calculation which involved the number zero.  Now, the way a sane programmer would represent a zero is by using the 0 literal representation.  But that's obviously too boring for a project like this, so I would try and find new ways of representing the value of zero.  An example would be something like &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;+!!NaN&lt;/span&gt;, or maybe &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;-{}&amp;gt;&amp;gt;1&lt;/span&gt;.&lt;br /&gt;
&lt;br /&gt;
Of course, there's a reason why both those obscure representations evaluate to 0 and how my above code manages to compute and alert the number 42, and one way of finding out those reasons is by painstakingly analysing the &lt;a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf" target="_blank"&gt;spec&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
If you don't have time to carefully go through those 252 pages, what you really need to grasp is JavaScript's type coercion rules due to weak typing...and then, abuse them mercilessly!&lt;br /&gt;
&lt;br /&gt;
I'm not really going to get too much into JavaScript's type system in this post, but I will briefly explain why the above two examples I mentioned evaluate to 0.&lt;br /&gt;
&lt;br /&gt;
Let's take &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;-{}&amp;gt;&amp;gt;1&lt;/span&gt; first.  According to JavaScript's &lt;a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence" target="_blank"&gt;operator precedence rules&lt;/a&gt;, the unary negation sign is evaluated first, thus coercing &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;{}&lt;/span&gt; into the special &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;NaN&lt;/span&gt; value.  Then the bitwise shift coerces the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;NaN&lt;/span&gt; value into a 0 (since &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;NaN&lt;/span&gt; is falsy) and 0 &amp;gt;&amp;gt; 1 is 0.&lt;br /&gt;
&lt;br /&gt;
Now for &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;+!!NaN&lt;/span&gt;, starting with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;!NaN&lt;/span&gt;&lt;span class="Apple-style-span" style="font-family: inherit;"&gt;&amp;nbsp;&lt;/span&gt;evaluating to the boolean value &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;true&lt;/span&gt; because the logical not sign coerces the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;NaN&lt;/span&gt; value to the boolean value &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;false&lt;/span&gt;, and the negation (logical-not) of false is true, so &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;!!NaN&lt;/span&gt; evaluates to &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;false&lt;/span&gt; because double negating false evaluates to true.  Finally, since the + here is used as a &lt;a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#.2b_(Unary_Plus)" target="_blank"&gt;unary operation&lt;/a&gt; and not binary, it coerces &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;false&lt;/span&gt; to 0; and that's it!&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Splitting it up&lt;/h2&gt;&lt;br /&gt;
Up until the end, I was working on a single line with no whitespace but when I was sort of ready with obfuscating, I needed to split the lines up into some shape (remotely representing something)...a task which I figured to be trivial at best.  But as I came to realize, splitting the code into multiple lines without introducing errors is far from trivial.&lt;br /&gt;
&lt;br /&gt;
Reason being of course that you can't just split the line in whichever point you want because  naturally keywords cannot be split and other restrictions of the language syntax restrict you from splitting certain constructs directly into multiple lines.&lt;br /&gt;
&lt;br /&gt;
For example, say you have &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;function(){return}&lt;/span&gt;, you can't for example split in the middle of the word &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;function&lt;/span&gt;:&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;fun&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ction(){return}&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
That will not compile, and neither will compile if you split the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;return&lt;/span&gt; keyword; you can split at any other part of the line though.&lt;br /&gt;
&lt;br /&gt;
But I actually had the most trouble splitting property calls.  Say you had to split &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;[].constructor.prototype&lt;/span&gt;; now that's a bitch because of the two relatively long keywords in the expression.&lt;br /&gt;
&lt;br /&gt;
How did I get around this?  Simple.  I switched from using dot-notation to subscript-notation, and since strings can be successfully split into multiple lines, it was much easier:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;[]['constructor']['prototype']&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Now if we wanted to split:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;[]['construc\&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;tor']['prototype']&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
To split strings into multiple lines in JavaScript, just add the backslash symbol to the end of the unterminated string literal, and now, your splitting task is much easier.&lt;br /&gt;
&lt;br /&gt;
Although using the subscript-notation made the lines easier to split, it introduced a new problem.&lt;br /&gt;
&lt;br /&gt;
Say I have ['ab'] and I need to split between the ' and the a characters.&lt;br /&gt;
&lt;br /&gt;
You can't split like this:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;['&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ab']&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
because now you have an unterminated string, which results in an error; but you also can't do this:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;['\&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ab']&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
because although it runs successfully, you have now added an extra character (\) to the previous line and that would invalidate your box-line shape of the code.  And of course, can't also do this:&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;[&lt;/span&gt;&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;'ab']&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
because, as mentioned previously, although it runs, you have now removed a character from the previous line which would invalidate the box.&lt;br /&gt;
&lt;br /&gt;
This one was a bit more annoying to deal with because, to my knowledge, there is no way around it...but still, this was all part of the challenge involved and it was fun.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-8225696556621782789?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/2Lx3XbQfQc0" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/2Lx3XbQfQc0/finding-answer-abusing-javascript.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-9xysbAOb3ng/TY86mKBSETI/AAAAAAAAA7o/_tKZ6aNIuDY/s72-c/ObfuscatedAnswer.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/03/finding-answer-abusing-javascript.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-2436079412925193980</guid><pubDate>Fri, 25 Feb 2011 23:42:00 +0000</pubDate><atom:updated>2011-02-26T01:23:32.394+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Farseer Physics Engine</category><category domain="http://www.blogger.com/atom/ns#">Game Development</category><category domain="http://www.blogger.com/atom/ns#">XNA</category><category domain="http://www.blogger.com/atom/ns#">Windows Phone 7</category><title>Adapting to Farseer Physics Engine's Meter-Kilogram-Second (MKS) system of units</title><description>Recently switched to version 3.x of &lt;a href="http://farseerphysics.codeplex.com/" target="_blank"&gt;Farseer Physics Engine&lt;/a&gt; and have been experiencing slow simulations since?  Can't get anything to accelerate past a certain point because everything looks like it's floating in a damn aquarium?  Are you frustrated and tearing your hair out because you think this new version "sucks" !?  &lt;a href="http://farseerphysics.codeplex.com/discussions/247591" target="_blank"&gt;Don&lt;/a&gt;&lt;a href="http://farseerphysics.codeplex.com/discussions/244376" target="_blank"&gt;'t&lt;/a&gt; &lt;a href="http://farseerphysics.codeplex.com/discussions/244014" target="_blank"&gt;worry,&lt;/a&gt; &lt;a href="http://farseerphysics.codeplex.com/discussions/244242" target="_blank"&gt;you&lt;/a&gt;&lt;a href="http://farseerphysics.codeplex.com/discussions/244691" target="_blank"&gt;'re&lt;/a&gt; &lt;a href="http://farseerphysics.codeplex.com/discussions/242289" target="_blank"&gt;not&lt;/a&gt; &lt;a href="http://farseerphysics.codeplex.com/discussions/236225" target="_blank"&gt;alone&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Now, take a deep breath and carry on reading...(tl;dr: &lt;a href="https://github.com/dreasgrech/SimplestFarseerPhysics3Example" target="_blank"&gt;demo&lt;/a&gt;)&lt;br /&gt;
&lt;br /&gt;
Starting with 3.x, FPE now uses the MKS (&lt;a href="http://en.wikipedia.org/wiki/MKS_system_of_units" target="_blank"&gt;Meter-Kilogram-Second&lt;/a&gt;) system of units and this has been the source of confusion for both people who were working with version &amp;lt; 3 and also people who were new to FPE.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;Note: Other people have already &lt;a href="http://www.progware.org/Blog/post/XNA-for-Windows-Phone-7-and-Physics.aspx" target="_blank"&gt;written&lt;/a&gt; &lt;a href="http://code.google.com/p/box2d/wiki/FAQ#API" target="_blank"&gt;about&lt;/a&gt; &lt;a href="http://farseerphysics.codeplex.com/documentation" target="_blank"&gt;this&lt;/a&gt; &lt;a href="http://simplefpplatformer.codeplex.com/SourceControl/changeset/view/8501#236789" target="_blank"&gt;topic&lt;/a&gt; but I feel that, since this has been a major source of confusion for many, it hasn't been given the attention it requires&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;hr /&gt;&lt;br /&gt;
To begin with, let's be naive and try to create a &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Body&lt;/span&gt; like such:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;float width = 200f, 
      height = 100f,
      density = 10f;
Vector2 position = new Vector2(300, 400);

Body body = BodyFactory.CreateRectangle(world, width, height, density, position);
&lt;/pre&gt;&lt;br /&gt;
In the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Draw&lt;/span&gt; method, I (naively) draw the texture at the body's position as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;spriteBatch.Draw(texture, body.Position, Color.White);
&lt;/pre&gt;&lt;br /&gt;
What I'm doing above (or what at least I think I'm doing) is create a 200x100 pixel rectangular body positioned at (200, 300) pixels on the screen and then drawing it at wherever the body is at the current moment, starting from our initial (300, 400).&lt;br /&gt;
&lt;br /&gt;
But because now Farseer Physics Engine uses the MKS system of units, &lt;b&gt;what we are actually doing is creating a 200m wide and a 100m high rectangle rectangle positioned 200 meters from the right and 100 meters from the top&lt;/b&gt;!  And Box2D (since Farseer is based on Box2D) &lt;a href="http://code.google.com/p/box2d/wiki/FAQ#API" target="_blank"&gt;tells us&lt;/a&gt; that we should keep our bodies (especially if they move) in the 0.1 - 10 meter range. &lt;br /&gt;
&lt;br /&gt;
This means that we now have to split the way we position physics objects on screen and the way we draw their corresponding textures.&lt;br /&gt;
&lt;br /&gt;
&lt;hr /&gt;&lt;br /&gt;
To accomplish this, we can use the &lt;a href="http://farseerphysics.codeplex.com/SourceControl/changeset/view/85371#1642119" target="_blank"&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ConvertUnits&lt;/span&gt;&lt;/a&gt; class found under &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Samples\Samples XNA\Samples XNA\ScreenSystem&lt;/span&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ConvertUnits&lt;/span&gt; is a helper class that lets us switch between display units (pixels) and simulation units (MKS) easily.&lt;br /&gt;
&lt;br /&gt;
So let's go back to that previous example and fix our code by first converting our display units to simulation units with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ConvertUnits.ToSimUnits&lt;/span&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;float width = ConvertUnits.ToSimUnits(200f), 
      height = ConvertUnits.ToSimUnits(100f),
      density = 10f;
Vector2 position = ConvertUnits.ToSimUnits(300, 400); // ToSimUnits has an overload which returns a vector given two floats.

Body body = BodyFactory.CreateRectangle(world, width, height, density, position);
&lt;/pre&gt;&lt;br /&gt;
Now to draw our body on screen, we need to convert the simulation units back to display units by the appropriately named method &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;ConvertUnits.ToDisplayUnits&lt;/span&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;spriteBatch.Draw(texture, ConvertUnits.ToDisplayUnits(body.Position), Color.White);
&lt;/pre&gt;&lt;br /&gt;
&lt;hr /&gt;&lt;br /&gt;
Still can't get it?  No worries, because I created the simplest Farseer Physics 3 example you can find which demonstrates what I said above: &lt;a href="https://github.com/dreasgrech/SimplestFarseerPhysics3Example"  target="_blank"&gt;https://github.com/dreasgrech/SimplestFarseerPhysics3Example&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
The example creates a rectangle and lets gravity do its part; that's it!  I've compiled it for both the Windows and the Windows Phone 7 XNA versions.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;Another note: Since FPE is currently undergoing the upgrade to 3.3, the above code example can break if used with a different version of the engine.  I've compiled the example with the version from Changeset &lt;a href="http://farseerphysics.codeplex.com/SourceControl/changeset/changes/85352" target="_blank"&gt;#85352&lt;/a&gt;.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : 'Blue Öyster Cult',
  name : "Astronomy",
  link : 'http://listen.grooveshark.com/s/Astronomy/2C1gqQ?src=5'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-2436079412925193980?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/jBd9YnDqK-8" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/jBd9YnDqK-8/farseer-physics-engines-meter-kilogram.html</link><author>noreply@blogger.com (Andreas Grech)</author><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/02/farseer-physics-engines-meter-kilogram.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-8562102692547223281</guid><pubDate>Sun, 13 Feb 2011 19:14:00 +0000</pubDate><atom:updated>2011-11-30T06:03:11.348+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Projects</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">Genetic Algorithms</category><title>StringEvolver: Evolving strings with a genetic algorithm</title><description>This is my first attempt at experimenting with a genetic algorithm.  The following is an application that evolves a string given a destination to converge to.&lt;br /&gt;
&lt;br /&gt;
&lt;center&gt;&lt;iframe width="640" height="360" src="http://www.youtube.com/embed/OkSrcncPt04?hd=1" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;/center&gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example run:&lt;br /&gt;
&lt;pre&gt;&amp;gt; StringEvolver -m 0.25 -s 0.6 -c 2000 -e 0.1 --fitness=hamming --ctype=one -t 0.3 "Charles Darwin was right!"

Evolution Destination: Charles Darwin was right!
Mutation Rate: 25%
Crossover Rate: 60%
Truncation Rate: 30%
Chromosomes / population: 2000
Elitism / population: 200 (0.1%)
Fitness Calculator: Hamming Distance
Crossover Type: One Point

    1: L&amp;lt;eI`Y@ D#raF'JKJ7DUAg&amp;quot;GR
    2: L&amp;lt;eI`Y@ D#raF'JKJ7DUAg&amp;quot;GR
    3: chNOLe&amp;quot;5]={Iiyrgk*,rEpE/!
    4: L&amp;lt;eI`Y@ D#ra nR$C1SrYqha+
    5: L&amp;lt;eI`Y@ D#ra nR$C1SrYqha+
    6: lpa5`Y@ D#ra nR$C8y.iqrt5
    7: C]Y&amp;amp;hJ1 %aRwi&amp;lt; aaB,r_Zh68
    8: 1s[r.ts %aGwi&amp;lt; _a&amp;quot;=rjXyN!
    9: chNOlFsyD#rwi&amp;lt; }aB,r_Zh68
   10: chNO9e&amp;quot; D#rwi&amp;lt; }aB=rPgh6!
   11: chNO9e&amp;quot; D#rwi&amp;lt; }aB=rPgh6!
   12: 1s[r.Ks D#ra n}way rAght!
   13: C}hplFs D#rwi.}way rPgh6!
   14: C'aclos Da{]inrwas r.ghx!
   15: C'aclos Da{]inrwas r.ghx!
   16: ChNrlFs Da&amp;gt;win}was  `gha!
   17: ChNrlFs Da&amp;gt;winlwas r;gh6!
   18: Ch[rlFs Da&amp;gt;wi&amp;lt; was rAght!
   19: Chacle@ D#rwin was rjght!
   20: Chacle@ D#rwin was rjght!
   21: ChNrles Darwin}was rAght!
   22: ChNrles Darwin}was rAght!
   23: Charles Darwin}was r`ght!
   24: Charles Darwin}was r`ght!
   25: Charles Darwin was rAght!
   26: Charles Darwin was rAght!
   27: Charles Darwin was rAght!
   28: Charles Darwin was rAght!
   29: Charles Darwin was rAght!
   30: Charles Darwin was right!

Found in 30 generations
Time Taken: 00:00:00.4730271
&lt;/pre&gt;&lt;h4&gt;Source&lt;/h4&gt;You can download the source from github: &lt;a href="https://github.com/dreasgrech/StringEvolver" target="_blank"&gt;https://github.com/dreasgrech/StringEvolver&lt;/a&gt;&lt;br /&gt;
&lt;h4&gt;Command Line arguments&lt;/h4&gt;&lt;b&gt;-m, --mutation=VALUE&lt;/b&gt;&lt;br /&gt;
A value between 0-1&lt;br /&gt;
&lt;br /&gt;
The mutation rate determines the probability of how often a &lt;i&gt;selected&lt;/i&gt; chromosome mutates.  Mutation is very important in a genetic algorithm because it helps in keeping diversity in the population, thus avoid local minima which can slow or even halt further evolution.&lt;br /&gt;
&lt;br /&gt;
The application currently uses a mutation operator called &lt;b&gt;Single Point Mutation&lt;/b&gt;.  For our current application, it works by randomly selecting a point in the string and switching the character at that point to another random character.&lt;br /&gt;
&lt;br /&gt;
As an example, say the chromosome to be mutated currently contains the string "aBcdE".  The single point mutation operator then randomly chooses position 2 (0-based) and replaces the character 'c' with the randomly chosen character 'W'.&lt;br /&gt;
&lt;br /&gt;
This way, the chromosome "aBcdE" has now been mutated to "aBWdE".  &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;-s, --crossover=VALUE&lt;/b&gt;&lt;br /&gt;
A value between 0-1&lt;br /&gt;
&lt;br /&gt;
The crossover rate determines how often two &lt;i&gt;selected&lt;/i&gt; chromosomes are sexually combined to produce two separate offspring.&lt;br /&gt;
&lt;br /&gt;
For this application, there are two available crossover operations: &lt;b&gt;One Point Crossover&lt;/b&gt; and &lt;b&gt;Two Point Crossover&lt;/b&gt;.  These operators are discussed further in the ctype argument.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;-e, --elitism=VALUE&lt;/b&gt;&lt;br /&gt;
A value between 0-1&lt;br /&gt;
&lt;br /&gt;
The elitism rate determines the number of the fittest solutions that are directly (untouched) transferred to the advancing population.&lt;br /&gt;
&lt;br /&gt;
Elitism can help in preventing the potential loss of possibly good solutions and can lead to quicker convergence.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;-c, --crcount=VALUE&lt;/b&gt;&lt;br /&gt;
A value greater than 1&lt;br /&gt;
&lt;br /&gt;
The chromosome count determines the number of chromosomes that each population will have.  The greater the number of chromosomes, the more time a population takes to advance to the next.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;--fitness=VALUE&lt;/b&gt;&lt;br /&gt;
VALUE = &lt;i&gt;sum&lt;/i&gt;, &lt;i&gt;levenshtein&lt;/i&gt; or &lt;i&gt;hamming&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
The fitness calculator determines which algorithm is used to calculate how fit a given chromosome is.&lt;br /&gt;
&lt;br /&gt;
There are currently three fitness calculators to choose from:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Sum&lt;/b&gt;&lt;br /&gt;
The sum calculator calculates the ASCII difference between each character of the target strings.&lt;br /&gt;
&lt;pre name="code" class="csharp"&gt;public override double CalculateFitness(Chromosome ch)
{
    var distanceToTarget = Target.Select((t, i) =&amp;gt; Math.Abs(t - ch.Value[i])).Sum();
    return 1.0 / distanceToTarget;
}
&lt;/pre&gt;&lt;b&gt;Levenshtein Distance&lt;/b&gt;&lt;br /&gt;
The Levenshtein distance between two strings is the minimum number of edits needed to transform one string into the other.  The transformation can include insertion, deletion and substitution.  This distance is also referred to as the edit distance.&lt;br /&gt;
&lt;pre name="code" class="csharp"&gt;public override double CalculateFitness(Chromosome ch)
{
    return 1.0 / LevenshteinDistance(ch.Value, Target);
}
&lt;/pre&gt;&lt;b&gt;Hamming Distance&lt;/b&gt;&lt;br /&gt;
The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.  The reason Hamming distance requires the strings to be of equal length is because unlike the Levenshtein distance, the Hamming distance only allows substitutions.&lt;br /&gt;
&lt;br /&gt;
As an example, the Hamming distance between "janica" and "jenixo" is 3.&lt;br /&gt;
&lt;pre name="code" class="csharp"&gt;public override double CalculateFitness(Chromosome ch)
{
    if (ch.Value.Length != Target.Length)
    {
        return 1.0 / double.PositiveInfinity;
    }

    var difference = 0;
    for (int i = 0; i &amp;lt; Target.Length; i++)
    {
        if (ch.Value[i] != Target[i])
        {
            difference++;
        }
    }
    return 1.0 / difference;
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;--ctype=VALUE&lt;/b&gt;&lt;br /&gt;
VALUE = &lt;i&gt;one&lt;/i&gt; or &lt;i&gt;two&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
The crossover type determines which crossover operator is to be used when sexually combining two chromosomes.&lt;br /&gt;
&lt;br /&gt;
There are currently two available methods to choose from:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;One&lt;/b&gt;&lt;br /&gt;
The One-Point Crossover method chooses a random point (called a &lt;a href="http://en.wikipedia.org/wiki/Locus_(genetics)" target="_blank"&gt;locus&lt;/a&gt;) in the string and all the data beyond that point in either chromosome is swapped between the parent chromosomes.  The resulting two chromosomes are the children.&lt;br /&gt;
&lt;pre name="code" class="csharp"&gt;public Tuple&amp;lt;Chromosome, Chromosome&amp;gt; Crossover(Chromosome c1, Chromosome c2)
{
    var locus = random.Next(0, c1.Value.Length + 1);
    string ch1 = c1.Value.Substring(0, locus) + c2.Value.Substring(locus),
           ch2 = c2.Value.Substring(0, locus) + c1.Value.Substring(locus);

    return new Tuple&amp;lt;Chromosome, Chromosome&amp;gt;(new Chromosome(ch1, fitnessCalculator), new Chromosome(ch2, fitnessCalculator));
}
&lt;/pre&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/_xl08dEExoZk/TSBl0pinDkI/AAAAAAAAA6s/FGZz9Vc6zqk/s1600/onepoint-crossover.png" imageanchor="1" style=""&gt;&lt;img border="0" height="192" width="223" src="http://4.bp.blogspot.com/_xl08dEExoZk/TSBl0pinDkI/AAAAAAAAA6s/FGZz9Vc6zqk/s320/onepoint-crossover.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;Two&lt;/b&gt;&lt;br /&gt;
The Two-Point Crossover method is very similar to the One-Point Crossover method but this one chooses two random points along the string rather than one.  The data between the two points is swapped and the resulting chromosomes are the children.&lt;br /&gt;
&lt;pre name="code" class="csharp"&gt;public Tuple&amp;lt;Chromosome, Chromosome&amp;gt; Crossover(Chromosome c1, Chromosome c2)
{
    int locus1 = random.Next(0, c1.Value.Length),
        locus2 = random.Next(locus1, c1.Value.Length),
        distance = locus2 - locus1;

    string ch1 = c1.Value.Substring(0, locus1) + c2.Value.Substring(locus1, distance) + c1.Value.Substring(locus2),
           ch2 = c2.Value.Substring(0, locus1) + c1.Value.Substring(locus1, distance) + c2.Value.Substring(locus2);

    return new Tuple&amp;lt;Chromosome, Chromosome&amp;gt;(new Chromosome(ch1, fitnessCalculator), new Chromosome(ch2, fitnessCalculator));
}
&lt;/pre&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/_xl08dEExoZk/TSBn6D-ghpI/AAAAAAAAA60/Co_N2yomVec/s1600/twopoint-crossover.png" imageanchor="1" style=""&gt;&lt;img border="0" height="192" width="223" src="http://3.bp.blogspot.com/_xl08dEExoZk/TSBn6D-ghpI/AAAAAAAAA60/Co_N2yomVec/s320/twopoint-crossover.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;-t, --truncate=VALUE&lt;/b&gt;&lt;br /&gt;
&lt;i&gt;0 &amp;lt; VALUE &amp;lt;= 1&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
The Truncation value determines how many chromosomes of the current population should be kept and used for the selection, crossover and mutation operations.  Note that before the truncation is performed, the chromosomes in the population are sorted in descending order by their fitness, so the fittest chromosomes are kept after the truncation.&lt;br /&gt;
&lt;br /&gt;
A value of &lt;i&gt;1&lt;/i&gt; uses all of the chromosomes and a value of &lt;i&gt;0.5&lt;/i&gt; uses half of the population (the better half, of course)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-8562102692547223281?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/DUhErz4q67g" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/DUhErz4q67g/stringevolver-evolving-strings-with.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://img.youtube.com/vi/OkSrcncPt04/default.jpg" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2011/02/stringevolver-evolving-strings-with.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-1538522283185788498</guid><pubDate>Thu, 23 Dec 2010 14:27:00 +0000</pubDate><atom:updated>2010-12-23T17:46:49.820+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">XNA</category><category domain="http://www.blogger.com/atom/ns#">Projects</category><title>The A* algorithm in XNA</title><description>The &lt;a href="http://en.wikipedia.org/wiki/A*_search_algorithm" target="_blank"&gt;A* search algorithm&lt;/a&gt; ("A star") is used for path finding and graph traversal. The following is my implementation in XNA.  &lt;br /&gt;
&lt;br /&gt;
The A* algorithm itself is very similar to &lt;a href="http://en.wikipedia.org/wiki/Dijkstra's_algorithm" target="_blank"&gt;Dijkstra's algorithm&lt;/a&gt; but the A* uses heuristics to achieve better performance.&lt;br /&gt;
&lt;h4&gt;Screenshots&lt;/h4&gt;&lt;div class="gallery"&gt;&lt;div class="imgholder"&gt;&lt;a href="http://1.bp.blogspot.com/_xl08dEExoZk/TRKDWZc3a2I/AAAAAAAAA6M/-BEjQm5dAGk/s1600/astar0.png" imageanchor="1"&gt;&lt;br /&gt;
&lt;img border="0" class="img" src="http://1.bp.blogspot.com/_xl08dEExoZk/TRKDWZc3a2I/AAAAAAAAA6M/-BEjQm5dAGk/s320/astar0.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="imgholder"&gt;&lt;a href="http://1.bp.blogspot.com/_xl08dEExoZk/TRJU2VVHFOI/AAAAAAAAA50/_gZRuA4ieHw/s1600/astar1.png" imageanchor="1" target="_blank"&gt;&lt;br /&gt;
&lt;img border="0" class="img" src="http://1.bp.blogspot.com/_xl08dEExoZk/TRJU2VVHFOI/AAAAAAAAA50/_gZRuA4ieHw/s320/astar1.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="imgholder"&gt;&lt;a href="http://2.bp.blogspot.com/_xl08dEExoZk/TRJU2rFXFFI/AAAAAAAAA58/jFhcyCTFWqU/s1600/astar2.png" imageanchor="1" target="_blank"&gt;&lt;br /&gt;
&lt;img border="0" class="img" src="http://2.bp.blogspot.com/_xl08dEExoZk/TRJU2rFXFFI/AAAAAAAAA58/jFhcyCTFWqU/s320/astar2.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="imgholder"&gt;&lt;a href="http://4.bp.blogspot.com/_xl08dEExoZk/TRJU22JQYDI/AAAAAAAAA6E/m8SfPzbhUKc/s1600/astar3.png" imageanchor="1" target="_blank"&gt;&lt;br /&gt;
&lt;img border="0" class="img" src="http://4.bp.blogspot.com/_xl08dEExoZk/TRJU22JQYDI/AAAAAAAAA6E/m8SfPzbhUKc/s320/astar3.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="clear"&gt;&lt;/div&gt;&lt;h4&gt;Usage&lt;/h4&gt;&lt;b&gt;Left Mouse Click&lt;/b&gt; - Create a barrier&lt;br /&gt;
&lt;b&gt;CTRL + Left Mouse Click&lt;/b&gt; - Set the source&lt;br /&gt;
&lt;b&gt;ALT + Left Mouse Click&lt;/b&gt; - Set the destination&lt;br /&gt;
&lt;b&gt;Space&lt;/b&gt; - Toggle grid lines&lt;br /&gt;
&lt;b&gt;Enter&lt;/b&gt; - Start pathfinding!&lt;br /&gt;
&lt;b&gt;`&lt;/b&gt; - Open the developer console&lt;br /&gt;
&lt;h4&gt;Heuristics&lt;/h4&gt;The A* algorithm uses a heuristic to improve performance by trying to "guess" the best path, although this will not, unlike Dijkstra's which does not use a heuristic, guarantee the shortest path.&lt;br /&gt;
&lt;h5&gt;&lt;a href="http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S9" target="_blank"&gt;Diagonal Distance&lt;/a&gt;&lt;/h5&gt;&lt;pre class="csharp" name="code"&gt;public int GetEstimate(Point source, Point destination)
{
    return Math.Max(Math.Abs(destination.X - source.X), Math.Abs(destination.Y - source.Y));
}
&lt;/pre&gt;&lt;h5&gt;&lt;a href="http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S8" target="_blank"&gt;Manhattan Distance&lt;/a&gt;&lt;/h5&gt;&lt;pre class="csharp" name="code"&gt;public int GetEstimate(Point source, Point destination)
{
    return Math.Abs(destination.X - source.X) + Math.Abs(destination.Y - source.Y);
}
&lt;/pre&gt;&lt;h5&gt;&lt;a href="http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S10" target="_blank"&gt;Euclidean Distance&lt;/a&gt;&lt;/h5&gt;&lt;pre class="csharp" name="code"&gt;public int GetEstimate(Point source, Point destination)
{
    return (int)Math.Sqrt(Math.Pow(source.X - destination.X,2) + Math.Pow(source.Y - destination.Y,2));
}
&lt;/pre&gt;&lt;h5&gt;Dijkstra&lt;/h5&gt;When the heuristic is 0, the A* algorithm turns into Dijkstra's algorithm&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public int GetEstimate(Point source, Point destination)
{
    return 0;
}
&lt;/pre&gt;&lt;h4&gt;Try it!&lt;/h4&gt;The source can be found on github: &lt;a href="https://github.com/dreasgrech/AStarXNA" target="_blank"&gt;https://github.com/dreasgrech/AStarXNA&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : "Rainbow",
  name : "Catch the Rainbow",
  link : 'http://listen.grooveshark.com/s/Catch+The+Rainbow/wRGDF'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-1538522283185788498?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/Gp7xqxyifQE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/Gp7xqxyifQE/a-algorithm-in-xna.html</link><author>noreply@blogger.com (Andreas Grech)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/_xl08dEExoZk/TRKDWZc3a2I/AAAAAAAAA6M/-BEjQm5dAGk/s72-c/astar0.png" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2010/12/a-algorithm-in-xna.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7117612757607239790.post-5116013404290944717</guid><pubDate>Tue, 21 Dec 2010 09:48:00 +0000</pubDate><atom:updated>2010-12-21T10:50:23.987+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Javascript</category><title>A String.Format for JavaScript</title><description>The following is my implementation of a miniature version of &lt;a href="http://msdn.microsoft.com/en-us/library/system.string.format.aspx" target="_blank"&gt;.NET's String.Format&lt;/a&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="javascript" name="code"&gt;String.format = String.format || function (format) {
    var params = [].splice.call(arguments, 1), nextOpen, nextClose = 0, index, plValue, spaces, totalSpaces;

    while ((nextOpen = format.indexOf('{', nextClose)) &amp;gt;= 0) {
        if (isNaN(+format[nextOpen+1])) {
            nextClose = nextOpen + 1;
            continue;
        }
        nextClose = format.indexOf('}', nextOpen);
        index = format.substring(nextOpen + 1, nextClose);
        if (index.indexOf(',') &amp;gt; 0) {
            spaces = +index.substring(index.indexOf(',') + 1);
            index = +index.substring(0, index.indexOf(','));
        }
        plValue = params[index] + '';
        if (spaces) {
            totalSpaces = new Array(Math.abs(spaces) - plValue.length + 1).join(&amp;quot; &amp;quot;);
            plValue = spaces &amp;gt; 0 ? totalSpaces + plValue : plValue + totalSpaces;
        }
        format = format.substring(0, nextOpen) + ((!plValue &amp;amp;&amp;amp; plValue != 0) ? &amp;quot;&amp;quot; : plValue) + format.substring(nextClose + 1);
        spaces = 0;
    }
    return format;
};
&lt;/pre&gt;&lt;h4&gt;Usage&lt;/h4&gt;&lt;pre class="javascript" name="code"&gt;String.format("Hello {0} {1}", "Andreas", "Grech");  // "Hello Andreas Grech"

for (var i = 0; i &amp;lt;= 1000; i += 200) {
    String.format(&amp;quot;{0, 5}. Something&amp;quot;, i);
}

/* Output:
    0. Something
  200. Something
  400. Something
  600. Something
  800. Something
 1000. Something
*/

String.format("Padded from {0, 7} left", "the");  // "Padded from     the left"
&lt;/pre&gt;&lt;br /&gt;
You can fork this project at github:  &lt;a href="https://github.com/dreasgrech/JSStringFormat" target="_blank"&gt;https://github.com/dreasgrech/JSStringFormat&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class="blogmusic"&gt;&lt;script&gt;
kaholic.blogmusic([
{ artist : "Fleetwood Mac",
  name : "The Chain",
  link : 'http://listen.grooveshark.com/s/The+Chain/2CR7lJ'
}
]);
&lt;/script&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7117612757607239790-5116013404290944717?l=blog.dreasgrech.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Knowledge-aholic/~4/fe2ZSa9nGpA" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/Knowledge-aholic/~3/fe2ZSa9nGpA/stringformat-for-javascript.html</link><author>noreply@blogger.com (Andreas Grech)</author><thr:total>0</thr:total><feedburner:origLink>http://blog.dreasgrech.com/2010/12/stringformat-for-javascript.html</feedburner:origLink></item></channel></rss>

