Removing Git Tags

Posted: 26th March 2015 by Tim in Git
Tags: , , , , , , , , , , , ,

If you’ve accidentally added a git tag, or if you want to remove old tags, these tags can be removed with the following three commands:

git tag -d <my_tag>
git push origin :<my_tag>
git push --tags

For example, if you want to remove the tag bad_tag, you would use these commands:

git tag -d bad_tag
git push origin :bad_tag
git push --tags

Linux Terminal Clock

Posted: 9th March 2015 by Tim in Bash, Linux
Tags: , , , , , , , , ,

Ever wanted to have a real-time clock on your linux terminal? We can create one with a single line of bash, like so:

while echo -en "$(date)\r"; do sleep 1; done

Let’s look at how this works:

  • date is a common unix tool used to print the current date and time. The $(...) means that the date command is run, and the output is placed here instead. For example, if logged in as root, echo "I am $(whoami)!" is the same as echo "I am root!".
  • echo -en will print the output of $(date). -e allows escaped characters (the \r in this case), and -n means echo will not add a newline character to the end of the line.
  • \r is a carriage return character. This returns the cursor to the beginning of the current line, which means the next thing to print will overwrite anything on that line.
  • while <condition>; do <commands>; done is a standard while loop; <commands> will be run while <condition> returns true (ie: execution is successful).
  • sleep 1 will pause program execution for 1 second.

Altogether, it means we will print the date every second, overwriting the previously printed date, until we end the program (ctrl-c) or until the echo command fails (which is unlikely to happen).

With Docker, you can specify the command to run inside the container on the command line. But what if you want to run multiple commands? You can’t escape the && syntax, or wrap the command in quotes, as Docker won’t recognise it. The trick here is to use

sh -c '<command1 && command2 [&& command3 [...]]>'

For example, to run date and whoami in a vanilla ubuntu container, we would run the following:

$ docker run ubuntu:latest sh -c 'date && whoami'
Wed Feb 18 00:42:53 UTC 2015

This works because sh -c '<date && whoami>' is one call; the commands will be split and executed from within sh.

Listing directories only in linux

Posted: 9th February 2015 by Tim in Linux
Tags: , , , , , ,

The ls command will list files and directories in the current directory. But what if you only want to list the directories? There are a few ways to do this. One of the easiest ways is this:

ls -d */

The -d flag instructs ls to display directories instead of displaying directory contents. The */ instructs ls to perform the listing on subdirectories only. The output will look something like this:

$ ls -d */

Test if a directory is empty in Bash

Posted: 29th January 2015 by Tim in Bash, Linux
Tags: , , , , , ,

Using Bash, there are a number of ways to test if a directory is empty. One of those ways is to use ls -A to list all files, including those starting with . and see if anything is printed. This can be done like so:

if [ ! "$(ls -A <path>)" ]
    echo "<path> is empty!"
    echo "<path> is not empty"

Or inline:

if [ ! "$(ls -A <path> ]; then echo "empty!"; fi

Or, for a slightly less readable version:

test "$(ls -A <path>)" || echo "empty!"

This works because test "" is true, and any other string value is false. If the directory is empty, ls -A will return an empty string.

There are many ways in the linux terminal to print the nth word of a given file or output. One way to do this without worrying about tabs, extra spaces or word length is to use awk. With awk, this can be done on one line by using the {print $<n>} syntax.

For example, the ps command may print this:

$ ps
  PID TTY          TIME CMD
 3677 pts/1    00:00:00 bash
 3699 pts/1    00:00:00 ps
 3700 pts/1    00:00:00 awk

To print only the fourth column (CMD), we can pipe the output to awk like so:

$ ps | awk '{print $4}'

There are a number of ways to print a number with zero-padding (leading zeros), depending on the variable type you are wanting to print. One easy way to add zero padding to any type is to use the str(<number>).zfill(<length>). This will convert any number type to a string before adding the extra zeros. For example:

def zeroPad(number, length):
    return str(number).zfill(length)

This function can be called using many different types. We can use this function like this:

print zeroPad(123, 5)
print zeroPad(12.3, 5)
print zeroPad('123', 10)

to print this:


Windows 8 comes with a disk partition utility, but it’s difficult to find. There are a few ways to run the utility, the easiest being:

Open the windows run prompt (windows key + r), and run diskmgmt.msc

Alternatively, for the graphically inclined, open the control panel and search for partition

To highlight any results found when searching in Vim, you can use :set hlsearch. To turn off the highlighting, use :nohlsearch. If search highlighting is something you always want turned on, you can add set hlsearch (no colon) to your .vimrc file.

If, like me, you like to turn off the search highlighting after you’ve found what you’re looking for, you can map :nohlsearch to one of the F keys. For example adding the following to your .vimrc:

set hlsearch
noremap <silent> <F8> :nohlsearch<CR>

will highlight search results, and remove that highlighting when you press F8. Highlighting will be turned back on when you start your next search. When adding this to the .vimrc, be sure to hit the F8 key instead of typing in “<F8>”, or the shortcut won’t work.

If you have a HyperSQL (HSQL) database stored in a file, it is often useful to be able to query that database from the command line. This can be done using the following command:

hsqldb-sqltool --inlineRc url=jdbc:hsqldb:file:<db_name>,user=<username>,password=[<password>]

By default, user SA with no password will exist for each database file. If the database does not exist, it will be created for you.

Hide grep command from ps output

Posted: 28th October 2014 by Tim in Linux
Tags: , , , ,

When searching for a running process on a *nix machine, it is common to use ps together with grep, like so:

ps -ef | grep vim

This works well enough for quick searches, but will always return the grep command since grep vim will always contain the string “vim”. The pgrep utility can work around this, but if that’s not available you can use this grep trick:

ps -ef | grep [v]im

Putting square brackets around one letter will still instruct grep to match “vim” in the ps output, but the grep command itself will not match since it does not contain this string exactly.

Disabling auto indent in Vim

Posted: 12th October 2014 by Tim in Vim
Tags: , , , , , , ,

Auto indent is disabled by default in Vim, but some systems have this feature enabled in the system-wide vimrc file (found in /usr/share/vim/vimrc or a similar location). There are two ways to disable this: remove the system-wide setting, or remove the setting for your user only.

To remove the setting system-wide, search for and remove or comment out this line in the system-wide vimrc file (the ‘plugin’ word may or may not appear):

filetype plugin indent on

To remove the setting for your user only, add this line to ~/.vimrc:

filetype indent off

You will need to restart your Vim session to pick up the new settings.

HTTP GET request in Python

Posted: 28th September 2014 by Tim in Python
Tags: , , , , , ,

There are a number of ways to make a GET request in Python, but the easiest (in my opinion) is via urllib2. With this library, you can make a request with only one line of code, storing the result for use later.

For example:

import urllib2
data = urllib2.urlopen("").read()
print "Website size (bytes): " + str(len(data))

Will print:

Website size (bytes): 114209

HTML link coloring with CSS

Posted: 12th September 2014 by Tim in CSS, HTML
Tags: , , , , , , , , ,

HTML link colors can be changed easily using CSS. The properties which can be set are:

  • link – a link to a page which has not been visited
  • visited – a visited link
  • hover – a link which has the mouse hovering over it
  • active – a link which is being clicked (mouse button held down)

Each of these properties can be set like any other CSS tag, so to change the color we can use the color tag.

For example, the following CSS:

#coloredlink a:link { color: blue; }
#coloredlink a:visited { color: red; }
#coloredlink a:hover { color: black; }
#coloredlink a:active { color: green; }

with the following HTML:

<div id="coloredlink">
<a href="" target="_blank">LaTeX Tutorial</a>

will produce this link:

Passing function pointers as a parameter to another function can be tedious work. The function pointer definitions can be long and cumbersome to write, and obscure to read. Using pointers to member functions can be even more ambiguous. Fortunately, we can leverage the power of templates to make this work easier for us by making the compiler figure out the function pointer type for us. If we take this a step further, we can pass in both the object and it’s method as templated parameters, effectively allowing us to use the same code for multiple objects and multiple methods.

Consider the following code:

#include <iostream>

struct MyFuncs
    int smallInt() { return 1; }
    unsigned long bigULong() { return 1000; }

class OtherFuncs
    unsigned long aNumber() { return 555; }

template <typename OBJECT, typename FUNC>
long long getNum(OBJECT obj, FUNC getNumber)
    return (obj.*getNumber)();

int main()
    MyFuncs funcs;
    std::cout << "small: " << getNum(funcs, &MyFuncs::smallInt) << std::endl;
    std::cout << "big: " << getNum(funcs, &MyFuncs::bigULong) << std::endl;

    OtherFuncs other;
    std::cout << "other: " << getNum(other, &OtherFuncs::aNumber) << std::endl;

    return 0;

The code above prints the following output:

small: 1
big: 1000
other: 555

This program creates a getNum(...) function which can take any object and that object’s (public) method which takes no arguments and returns a value which can be cast to a long long. If written without templates, we would need to write separate getNum(...) methods for each of the calls in main. Templates allow us to avoid such code duplication while keeping the code manageable.

Creating bar charts with gnuplot

Posted: 11th August 2014 by Tim in Gnuplot
Tags: , , , , ,

Bar charts are very easy to create with gnuplot. Very little setup is required; just a data file with labels in one column and data in another. From here, the graph can be drawn with the following line:

plot <data_file> using <label_column>:xtic(<value_column>) with boxes

For example, the following two files:


set terminal pngcairo font "arial,10" size 500,500
set output 'barchart.png'
set boxwidth 0.75
set style fill solid
set title "Population of Australian cities (millions), as of June 2012"
plot "population.dat" using 2:xtic(1) with boxes


Adelaide    1.277174
Brisbane    2.189878
Canberra    0.374658
Darwin      0.131678
Hobart      0.216959
Melbourne   4.246345
Sydney      4.667283

Will create this graph:

gnuplot bar chart

If you have a JAR file and want to print the details from MANIFEST.MF, this can be done with one command in linux, using the unzip utility. For example:

$ unzip -p /usr/share/java/hsqldb.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Created-By: 1.7.0_03-b147 (Oracle Corporation)
Specification-Title: HSQLDB
Implementation-Title: Standard runtime
Class-Path: /usr/share/java/servlet-api-3.0.jar
Main-Class: org.hsqldb.util.SqlTool
Ant-Version: Apache Ant 1.8.2
Implementation-Vendor: buildd
Implementation-Version: private-2012/07/12-02:29:31
Specification-Vendor: The HSQLDB Development Group

PHP is able to communicate with PostgreSQL databases using some relatively simple calls. In a similar manner to other database systems, the script needs to do the following:

  1. connect to the database using pg_connect
  2. execute queries using pg_query and pg_free_result
  3. close the database connection using pg_close

For example, consider the following script:

// database connection
$dbhost = "localhost";
$dbname = "everyone";
$dbuser = "phptest";
$dbpass = "testpassword";
$db = pg_connect("host=$dbhost dbname=$dbname user=$dbuser password=$dbpass")
    or die("Could not connect to database $dbname on host $dbhost!");

// execute the SQL query
$query = "SELECT lanname, lanpltrusted FROM pg_language;";
$result = pg_query($query)
    or die ("Query failed: " . pg_last_error());

// print the results
echo "<table style=\"width: 500px; border: 1px black solid;\">\n";
echo "\t<tr>\n";
echo "\t\t<th>Language</th>\n";
echo "\t\t<th>Trusted</th>\n";
echo "\t</tr>\n";

while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
    echo "\t<tr>\n";
    echo "\t\t<td>${row['lanname']}</td>\n";
    echo "\t\t<td>${row['lanpltrusted']}</td>\n";
    echo "\t</tr>\n";

echo "</table>\n";

// clean up

This script fetches all languages supported by this PostgreSQL installation, and notes whether it is ‘trusted’ (ie: whether non-superusers can create scripts using that language). The script above will generate the following HTML table:

Language Trusted
internal f
c f
sql t
plpgsql t

Note that this code does not only work for web environments; it can be used for standalone PHP scripts too.

LaTeX style (.sty) files

Posted: 27th June 2014 by Tim in LaTeX
Tags: , , , , , ,

When writing LaTeX documents, you may find yourself copying and pasting some common settings such as margins, fonts and paragraph indentation. This is not only tedious, it can be a real headache if you’re writing multiple documents that you want to look the same. To solve this problem, you can use a style (.sty) file.

A style file uses the same syntax as a LaTeX file, but uses the .sty suffix. To use this file in your LaTeX document, load it using the \usepackage{<filename_without_sty_suffix>} syntax.

Consider the following two files:


% timstyle.sty
% This file contains common document settings

% Page margins (2cm wider, 2cm longer)

% Font (Times New Roman)

% No paragraph indentation


\documentclass[11pt, a4paper]{article}
\usepackage{timstyle} % note: no .sty suffix here
Hello World! This is the first paragraph in the document.
The paragraph is not very long, but it spans multiple lines.
As you can see, the first line of the paragraph is not indented.\\

This is the second paragraph. Look --- still no indentation!

The code above will produce this document. As you can see, the margin, font and paragraph indentation settings are in timstyle.sty, which simplifies the example.tex file. The style file can now be reused in other files too.

Command Line Arguments in Bash

Posted: 14th June 2014 by Tim in Bash, Linux
Tags: , , , , ,

In Bash, arguments passed in on the command line are stored in numbered variables. For example, the first argument is $1, the second argument is $2, and so on. The total number of arguments passed to the program is stored in $#

$0 contains the path to the program. This path may be an absolute path or a relative path, depending on how you called the script. $@ and $* will return all of the arguments passed to the program.

For example:

echo "Execution command: '$0 $@' ($# args)"
echo "First 3 arguments:"
if [ $# -ge 1 ]
    echo "  \$1 = $1"
if [ $# -ge 2 ]
    echo "  \$2 = $2"
if [ $# -ge 3 ]
    echo "  \$3 = $3"

This script will print this if called using a relative path:
Execution command: './ one two three' (3 args)
First 3 arguments:
  $1 = one
  $2 = two
  $3 = three

Or, if called using an absolute path:
Execution command: '/tmp/ ichi ni san' (3 args)
First 3 arguments:
  $1 = ichi
  $2 = ni
  $3 = san

Using tools such as ps or top, you are able to see the processes running on a machine. However, you can’t see the directory from which the process was started. Knowing the working directory can be useful if, for example, you need to move a script or program to stop a fork bomb, if you want to see where a script or program lives or, if a script or program reads files using a relative path, to see which files are being read.

This working directory can be found using the pwdx <pid> [<pid> ...] utility. For example, consider the following output from ps:

everyone  2646     1  2 21:21 ?        00:00:00 terminal
everyone  2651  2646  0 21:21 pts/0    00:00:00 bash

We can see that terminal and bash are running, but we don’t know where these processes were started. Using pwdx, we can easily find out:

$ pwdx 2646 2651
2646: /home/everyone
2651: /home/everyone

Consider the following query (tested on PostgreSQL – some other systems may require a table to be specified):

SELECT 'Yes' AS Value_Returned
WHERE 1 != 2;

This query returns 1 row: ( Value_Returned = 'Yes' ), as one would expect. But what if we compare against NULL?

SELECT 'Yes' AS Value_Returned

0 rows returned, even though 1 is not NULL. This is because of the way logic works for NULLs; <anything> != NULL and <anything> = NULL always return UNKNOWN, which is not TRUE. UNKNOWN AND TRUE equals UNKNOWN, and UNKNOWN AND FALSE equals FALSE.

Similarly, any NOT IN operation using a set containing NULL will never return TRUE. For example:

SELECT 'Yes' as Value_Returned

does not return any rows.

In a C or C++ program, fork() can be used to create a new process, known as a child process. This child is initially a copy of the the parent, but can be used to run a different branch of the program or even execute a completely different program. After forking, child and parent processes run in parallel. Any variables local to the parent process will have been copied for the child process, so updating a variable in one process will not affect the other.

Consider the following example program:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
    printf("--beginning of program\n");

    int counter = 0;
    pid_t pid = fork();

    if (pid == 0)
        // child process
        int i = 0;
        for (; i < 5; ++i)
            printf("child process: counter=%d\n", ++counter);
    else if (pid > 0)
        // parent process
        int j = 0;
        for (; j < 5; ++j)
            printf("parent process: counter=%d\n", ++counter);
        // fork failed
        printf("fork() failed!\n");
        return 1;

    printf("--end of program--\n");

    return 0;

This program declares a counter variable, set to zero, before fork()ing. After the fork call, we have two processes running in parallel, both incrementing their own version of counter. Each process will run to completion and exit. Because the processes run in parallel, we have no way of knowing which will finish first. Running this program will print something similar to what is shown below, though results may vary from one run to the next.

--beginning of program
parent process: counter=1
parent process: counter=2
parent process: counter=3
child process: counter=1
parent process: counter=4
child process: counter=2
parent process: counter=5
child process: counter=3
--end of program--
child process: counter=4
child process: counter=5
--end of program--

C/C++ gotcha – using #if true

Posted: 14th April 2014 by Tim in C, C++
Tags: , , , , , , ,

Consider the following code, which compiles without warnings with both gcc and g++:

#include <stdio.h>

int main(int argc, char **argv)
#if true
    printf("This does what you expect\n");
    printf("This does not do what you expect!\n");

    return 0;

When compiling with g++, the program prints This does what you expect. However, when compiling with gcc, This does not do what you expect!

The problem here is with the #if true statement. In C++, true is a keyword which (unsurprisingly) evaluates to true. However, in C there is no such keyword, so true is just an undefined macro. #if <undefined_macro> will always evaluate to false, hence why the #else block is evaluated instead.

If you’re writing code which is used in both C and C++, use #if 0 or #if 1 instead as this is guaranteed to behave in the same way in both languages.

Adding lyrics to sheet music with Lilypond

Posted: 26th March 2014 by Tim in LilyPond

Lilypond is a useful tool for typesetting music. previously, I explained the basics of how to create sheet music for Mary Had A Little Lamb. This post will explain how to add the lyrics. This post follows on from the previous post, so read that first if you haven’t done so already.

Adding lyrics to your music only requires two extra steps:

1) Write down the lyrics

Lyrics need to be written inside a \lyricmode block. A couple of things to note here:

  • By default, each word is associated with one note. To skip a note, use "".
  • If a word spans multiple notes, split the word on the note boundaries and add -- between them. See the example below.

The lyrics for Mary Had A Little Lamb would look like this:

words = \lyricmode {
    Ma -- ry had a
    lit -- tle lamb
    lit -- tle lamb
    lit -- tle lamb
    Ma -- ry had a
    lit -- tle lamb whose
    fleece was white as snow

In the above, words is the name given to this block of lyrics, which will be used later.

2) Add the lyrics to the score

This can be done with \addlyrics \words where \words is the name given above.

The full document would look like this:

song = \relative c' {
    \clef treble
    \key c \major
    \time 4/4

    e4 d c d e e e2 d4 d d2 e4 e e2
    e4 d c d e e e c d d e d c2 r2

words = \lyricmode
    Ma -- ry had a
    lit -- tle lamb
    lit -- tle lamb
    lit -- tle lamb
    Ma -- ry had a
    lit -- tle lamb whose
    fleece was white as snow

\score {
    \new Staff \song
    \addlyrics \words

which will generate this:

Lilypond lyrics example - Mary Had A Little Lamb