Adding Disqus Comments to Jekyll

TL;DR Adding Disqus comment system to Jekyll site.


Jekyll is great for static site content, but when it comes to dynamic content such as comments, we will have to turn to embed comment system, Disqus for help.


Disqus is an addon that powers discussion threads. For blogs, each discussion thread would represent a blog post, with all the comments under that particular thread.

Go on to Disqus and sign up for an account if you do not already have one. Create your site, add in your site details and all. This site object is where all your threads will be stored.

Login to your dashboard, and navigate to the embedded options there (Admin > Installing Disqus > Universal Code). Disqus provides extensive support for all sorts of platforms. But in our case, we will be using the more generic embed code version.

The code that you have will look something like this:

<div id="disqus_thread"></div>
< script>
var disqus_config = function () { = PAGE_URL; = PAGE_IDENTIFIER;

(function() {var d = document,s = d.createElement('script');s.src = '//';s.setAttribute('data-timestamp', +new Date());(d.head || d.body).appendChild(s);})();

How to use?

Think about where you want your comment thread to be placed in. For me, I would want my Disqus comments to only appear in posts. It does not make sense to have a comment thread appearing on the homepage.

With that in mind, we will be placing the Disqus embed code into our _post.html template in _layouts.

How does the code work? To identify which thread you want to load on that particular page, you define the thread’s id as page.identifier in disqus_config(). So what do we use as the page’s unique identifier? Looking at Jekyll documentation, we can see that would be the ideal id for our Disqus thread.

Now make the appropriate changes to the embed code and paste it into wherever you want your comments to be displyed. Now paste the following code into _layouts/post.html:

<div id="disqus_thread"></div>
< script>
var disqus_config = function () { = "{{ }}";

(function() {var d = document,s = d.createElement('script');s.src = '//';s.setAttribute('data-timestamp', +new Date());(d.head || d.body).appendChild(s);})();

Finishing touches

The final feature that we will add in for this tutorial is the ability to disable comments. To do this we will make use of the front matter YAML that is included in each post.

We will create a new variable nocomment in the post’s front matter(accessible in post.nocomment). If it is not defined, the Disqus thread will be displayed. If the value of page.nocomment is set to true, then the thread will be hidden.

Wrap the disqus thread code with the following Liquid template tags:

{{ "{% unless page.nocomment " }}%}
<div id="disqus_thread"></div>
< script>
var disqus_config = function () { = "{{ }}";

(function() {var d = document,s = d.createElement('script');s.src = '//';s.setAttribute('data-timestamp', +new Date());(d.head || d.body).appendChild(s);})();
{{ "{% endunless " }}%}

The end

Using this technique of including snippets of code into your template, you can greatly extend the functionality of your site. Using this method, you can add in other forms of plugins such as chat and tweet display.


Adding tags and categories to Jekyll

TL;DR Build upon Jekyll’s built-in tag and category tagging system, skip to tutorial

Note Source files are available in this gist


Jekyll is a very good static content generator in all rights and is a pretty good fit for blog posts in general. However, the core is missing a key feature: tags and categories.

Although Jekyll posts support the use of tags and categories, it is up to the theme to implement these features and display them in the layout. This is very annoying, especially when it comes to creating an index for all the tags and categories, since there is no simple way of getting the tag index.

The solution

This tutorial will help you add a generated tag index page to your blog. This page will include all the posts that are of a certain tag (or category), making your blog navigation easier.

This tutorial will focus on create the tag index page for your Jekyll blog. The idea is pretty much the same for categories.

During compilation, the generators that we created will be activated and will then generate the list of posts for the corresponding tag. Then for each tag, they will be parsed into the tag index template page, where the list of posts will be displayed along with the details.

Generating the tag index page

For this to work, there are a few things needs to be created. One, the generator itself. When all the information of the posts have been read into the system, the built in tag system will register the tags to each post in post.tag as a list. We will be creating a generator to create the index page, the plugin will be in the _plugins folder in the root directory as a ruby file.

The plugin will create a TagGenerator object that creates a new ‘TagIndex’ page for each of the existing tags. The TagIndex page uses a different template file(_layouts/tag_index.html). How the posts are displayed is defined in the template file later. This plugin file will reside in _plugins/_tag_gen.rb.

The content of the template file for the tag index will include a main for loop that loops through the list of posts, and print out the details of the post individually. Below is a simple example of a tag index page, with minimal details and styling. This template file will reside in _layout/tag_index.html.

And to add the finishing touches, we add the links to the tag index page to the posts themeselves. This will have to depend on how you define the permalink for your tags. For each tag, you just have to add link to the index page. For a simple list of tags separated by commas, you can add in something like this in your post template.

Testing it out

Now when you build your Jekyll site, and go on to the individual post page, you will be able to access the tag index page and see all the posts that are tagged with that particular tag.

What about categories then? Using the same idea, create your category generator and your category index page. Most of the changes would probably be just to rename the variables in the generator and index page. If you need help, you can view the appropriate files under _cat_gen.rb and cat_index.html under the gist to view the changes to make.

The End?

The Jekyll static site generator is actually very extensible and has support for a very extensive plugin system. In this tutorial, we have only used the generators, but if you interested in building more plugins for Jekyll, you can take a look at official plugin documentation.

Redirecting GitHub Page to a custom domain

Note: This tutorial requires you to have a domain. If you don’t already have one, you might not be able to really try this out for yourself. But still, this tutorial will make a good read 🙂

TLDR: Skip the explanation and go straight to the steps

The reason why I chose Github Pages is because of my extensive usuage of Github in general for project hosting. Using GitHub Pages fits into my workflow. Have the content ready, push it to GitHub, and it will be deployed to GitHub Pages.

Plus, using GitHub Pages means that you can take advantage of the Jekyll generator. You can focus on your content, push it to GitHub, and it will be “compiled” automatically.

I have plans to migrate my blog to my github account. If everything goes well, you can expect a tutorial on how to setup a blog on there, complete with google analytics and all that.

Setting up a page on github

Each account on GitHub will be allowed one subdomain in the following format: If you already have your content ready on that repository, you can skip this section. If you have no idea what I am talking about, read on.

Create a new repository, then go on to the “settings” tabs of your repository.

Note: Your new repository must have the following name: [username], where [username] is your GitHub handler.

Scroll all the way down to the section where it says “GitHub Pages”. Go on and “launch automatic page generator”. This generator lets you edit the information to your page. Choose a nice layout and save the changes.

What you have just done is to create a new branch master in your respository and populate it with the generated page. If you go on and see the files available (in the “code” tab), you will see the index.html sitting there, waiting to be shown to the world.

Basics of DNS settings

If covered in detail, this section can take a whole posts by itself. Instead, I am going to just cover a simple version of it, covering what we will be using in this post.

Types of domains

Before that, let’s cover the few types of domain that GitHub supports. The first type would be apex domain. This is the “main” domain. Examples of such domains would be,, These are one level below the top-level domain (.com, .org, etc).

Then we have subdomains. These are one level down the apex domains, and are usually used to split up your sites into different parts. Examples would include, (see GitHub uses subdomains too).

DNS Record types

There are a few different types of DNS records. These records will point to different resources, then your request will be passed from one resource to another and finally be resolved to an IP address.

Here, I cover the A record and CNAME record, which is used in pointing your domain to a certain resource online. No idea what I am talking about? Read on.

A Record

An A (address) record directs the hostname to a certain IP address. For example, you could have point to your home computer and serve files out of there. Let’s assume your home computer has the IP address Your record will look something like this:

Name/Host   Type    Value   A

Note that in the host section, there is a trailing .. It refers to the top level domain. But for the IP address, there isn’t any top level domain to resolve, hence, there is no need for the trailing ..

CNAME Record

The second type of record CNAME (canonical name), is also known as the alias. This allows you to point different subdomains to different parts of the web. Unlike the A record, the CNAME need not be an IP address, it can point to a domain or a subdomain.

The request will follow the resource that the records points to and continue to resolve the request from there.

Name/Host   Type    Value
www         CNAME   @

This CNAME record redirects the www subdomain to the apex domain (the @ symbol is a shortcut many hosting use to refer to the apex domain). So when you go to, it will be resolved to

Changing the settings

Go your GitHub respository, go to “Settings > GitHub Pages”. Let’s say your domain is Change your “Custom Domain” to

Now login to your GoDaddy account, and navigate to “Domains > Manage DNS”. You will be brought to a table of records. There will be some of the default record there already. You will see a few A records, some CNAME records, and some MX and NS records (not important for now).

Create a new CNAME record with www as the name. Now put in your github pages link as the value. So your record will look something like this.

Host/Name   Type    Value
www         CNAME   <username>

Note: If you already have a www CNAME record, you can edit it to point to your GitHub Page.

Check if it is working

For those who are used to setting up network, working with DNS, you will probably be familiar with “dig” (DNS information groper). For those of you starting out, there is an online version that you can use to check your settings.

Now go onto the page and under the “domain name” textfield, enter your www subdomain (eg. Perform the query and wait for a while. If everything works, you will see a list of addresses, similiar to the following list:


If you want a more verbose query with more information you can choose to uncheck the “short” checkbox.

What does the list mean? When you visit, it resolves to That is what the first line represent. So the list is basically a “path” of what the request went through, finally arriving at GitHub Page’s IP address:

Try this instead

What about apex domain? Didn’t you mention it before? What about the A record that you mention earlier?

Run the verbose DIG query (without the “short” selected) on your domain. If everything is working well, you will notice the last line of the records (the end of the “path”) is actually an A record.

What this actually means is that when everything is finally resolved, the final IP address that your points to is that

What if you want your to point to an IP address too? What if you want to setup your github pages with an apex domain?

Changes these settings

First go over to GoDaddy DNS management portal. Add 2 A entries into the table. Link them to and respectively. These are the IP addresses for GitHub Pages server. Your table will now look something like this:

Name/Host   Type    Value
@           A
@           A

The @ symbol represent the apex domain (eg., without any subdomain. The following setting will redirect the apex domain ( to your GitHub Page.

If you want to resolve a subdomain to your GitHub page, you can do so by changing the “Name/Host” to whatever subdomain you want. (changing it to blog will result in resolving to your GitHub page.

If you need help, you can refer to the official help page.

Checking that it works

Use the DIG tool that I told you just down. Query your own domain, you should see a list like this:

These IP addresses represent the A records that your domain has been pointed to.


There are many different kind of records that DNS server use to help resolve different requests. This posts only cover a few of those. If you want to learn more you can take a look here to see what’s the difference between the varying types of records.

GoDaddy uses A records, but other hosting platforms might use different kinds of DNS records such as ALIAS or ANAME. To learn more about setting up GitHub Pages on those hosting sites, you can take a look at GitHub’s own help page.

Css Tip – Css Browser Selector

Styling sites for different browsers have always been a headache for front end developers. Sometimes, the implementation has its own prefixes, sometimes the model doesn’t work at all.

Browser specific stylesheets

So developers came up with the idea of browser specific stylesheets. For each different browser, you redefine a few style declarations to make the layout and styling work.

But having multiple stylesheets is far from optimal. You take more effort to organize your files, some browsers have quirks that needs some fixing, and all sorts of weird problem pops up. And that adds up to a lot of time wasted.


One more elegant solution will be to borrow the idea of browser prefixing. Instead of having multiple stylesheets, you now have one stylesheet with all the fixes that you can apply.

Even better, using this method allows you to extract other details like browser versions and operating systems. This way, you can target differrent content at different platforms and still have a static one-page website.

How it works

This is a script from Rafael Lima. The basic idea is to extract information from the userAgent string and apply the appropriate classes to the document element.

And when defining the style declarations, you just have to use the appropriate classes to fix the different cross browser errors.

Access the script from here


This way of frontend development focuses on limiting server side interaction. Sending all the information to the client and let all the decision to be done over the client side.

All methods have their pros and cons. This method will be suitable for simple sites that require simple static content. If you are working on a site with dynamic content, handling the browser fixes server-side could be an appropriate choice, since its just a simple extension and can help reduce page load time.

If there is any questions or queries, leave a comment or drop me an email.

How I learnt basic morse in 3 days

In cheaper by the dozen, it was mentioned in one of the childhood stories that her father managed to teach morse to kids over a short span of an holiday.

Then I thought to myself, considering my age and my access to technology, I could probably be able to do it in a week, could I?

Starting with the trick

The method used in the story was to use phrases to help memorize the dots and dashes of the alphabets, using the emphasis of certain syllabus as hints.

The first few of the alphabets were given in the book, I went online and googled the rest. I settled on this list that I found on wikipedia.

I read through them a few times. It wasn’t really to memmorize it, more of trying to get the phrases in my head.

Testing it out

Armed with the knowledge, I went online to search for a morse training app. You could probably download any of them, I think it doesn’t really make much difference if the funtionalities are the same.

I downloaded the morse trainer, and tried out the transmission mode. I tried to transmit some words, I couldn’t really get the hang of it, I was too slow, the pause makes the app thinks that I am between words, I couldn’t continue.

Getting hang of tapping morse

This isn’t the way to go. I went on to the freepad mode and tried to enter some words. There was a guide in the app. Apparently, between letters the pause should be the length of a dot, and between words, the length of a dash.

I practice really hard. And after a while, I got the hang of it. The trick was to type the letters and say it out at the same time. Somehow, you will insert that pause automatically. But lets say you are pausing too long and the spaces keeps appearing, You can try saying out the letter faster. Similiarly, if your tapping are all jumbled up, you can slow down the recitation to get the right speed.

How do I push this to the extreme? When practicing in the word mode, I switched off the sound and looked away while tapping out the code. I find that this helps me grasp the momentum better as I learn not to rely on the use of audio and visual feedback.

Memorising the alphabets

It finally the main part. I still remember my first word – “elements”. When I was training the tapping, I wrote out this word in morse (with the appropriate spaces) and tried tapping it out. After trying out for really long, I found that I memorise morse best in the visual form.

What do I mean visual form? It means that I memorize the alphabets in blocks. Take “L” for example. Initially, I used the phrase method, so I have got “he LOST his lid”, which translate to “._..”.

After a while I realized that when I actually tried to recall “L”, the block of dots and dashes came to me really quickly. So when I got “L”, the image “._..” just came very quickly to me. For me that seemed like a shortcut.

This works for the more common letters such as “E”, “T”, “L”, “Y”, etc. Interesting these patterns are opposite pairs, which means that exchanging dots for dashes, you get “T” from “E” and “Y” from “L”. Maybe that’s why it was easier for me to imagine it as blocks.

For the rest, I still use the phrases. For example, “G” for “GOO GLE ad”, “V” for “vic to ry Vee”. These are the less common letters, so the phrase still prove to be a great help, especially if the phrase jumps up to you very quickly. (tip: choose a weird and memorable phrase)

But after tapping morse for a long time, I suspect that it will be very easy to imagine the letters of blocks of dots and dashes. Take “R” for example. I learnt it as “ro TA tion”, but now when I encounter it in my tapping, the block of “._.” jumps up to me immediately.


After 2 days of practicing, I am proud to say that I have some basic mastery of morse code. Without refering to any sheet of information, I can type out the words with relative accuracy (except for the occasional pausing too long problems) without any form of feedback (audio or visual).

I took 10 tries to tap out 10 words
score for morse tapping

Now that I am suffuciently capable of transmitting morse, I will be moving on to receiving morse and decoding it in real time. The practice mode in the app does not really provide a very good practice (I feel), as it does not use real words. I will find another way to hone my morse receiving skills before reporting any results.


Over the short span of 3 days, I have learnt to transmit morse. That might be long for some people, but I feel that being able to reach such level of efficiency is rather commendable.

But to be fair, I had a lot of time to practice, and didn’t have much other things to distract me from my learning.

So, if you are wondering if you can spend a weekend learning morse, no worries, start today and you will be tapping morse in no time.

Css Tip – Using flexbox to style a button

When you try to use flexbox in a button, it doesn’t render as it is supposed to , why is this so, and how do I fix this?


The flexbox model is one of the up and coming standards for web design. Once you have mastered it, you can use it for any design you want.

You would expect that it should work on different HTML elements as well, but when you try to apply the model to a button and render it in Firefox, it just wouldn’t render properly. (click on caption to view codepen)

How it appears
how it looks like

How it is supposed to look like
how it supposed to look

As a good developer ensuring cross browser compatibility, this problem annoys me to no end.

Solution (inline block)

In the particular example above where we try to style the button, we could render the image and text as inline block. In that case, the image and text will align side by side.

But using this method, you won’t be able to easily get the image and text to align vertically (unless you use some margin or valign hack, which complicate stuff).

The more generic method

I didn’t believe it could work until I tried it out, the solution seems too simple. Apparently, by wrapping the button’s content with a “div” element, you can render the flexbox properly without any problems.

This way, you can still use flexbox for all your layout needs. But do note that having a content wrapper means that you have to remember to remove the background and border of your button to get the look that you want.

Why didn’t it work originally?

It all boils down to how the button is implemented in Firefox. For special elements, like buttons and form inputs, its safer to assume that structured differently across browsers.

This is because these special elements have unique responses that the browser have to take into consideration, so they are often rendered differently cross browser.

If you are searching for a more technical answer, you can use this thread as a starting point.

Any questions or issues, you can leave a comment here, or direct your query to my email.

Explaining 2016 Codejam round 1A

This post is going to explain how I got my answers for codejam round 1A. Hopefully, I will be able to continue writing these posts as the 2016 codejam competition furthers. But that have to depend on whether I will be able to answer the questions.

Yes, I know that Google does provide its own question analysis (it’s available here). So why do I write it, repeat it again?

Google’s answers are writtne by expert coders who have a wealth of experience writing algorithms, thinking of solutions. Most that are stuck on the problem are probably not. The little hints given might not be sufficient, hence, the tutorial.

Also partly for myself, in case I have forgotten how to solve it have couldn’t understand the analysis by Google.

Problem A

This problem is a very simple “step-by-step” problem, as long as you can figure out the method of generating the string, you can get the answer by adding characters to the string one by one.

The method goes like this: to get the largest possible string (alphabetically), process the characters one by one, if the character is larger than the character at the start of the answer, add it to the front, if not, add it to the back.

There really is not much in this, it is a pattern questions, as long as you can figure it out, the solution is easy to write.

Submission for small input

N = input()
for n in range(N):
    chars = raw_input()

    ans = chars[0]
    chars = chars[1:]

    for c in chars:
        if c>=ans[0]:
            ans = c+ans
            ans += c

    print 'Case #%d: %s'%(n+1, ans)

Problem B

The second problem is actually very simple, but it is the question where I found that I am deeply dissapointed in myself. This is the problem where you have to determine the values of a missing row from a grid.

When I first started on the problem, I jumped in immediately and started working on the algorithm to find the correct order of the grid from the different pieces of information. But there was one part I overlooked — because of a few rules that are placed in the problem, there is a much much simpler answer to it.

This is the key rule: “all the row and columns must be in ascending order, from left to right, from top to bottom, with no repetition in each row or column”. From this rule, we can use the existing information from the grid to determine the missing numbers and the order it is in.

When you are in a grid, and you are required to record the sequence of the rows and columns, there a case of double counting, where each person is counted exactly twice. Since only one strip (either row or column) is missing, whatever number only appears an odd number of times, must be one of the missing number.

What if one of the row/columns have two of the same number? Doesn’t that mean that there will be an even number of occurance for that value? Well, that’s covered by the rules, “there is not repeated number in each row”.

What if we got the numbers, how do we arrange them? No problem, it’s also covered by the rules — “all sequences of the rows and columns must be in ascending order”.

success for small input

T = input()
for t in range(T):
    N = input()

    all = []
    for n in range(N*2 - 1):
        all += map(int, raw_input().strip().split())

    line = []
    for i in set(all):
        if all.count(i)%2: line.append(i)

    s = ' '.join(map(str, sorted(line)))
    print 'Case #%d: %s'%(t+1, s)

Problem C

This is one of the more classical problems, using graph as a model for the problem. To do this question, we will have to refer to a diagram for explaination. This is the diagram taken from Google’s codejam answer.

graph diagram

Try drawing a few graphs on your own. And you probably see how the friendship circle will work out. As explained in the analysis, the way to form the longest chain of amiable students sitting together is to make use of the students who mutually like each other.

But if the chain using the mutual liking students are too short, the only are option in forming a circle is to find the cycle with the longest cycle length. (eg. biggest loop), like in the first example.

So there is 2 parts to the solution. One, find the cycles in the graph. Two, Find the longest tail from the cycles with length of 2, 2 kids liking each other, then add up all of them together to form one big circle (just like in the picture, with the 2nd and 3rd part combined).

Okay, my solution for finding all the cycles in the graph might not be the most efficient, but it is definitely a method that works, and it works well within the time limit.

As for the second part when we need to find the tail, it is a depth first search for the longest link. Don’t get it? Basically we follow the data and start tracking back each chain, starting of the kid in the length-2 cycle. We will try all the combinations and then return the length of the tail which goes the deepest.


# current, data, not-to-be-counted
def longest(current, data, nocount): 
    nodes = [n for n in data[current[-1]] if nnocount]    
    if not nodes:
        return current

    max_line = []
    for n in nodes:
        temp = longest(current+[n], data, nocount)
        if len(max_line)<len(temp):
            max_line = temp
    return max_line

T = input()
for t in range(T):
    N = input()
    d = [int(i)-1 for i in raw_input().split()]

    c2 = []

    # normal cycle counting
    c_max = 0
    mv = range(N)
    while mv:
        c = [mv[0]]
        mv = mv[1:]

        while len(c)1][0]
        idx = c.index(start)
        c_len = c.index(start) - idx + 1

        if c_max  m: m= c_max

    print 'Case #%d: %d'%(t+1, m)


The problems are solvable, but I do need sometime to write the solution and really think about the edge cases. I hope that 1B will be more lenient (although it is unlikely). And if I do understand and manage to get a solution, I will share them again when I get the writeup written.