How I set up Pelican for blogging pt. 1

No, this blog still uses WordPress (now Hugo!) because of its convenvience and ease of use. But I needed a way to document my personal server that I use for Mumble, IRC and my small projects and I decided to test out static blog generators for that.

Normally people use Octopress (based on Jekyll) which labels itself as “A blogging framework for hackers” which is cool and all but I really don’t like Ruby and I had heard a lot of good stuff about Pelican so I went with that.

This post merely describes what’s different in my own approach and isn’t very detailed in itself, for a better tutorial in setting things up I recommend the documentation pages on how to get started.

Installing Pelican was a breeze, running sudo pip install pelican markdown installs both Pelican and the required packages to write in Markdown (normally you do this in a virtual environment but since I normally don’t work in Python this isn’t a concern for me). Following this up with pelican-quickstart generates a good basic template for getting started in the current directory.

I set up my blog in ~/Projects/Pelican and instead of using the make tools included with the quickstart package I set up my own alias in .bash_aliases like so echo "alias blog='pelican ~/Blog -o ~/Projects/Pelican/web -s ~/Projects/Pelican/pelicanconf.py'" >> ~/.bash_aliases. This allows me to write my blog posts in the “Blog” folder in my home directory and then just call blog to re-generate the blog when I’m done.

Of course this requires me to create a virtual host in Nginx that points to the output folder, but I prefer this over running a dedicated Python server since it allows for some better caching options as well as better performance and less resource hogging on the server.

On two factor authentication

I’m studying computer security this term and it has a way of making you very paranoid about security matters, and recent articles like this and this really doesn’t help either. Therefore I’ve decided to set up two-factor authentication everywhere possible to help protect myself to some degree for the uselessness of passwords.

Two-factor authentication essentially means that you use two authentication factors to log in instead of only one. An authentication factor is one of three things, something you know, something you have or something you are. A password is a good example of the first, while a card or cell phone is in the second category.

What this means is that for someone to hijack one of my accounts they will not only need to know my password but they also need my cell phone to generate a temporary one-time key to log in. While my phone can also be remotely tracked and locked down in case it’s stolen, and through backed up recovery keys I will still be able to access my accounts.

It might sound complex and difficult but it really isn’t, and the major security gain is a worthwhile trade off. To enable two-factor authentication you merely have to download an app (like Google Authenticator or Authy), use it to scan a QR code for the account you want secured and then you’re done. The next time you log in on a new computer you open your app, get a key to type in and you’re logged in as usual.

There’s also fairly comprehensive list of services which support two-factor auth.

On Vagrant

Vagrant enables a developer to isolate their project to a dedicated virtual machine while still coding in the same environment they use for other projects. You can essentially edit your project files in Windows and access the result through Windows while everything is running on Linux without having to do any of the tedious work of setting up and installing a virtual machine.

The cool thing about Vagrant is how the configuration file for the project can be redistributed with the rest of the code base to give other developers access to an exact replica of the original development environment.

The really cool thing about Vagrant is how ridiculously easy it is, they have a guide for setting up a first project which takes about 30 minutes to complete and goes over all the aspects of setting everything up.

The major thing that bothers me is that it’s somewhat slow, a virtual machine has a huge overhead compared to running directly on the host machine. It also takes about fifteen minutes to set up a Vagrant box the first time, which is actually negligent compared to the many hours it would take to do it manually but still feels like a long time.

Provisioning could also have been made simpler, but there are a lot of alternatives and even more examples for setting up any imaginable environment so it isn’t really a problem per se.

Fucking sudo

I stumbled across this comment a while ago and though it was pretty funny, so I wrote a basic one liner to add the “feature” to my shell. Basically what it does is allowing you to write “fucking” instead of “sudo” for the humorous effect of it, example below.

$ make install  
No.  
$ fucking make install

Here’s the code for setting it up. The specified configuration file needs to be changed for it to work in other shells than bash.

$ echo "alias fucking='sudo'" >> ~/.bashrc && . ~/.bashrc

Automatically setting height of textarea to height of its contents on page load

jQuery makes everything so ridiculously simple. To make sure a textarea is automatically resized so it fits its content one could calculate the amount of rows of text and the approximate height of the font and set the height of the textarea to the product of that. Or you could set the height to the scroll size with jQuery and JavaScript.

<script>
    $(function() {
         $('textarea').height($('textarea').prop('scrollHeight'));
    });
</script>

Admittedly, it’s not a complete solution if you need it on a page with more than one textarea though. Then it goes from a one-liner to a three-liner.

<script>
    $(function() {
        $('textarea').each(function() {
            $(this).height($(this).prop('scrollHeight'));
        });
    });
</script>

Is [language] worth learning?

This is a really short response to a question I’ve stumbled across twice today, “Is [language] worth learning?” All languages have some worth, but they are all good in different areas. It all depends on what you want to do and how much you want to learn about programming.

C is very good if you want to learn how computers work without delving into the inaccessible mess that is assembly programming. However, it takes quite a bit of effort and understanding to do a lot with C.

Java is a good choice if you want to get into computer science and work with algorithms and data structures since the language has a lot of support for this in its standard library. However, I think the language is quite boring and doesn’t leave much room to quickly hack together things.

Python is probably the best balance between accessibility for beginners and features for more complex projects. It’s also multi-paradigm which means it supports several different programming methods. If someone is just starting out with programming, Python is almost probably the way to go and Learn Python the Hard Way is probably the best way to learn the language.

How to put checkboxes in Bootstrap dropdowns

Bootstrap is an extremely useful set of tools which, I personally believe, everyone should know about and use for their own internal projects. It’s ridiculous what a time saver it is, especially combined with Font Awesome to get over 360 free, scalable icons to use with Bootstrap.

Bootstrap also have these amazing JavaScript tools which, for instance, allows you to place a dropdown menu on virtually any element. The only problem with these are that you can’t really put forms in them, since the dropdown closes when you click on it. So I looked over Stack Overflow and Google and found all sorts of elaborate solutions to it, some where pretty good, others not so much.

However, they were all very involved to set up and configure, and was generally a lot more than I needed so I was hesitant to implementing them and looked a bit more until I stumbled across an issue on GitHub where someone proposed a better solution.

So I added their JavaScript and some padding, and a scrollbar through CSS for appearances and got a very simple but still solid solution to my problem. I uploaded my final result to JSFiddle (http://jsfiddle.net/VEKYN/). It’s amazing how much time and effort you can save by just looking a little bit more at what’s already available.

An alternative for SQL pagination

I was reading up on improving the performance on MySQL when I found an article and stumbled on a really cool alternative to using offset when generating pagination results from the database.

On the query side, instead of using LIMIT with offset, you can select one more row than you need, and when the user clicks the “next page” link, you can designate that final row as the starting point for the next set of results. For example, if the user viewed a page with rows 101 through 120, you would select row 121 as well; to render the next page, you’d query the server for rows greater than or equal to 121, limit 21.

Source: http://www.infoworld.com/d/data-management/10-essential-performance-tips-mysql-192815?page=0,1

Building a template engine in PHP

Possibly the most common sign of bad code is tight coupling, especially between logic and presentation. It might seem like a good idea to print out the HTML while the data is being generated, but it more often than not leads to a big incoherent mess of tangled code. It also causes other issues, like what happens if an unexpected error occurs in the middle of the page? By then half the page has already been outputted and it might be too late to handle the error nicely.

There are a lot of problems with mixing logic and presentation, but it’s actually very easily solved, especially in PHP. While PHP makes it unnecessarily easy to write shitty code it also provides a lot of ways to avoid it. I’ll use this post to show you how ridiculously easy it is to create a template engine in PHP in three easy steps.

So, we begin by setting up a simple class to wrap our template. The $template variable passed in the constructor is the relative path to our template, e.g. if the templates are in a folder called “views” you should pass “views/.php” to the constructor.

class Template
{
    protected $template;

    public function __construct($template)
    {
        $this->template = $template;
    }
}

Then we add variables to it, we use magic getters and setters for this to make handling of our template a little more verbose, but you can of course use regular getters and setters if you prefer that.

class Template
{
    protected $template;
    protected $variables = array();

    public function __construct($template)
    {
        $this->template = $template;
    }

    public function __get($key)
    {
        return $this->variables[$key];
    }

    public function __set($key, $value)
    {
        $this->variables[$key] = $value;
    }
}

Lastly we add the printing of the template, this abuses some pieces of PHP’s functionality. Partly that code can be included anywhere and that all the output can be stored and loaded into variables. We load all created variables into the functions variable scope with extract(), this has the nice side effect of not conflicting with variables created outside the function and limiting the template file’s access to variables created in the template. Also, by using chdir() before including the file, we change the working directory to the specified template directory (if any). This allows for including other templates within templates without having to concern ourselves with where the template will be loaded from.

public function __toString()
{
    extract($this->variables);
    chdir(dirname($this->template));
    ob_start();

    include basename($this->template);

    return ob_get_clean();
}

We can then use it anywhere we want like this. Of course, if you actually need functionality like this you might have more use for a template engine like Twig, which is a bit more extensible and comes with a ton of cool features.

$view = new Template("path/to/template.php");

$view->title = "Hello world!";
$view->description = "This is a ridiculously simple template";

echo $view;

Bear riddle

I love riddles, this is probably my favorite one since it seems very irrational but is pretty easily solved by logical deduction. Can you solve it?

A bear walks one mile south, one mile east and one mile north and is then back at its original position.

What color is the bear?