Monday, July 19, 2010

Default function formal parameters in Javascript

Having been programming quite a bit in Ruby and PHP lately, I have gotten used to default formal parameters. This is when you can call a function and omit some of the parameters, the function then assigns pre-defined default values when evaluating those parameters.

It's quite handy at times and helps keep the code succinct and clean.

To see what I mean, in ruby for example you would do the following:

  def a_function(a_param = default_value)
    ...
  end

Later on, the function above could be called in any of the following ways:
  # call function with default param values
  a_function()

  # or specifying a value for the param
  a_function("foo")

In order to achieve the same in Javascript the following is recommended:
  def a_js_function(a_param) {
    var a_param = a_param || default_value;
  }

With the above, you can now call your Javascript function in any of the following ways depending on what you're looking at achieving:

  // call function with default param values
  a_js_function();

  // specify a value for that parameter
  a_js_function("foo");

Note that you can apply the above to all the required parameters of your Javascript function.

That's it!

Wednesday, June 23, 2010

Solving it: iOS 4.0 installation stalls on iPhone 3G issue

I did a successful upgrade to iOS 4.0 last night on my iPhone 3G although I started it a day earlier. If anyone turns out to have an issue where their updates gets stuck at about 60% or 90% no matter how many times they restart it, or how long they wait, the solution is as follows:

depending on the computer operating system of the user, they should open one of the following folders:

  • Mac OS: ~/Library/Application Support/MobileSync/Backup
  • Windows XP: %AppData%\Apple Computer\MobileSync\Backup
  • Windows Vista: %AppData%\Roaming\Apple Computer\MobileSync\Backup
  • Windows 7: %AppData%\Roaming\Apple Computer\MobileSync\Backup

Then move the backup folder inside it to their desktop (move, not copy it).
The next step is to restart the restore process for with the iOS 4.0 ipsw. It will go through seamlessly.

Once it's done as iTunes and the phone will let them know, they should unplug it from iTunes and unplug the USB cable from their PC / Mac

Next, they should move the backup folder that was inside the directory above back to its original location. Replug the iPhone and it will restore their data from iPhone OS 3.y.x.

Hope this helps as it took me 2 days to figure this out and googling did not help at the time.

Friday, June 4, 2010

CSS List-Based Tables

This morning I needed to put together a layout for a demo. It was previously done with HTML Tables (there is nothing wrong with using tables when you've got to use tables), however, I've felt the need to convert it into a CSS-list-ish table instead. A couple of hours of looking around the Internet and I couldn't really find what I needed. So I came up with the following which satisfies my requirements in running seamlessly in the latest browsers. I haven't checked it out in Internet Explorer however, so not too sure how it'd do there. But for my current requirement, it works perfectly. Here's the CSS code for the stylesheet:

/* here is our table */
.table {
  display: table;
  border-collapse: collapse;
  margin-left: auto;
  margin-right: auto;
  width: 95%;
  overflow: auto;
  text-align: left;
  border-top: 1px solid #CCC;
  border-right: 1px solid #CCC;
}

.table ul {
  display: table-row;
  list-style: none;
  height: 2em;
  width: 100%;
}

.table ul li {
  display: table-cell;
  height: 2em;
  border-left: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  padding: 0.5em 0.5em;
  width:10%;
}

.table ul.header {
  height: 2.5em;
  background: #EEE;
}

.table ul.header li {
  height: 2.5em;
  text-align: left;
  font-weight: bold;
  font-size: 1em;
  padding-top: 0.7em;
  padding-bottom: 0;
}

A typical example of using the stylesheet above would look as follows:

  • Product Name
  • Product Code
  • Unit Price
  • Quantity
  • MacBook Pro
  • ML-1025a
  • USD 1500
  • 2
  • Google Nexus One
  • GNO-v1.0
  • USD 499
  • 10

Well that's it. Hope someone finds it useful.

Saturday, October 17, 2009

Implementing Syntax Highlighting on your blog / website

One of things that has always been missing on my blog as a techie and programmer (and you can judge that from older posts) was a Language / Script Syntax Highlighter. Sometime last week I finally decided to work on a solution for this. Before I continue, credits where they are due (no need to re-invent the wheel if it's already been done, right?):

  • Loading external Javascript files: depending on your situation, you might need to load all the Javascript files that you require from an external server. For example, if you are exclusively using the Blogger platform like I am, you may need to load your files externally as you cannot per-say upload them to the blogger server for use in your scripts. In order to do this, I found a very useful script here: Snipplr LoadScript Function.
  • SyntaxHighlighter: This is a fully functional self-contained code syntax highlighter developed in Javascript by Alex Gorbatchev.
After a bit of Googling, I found my perfect solution. It's called SyntaxHighlighter and has been around for quite a while (since 2004). However, when you Google for it, the first links that show up are that of older versions. SyntaxHighlighter is a work in progress and is already on version 2.x.x. So let's dive straight into the code. The first step you'd like to take loading the style sheets that you'd like to use for your code listing. There is the essential / core one which is shCore.css. Once that's loaded, you should have a look at the various available themes to see which one you'd like to use. Head over here. I personally prefer the default theme as it fits with the white and plain color scheme of my blog. Once all the decisions above have been made, you should go ahead and add the following lines of code to the "head" tag of your blog:

<link href='http://alexgorbatchev.com/pub/sh/2.0.320/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/2.0.320/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>

Note that you can replace the default theme by looking at the available files available here. Once you're satisfied with the styling, you can move on to the first interesting section of the implementation.

First, add in the script that's needed to load external Javascript files. Also, you'd like to define a URI variable that will be used to refer to the main URI where your files will be loaded from. In the script below, the variable loadURI has been created just for that purpose. As per the reference above, we will use the loadScript function. Right under the previous CSS links we created, add the following lines of code:

<script type="text/javascript">
//<![CDATA[
// let's define a variable for the URL, making it easier to change
// should the case arise
var loadURI = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/';

// reference: http://snipplr.com/view/18756/loadscript/
function loadScript(url, callback){

 var script = document.createElement("script")
 script.type = "text/javascript";

 if (script.readyState){  //IE
  script.onreadystatechange = function(){
   if (script.readyState == "loaded" || script.readyState == "complete") {
     script.onreadystatechange = null;
     callback();
   }
  };
 } else {  //Others
  script.onload = function(){
   callback();
  };
 }

 script.src = url;
 document.getElementsByTagName("head")[0].appendChild(script);
}
//]]>
</script>

The script above will allow you to load all the subsequent Javascript files you'd like to use from the external server. As specified before, this is very useful if you are not able to host the files on your blogging platform. It's time to use the script above. Assuming that you'd like to load the scripts straight from the servers where they're published (cautionary note: you should not be doing this), you'd add the following lines to the script above:

loadScript(loadURI + 'shCore.js', function(){
 loadScript(loadURI + 'shBrushCss.js', function(){});
 loadScript(loadURI + 'shBrushSql.js', function(){});
 loadScript(loadURI + 'shBrushPhp.js', function(){});
 loadScript(loadURI + 'shBrushJava.js', function(){});
 loadScript(loadURI + 'shBrushJScript.js', function(){});
 loadScript(loadURI + 'shBrushBash.js', function(){});
 loadScript(loadURI + 'shBrushXml.js', function(){});
 initSyntaxHighlighter();
});

As you can see, the scripts that I've added are those for the languages I'd like to support on my blog. Basically, with the above, the following languages will be automatically supported: CSS, SQL, PHP, Java, Javascript, Bash. Obviously, we all have different needs. In order to see what fits your needs, you should have a look at the following page: Bundled Syntaxes. Head over here to see what the concrete names of the files are. Once you've decided on the scripts that you need, all you have to do is to make sure they're loaded in the main template of your blog / website or you could write some script that would load them dynamically on demand. One essential point to note is that the shCore.js definitely needs to be the first one to be included as per my example above. Once loaded, we use the callback functionality of the loadScript function to load the remaining scripts. This ensures that shCore.js is all loaded into the browser before downloading the other script files. Not doing it this way (as I have learned) would results in Reference Errors in WebKit (engine behind Safari, Opera, Google Chrome, etc...). After all the loadScript calls, there is an aditional function initSyntaxHighlighter() call, which will be explained further down the line. All in all the full script should now be looking like this:

<script type="text/javascript">
//<![CDATA[
// reference: http://snipplr.com/view/18756/loadscript/
function loadScript(url, callback){

 var script = document.createElement("script")
 script.type = "text/javascript";

 if (script.readyState){  //IE
  script.onreadystatechange = function(){
   if (script.readyState == "loaded" || script.readyState == "complete") {
     script.onreadystatechange = null;
     callback();
   }
  };
 } else {  //Others
  script.onload = function(){
   callback();
  };
 }

 script.src = url;
 document.getElementsByTagName("head")[0].appendChild(script);
}

// load the scripts for the language we'd like 
// to have syntax highlighting for on our blog / website
loadScript(loadURI + 'shCore.js', function(){
 loadScript(loadURI + 'shBrushCss.js', function(){});
 loadScript(loadURI + 'shBrushSql.js', function(){});
 loadScript(loadURI + 'shBrushPhp.js', function(){});
 loadScript(loadURI + 'shBrushJava.js', function(){});
 loadScript(loadURI + 'shBrushJScript.js', function(){});
 loadScript(loadURI + 'shBrushBash.js', function(){});
 loadScript(loadURI + 'shBrushXml.js', function(){});
 initSyntaxHighlighter();
});

//]]>
</script> 


The SyntaxHighlighter is almost setup. The next step will be to have a look at how you'd like to configure it. My own configuration is very basic. For more info on all the options as far as the configuration of the script is concerned, you should check the SyntaxHighliter Configuration wiki page. For a very simple and basic configuration, append the following lines of code to the previous one:

function initSyntaxHighlighter()
 {
  SyntaxHighlighter.bloggerMode = true; // set to false or remove if not on blogger platform
  SyntaxHighlighter.stripBrs = false;
  SyntaxHighlighter.clipboardSwf = loadURI + 'clipboard.swf';
  SyntaxHighlighter.all();
 }

Pay attention to the name of this function. It's the same function we call in the loadScript callback of shCore.js. We call it at that stage for the same reason as earlier: avoiding variable or class name Reference Errors in WebKit.

What you may notice here is that I have set the bloggerMode to true. This is because I am hosting my configuration on the blogger platform. If you're hosting on a non-blogger platform, make sure to set that configuration parameter to false or remove that line of code altogether. Once you're happy with the configuration above, you should go ahead and test it. To use see results of all the hard work above, you'd use CSS classes related to the syntax highlighting languages you've included. An example of using it for a bash script for example would be as follows

<pre class="brush: bash;">
  !#/bin/bash
  echo "hello world!"
  export $path:/something/somewhere
</pre>

You will notice the use of "brush" in the class. That's just how you'd use it. So, if you were to need a Javascript syntax highlight, all you'd have to do is to use the "pre" tag or any other tag that you'd specify although "pre" is pretty convenient and add the class as follows: class="brush: html;". This works almost the same way as when adding the style attribute to your tags.

Here's a screenshot of what you will get if everything got properly setup:



Hope this helps anyone else who is looking for a way to have syntax highlighting on their websites or blogs. I find it extremely useful and it's first usage on my blog has been for this post.

Note:I have added all of the sample code above in a one example HTML file which can be downloaded here: Sample Demo File.

Update:You should also download the following PNG files and make sure that they are in the same directory as the CSS files you've linked above. The files are:

Monday, March 9, 2009

Super-Easy Sortable Table

This morning, I needed to find a way to sort some Data on the front-end or back-end, depending on the solution I came up with. The day before, I had written this whole super-cool implementation for the sorting which worked nicely with PDOs (PHP Data Objects) and my model objects. Thing is, as far as sorting the data is concerned, there should be a easier and faster way which reduces the load on the server (both database and page serving) and lets the client do all the work.

I had a explored a few of the lovely jQuery solutions and despite my love for jQuery, I thought they were overkill. I just found a solution that takes about 5 minutes to implement and customize and that works brilliantly.

Here's the link: http://yoast.com/articles/sortable-table/

There is only one catch though: I am lucky with this, the amount of data I am pushing back and forth and very small and will remain small; however, if you will be doing some sort of pagination, this script is not a good idea as it only sorts the data on the current page. Meaning that the data on the further pages are not sorted. So, if you had a "Z" somewhere in your records, because the sorting is not happening on the database end, it will not come up as top or first record. Just something to keep in mind.


Cheers!

Friday, November 14, 2008

mod_rails (Passenger) setup issues with Apache2 on OS X

mod_rails not finding Apache2 APR



When installing mod_rails with a custom Apache2 setup, you may get the following while running sudo passenger-install-apache2-module:


Compiling and installing Apache 2 module...
cd /usr/local/lib/ruby/gems/1.8/gems/passenger-2.0.3
rake clean apache2
(in /usr/local/lib/ruby/gems/1.8/gems/passenger-2.0.3)
rake aborted!
Could not find Apache Portable Runtime (APR).
/usr/local/lib/ruby/gems/1.8/gems/passenger-2.0.3/rakefile:37
(See full trace by running task with --trace)



The main reason for this is that mod_rails cannot find apr-1-config which should have been installed within (as per my system) /usr/local/apache2/bin. In order to solve the problem, you just need to add the Apache2 custom install bin directory to your user path (as per my system):


export PATH=":/usr/local/apache2/bin:$PATH"


That should do it.

mod_rails and "MACOSX_DEPLOYMENT_TARGET environment variable"


The error you are most likely to get would be close to the following:


g++ -flat_namespace -bundle -undefined dynamic_lookup Utils.o Bucket.o Logging.o System.o Configuration.o Hooks.o mod_passenger.o -fPIC -o mod_passenger.so -lstdc++ -lpthread ../boost/src/libboost_thread.a -L/usr/local/apache2/lib -lapr-1
/usr/bin/ld: flag: -undefined dynamic_lookup can't be used with MACOSX_DEPLOYMENT_TARGET environment variable set to: 10.1
collect2: ld returned 1 exit status
rake aborted!
Command failed with status (1): [g++ -flat_namespace -bundle -undefined dyn...]
/usr/local/lib/ruby/gems/1.8/gems/passenger-2.0.3/rakefile:142
(See full trace by running task with --trace)


In this case, you will have to add the following to your environment variables


export MACOSX_DEPLOYMENT_TARGET=10.4

Wednesday, May 7, 2008

Guido Sohne

Have you ever thought that death would come through email? I just heard the saddest and most shocking news today: a very good friend of mine, Guido Sohne passed away. I hadn't seen him in years since I left Ghana, but every time he came to SA, he'd give me a call and we'd talk about various issues on the phone. He's always told me that I had to learn how to relax and take life as it comes. He had always been a reference point for me, a very unique individual and with whom one could enjoy any kind of discussion.

I still cannot believe he's gone. So long Guido.