Automatically creating footnotes when referencing Multimarkdown glossary entries

Multimarkdown has a feature to add glossary entries when compiling to LaTeX, and it looks like this:

[^glossaryentry]: glossary: term
    The actual definition belongs on a new line, and can continue on
    just as other footnotes.

And to reference a glossary entry created that way, you can use:

This is some text. [^glossaryentry]

Which, in LaTeX, renders to

This is some text. \glsadd{term}

Unfortunately, \glsadd does not add any indication in the text where it is invoked, and there is not (easy) way to change the Multimarkdown behavior to use, \gls instead of \glsadd, for example.

The workaround I devised for this problem is that I overwrote the \glsadd command.

First: Caveats

In my case the created footnote markers (the small numbers added inline) linked to the first page of the document instead of linking to the actual footnote, and I wasn’t able to find out why. I “fixed” this problem by disabling links for footnotes entirely by using the hyperfootnotes=false for the hyperref package, as explained here.

The Code

% Rewrite glsadd so that it also creates a footnote
% We do this so that the glossary references created by Multimarkdown
% (which uses \glsadd) also generate a footnote (didn’t want to hack mmd)

% This copies the old \glsadd command to \Oldglsadd, so that we can invoke it in our new command
% http://www-h.eng.cam.ac.uk/help/tpl/textprocessing/extending_latex.html#Commands
\let\Oldglsadd\glsadd

% Create the new \glsadd command
\renewcommand{\glsadd}[1]{%
    \footnote{\textbf{\gls{#1}}: \glsentrydesc{#1}}     % Create the footnote
    \Oldglsadd{#1}%                                     % Call the old glsadd to add the reference
}

If you insert this snippet into your LaTeX preamble, all you Multimarkdown generated glossary entries will also appear as footnotes on the page where they are referenced.

Hope this saves you some time, because it took me a solid hour to figure this out…

The Class#inherited method in Ruby

For the impatient:

[Class#inherited is a] Callback invoked whenever a subclass of the current class is – ApiDock


The long story: Today I stumbled over a piece of code like the following:

class Foo
  class << self
    def inherited(subclass)
      $subclasses << subclass
    end
  end
end

The interesting thing is that this was the only occurrence of inherited in the entire codebase, so I instantly assumed some Ruby magic and went over to RubyDoc, but didn’t find anything there. After some additional Googling I found a mailing list post which confirmed that inherited is a method on Class, but it still didn’t explain why it didn’t show up on RubyDoc.

It turned out that apparently RubyDoc only shows public methods, which IMO is pretty confusing (at least it was for me). I finally found my missing method on ApiDock, which does show private methods.

Removing trailing spaces in your code with Mow.py

As I had become more and more annoyed by the fact that there was no nice and easy way to trim trailing spaces from my source code, I’ve written “Mow.py“, a convenience Python script that makes it as easy as git mow (or if you’re not a git user mow -r) to get rid of those nasty spaces.

Check it out over at GitHub :)

Enabling HTTPS in Apache results in 403 Forbidden in Internet Explorer

After enabling HTTPS for a certain VHOST (within MAMP, but that is probably not relevant), Internet Explorer 8 started denying to display any HTTPS enabled page, showing a 403 Forbidden error instead. This problem occurred because of the following setting in my Apache configuration:

# Don’t accept connections from non-SNI clients disabled
SSLStrictSNIVHostCheck on

Apparently IE8 doesn’t support Server Name Indication (I’m using version 8.0.6001.18702), even though it should

Long story short, disabling the option solved my problem. This was on my local development system, so I’m not worried about the security implications, but I’d like to know them anyway, so if anybody knows, please leave comment :)

Notes with pdf-presenter-console and latex beamer

I’m giving a talk soon and I thought it is a good idea to make the slides with latex beamer. Fair enough the slides were made quickly and everything was set.

After a while I found a good presentation tool named pdf-presenter-console which is written in Vala and just fits my needs, except for the lack of a method for displaying notes on your slides. It uses one screen displaying the current and the next slide as well as the elapsed time and the other screen for the current slide in full screen for the audience. What I wanted was, that the presenter screen, that is the one with the information for the presenter (me), displaying the slides with notes.

The code base of pdf-presenter-console allows a very quick change so that one can pass another PDF file to the presenter than to the presentation. Now what I needed was a way to include the notes in my slides.

As I found out, latex beamer supports notes but displays them on a separate slide using a more or less ugly theme. Using pgfpages and a simple .sty file I got a workaround for that. I created a new direction for the two screen pgf layout based on bottom and changed the dimension in a way that both pages overlap. In the .tex file I only had to use it and to make the notes template a bit more usable.

nemonotes.sty:

\RequirePackage{pgfpages}

% Page layout which lays the second page over the first
\define@key{pgfpagesuselayoutoption}{second notes bottom}[]%
{%
\def\pgfpageoptionfirstcenter{\pgfpoint{.5\paperwidth}{.5\paperheight}}%
\def\pgfpageoptionsecondcenter{\pgfpoint{.5\paperwidth}{.5\paperheight}}%
\def\pgfpageoptiontwoheight{\paperheight}%
\def\pgfpageoptiontwowidth{\paperwidth}%
}

in the .tex file:

\usepackage{pgfpages}
\usepackage{nemonotes}

% Use slide with red box + notes for notes
\setbeamertemplate{note page}{
    \vspace{.9\textheight} % skip 90% of the page

    \colorbox{red}%
    {%
        \parbox{\textwidth}{%
            \textbf{Notes:}%
            \insertnote%
        }%
    }%
}

% Itemize for notes with little spacing
\newenvironment{nitemize}{
\begin{itemize}
    \setlength{\itemsep}{1pt}
    \setlength{\parskip}{0pt}
    \setlength{\parsep}{0pt}
}{\end{itemize}}

% Enable this to have notes in your slides!
\setbeameroption{show notes on second screen=notes bottom}

Usage example:

\begin{frame}
    \frametitle{Test}

    \note{
        \begin{nitemize}
            \item Foo
            \item Bar
        \end{nitemize}
    }
\end{frame}

pdf presenter console usage example:

$ pdf_presenter_console slides.pdf slides_notes.pdf

To use this, copy the .sty content in your texmf path and add the .tex file content to your tex file.

The necessary changes for pdf-presenter-console are available at my github repository (#d24056)

LaTeX: Checking if a macro is (un-)defined

When I started coding some LaTeX templates for myself, I had a very hard time figuring out how to check if some macro is defined or not. I tried lots of different solutions, and none of them seemed to do what I want (or anything, for that matter). I ended up using ifundef from the etoolbox package:

\usepackage{etoolbox}

\ifundef{\somemacro}{
    \newcommand{\somemacro}{default value}
}{ \relax
} % else: do nothing

Hope this saves you some time ;)

ERROR 2006 (HY000) at line ####: MySQL server has gone away

One of those very helpful error messages. I got this error when importing a large database, and it was caused by some insert statements exceeding the configured max_allowed_packet size (manual). According to this bug entry, the error message should actually say

Got a packet bigger than 'max_allowed_packet' bytes

but that doesn’t seem to fixed to this day. To fix the error, simply increase max_allowed_packet in your my.cnf file, under the [mysqld] section, e.g.

[mysqld]
max_allowed_packet = 16M

C/C++: Fill variables using a single value

A more or less interesting C/C++ problem occured to me this day:

How do I initialize an integer with one part without using shifts. For example you have 0xFF and you want 0xFFFFFF.

Normally you would do something like this

int x = 0xFF << 16 | 0xFF << 8 | 0xFF

But how does it work without this runtime computation? And does it help you increase your performance? Of course not, but we'll see.

One could use arrays:

#define FILL(x,t) *(t*)(const unsigned char[]){x,x,x,0}

int main() {
    int foo = FILL(0xFF, int);

    return 0;
}

This would convert to the following assembly (64bit code):

.main
    …
    subq    $16, %rsp       ! reserve space for rbp and foo
    movl    $._6, %eax      ! load address of ._6 (our static array)
    movl    (%rax), %eax    ! dereference rax and save value in eax
    movl    %eax, -4(%rbp)  ! save value of eax in `foo`
    …

._6:
    .byte    -1
    .byte    -1
    .byte    -1
    .byte    0

If you're wondering why there is -1 and not 255 at the .byte directive, the number stands for 0b11111111 whereas -2 would stand for 0b11111110 and so on.

Comparsion to naive solution

The naive solution:

int foo = 0xFF << 16 | 0xFF << 8 | 0xFF

Compiles to the following assembly (64bit again):

.main:
    …
    subq    $16, %rsp
    movl    $16777215, -4(%rbp)
    movl    -4(%rbp), %eax
    …

The compiler optimizes the expression so it is a number which will be put into our variable foo. This is way better than loading an address and dereferencing it.

Conclusion

Use shifts, the compiler will optimize them anyway.

Installing NewRelic into MAMP on Mac OS X

Easy as pie if you know how to do it :)

  • Download the New Relic installer files (as a .tar.gz package)
  • Find out your MAMP PHP path (mine was /Applications/MAMP/bin/php/php5.3.6/bin)
  • Go to your unpacked new relic installer files and execute
sudo NR_INSTALL_PHPLIST='<your mamp php path>' ./newrelic-install
  • Follow the instructions in the installer (don’t forget to edit your php.ini, the installer gives you instructions on what to add)

And voilá, worked like a charm :)

PS: New Relic is kind of awesome!

Setting up NHibernate with SQLite using Visual Studio 2010 and NuGet

Here’s something that really took me some time to figure out. The problem was that I tried to set up the libraries all by myself, when there is this awesome tool called NuGet which does it for you. So here’s how I did it.

Installing NuGet

This is pretty straight forward. Download NuGet from the project’s homepage and follow the installation instructions.

Setting up your project

For this tutorial, I created a Visual C# Console Application called “NHExample”, and I suggest you do the same (including the name, because I will be using it later in the example files):

Installing the required libraries

Now, in the main Visual Studio window, go to “Tools > Library Package Manager > Manage NuGet Packages”. If you don’t have that menu option make sure you’ve restarted Visual Studio after installing NuGet. The following dialog should open:

Now install the following libraries (if you can’t find them, there’s a search field in the upper right corner):

  • NHibernate (installs Iesi.Collections as a dependency)
  • System.Data.SQLite (x86)

Configuring NHibernate for SQLite

Create a new XML file called hibernate.cfg.xml in your project’s root directory (Right click on your project > Add > New Item, then from the left menu choose “Data” and then “XML File”), and insert the following content:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory name="NHibernate.Test">
    <property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
    <property name="connection.connection_string">Data Source=nhibernate.db;Version=3</property>
    <property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
    <property name="query.substitutions">true=1;false=0</property>
    <property name="show_sql">true</property>
  </session-factory>
</hibernate-configuration>

Two notables things here. First, there is the Data Source in the property connection.connection_string which specifies which database file will be used (the files is created automatically if it does not exist). Second, there is the property show_sql. If you set that one to true, all SQL-Queries generated by NHibernate will be written to the console, which is very useful for debugging.

Important: You need to set this XML file’s Copy to output directory option to “Copy Always”, or your application will burst into flames almost immediately.

Creating the Entity Class and the Mapping

We’re going to create and map a very simple “Product” entity in this tutorial (there are plenty of sources if you want to create more complex stuff, see the Links section at the end of the article for some of them). To do this, we need two things:

  • The actual C# Class
  • The XML mapping file

The C# Class

The C# Class is pretty straight forward:

using System;

namespace NHExample.Domain
{
    public class Product
    {

        public virtual Guid Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Category { get; set; }
        public virtual int Price { get; set; }

    }
}

Three important things in this short piece of code, though:

The NHibernate XML Mapping

I’ve created a new directory called “Mappings” for the XML file, which needs to be called Product.hbm.xml. The content has to be as follows:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                  assembly="NHExample"
                  namespace="NHExample.Domain">

  <class name="Product" table="products">
    <id name="Id">
      <generator class="guid" />
    </id>
   
    <property name="Name" />
    <property name="Category" />
    <property name="Price" />
  </class>

</hibernate-mapping>

This file tells NHibernate how the database scheme should look and which class properties should be persistent. You may have noticed that there are no type attributes for the properties, because NHibernates infers the types directly from the class file. The <generator class="guid" /> is used to automagically generate an Id for newly created entities.

Important: In order for NHibernate to be able to load your mapping file, you need to set it’s Build Action to “Embedded Resource” (it is above the “Copy to output directory” option we’ve seen in the “Configuring NHibernate for SQLite” section).

Actually using NHibernate

So now we’ve set everything up and we’re ready to write some actual code. And the first thing we need to do is the NHibernate configuration initialization and the creation of a session:

// Initialize NHibernate
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Domain.Product).Assembly);

// Get ourselves an NHibernate Session
var sessions = cfg.BuildSessionFactory();
var sess = sessions.OpenSession();

The first part reads the XML configuration file we’ve created earlier, initializes the SQLite driver and also reads the mapping file for our Product entity.

// Create a Product...
var product = new Domain.Product
            {
                Name = "Some C# Book",
                Price = 500,
                Category = "Books"
            };

// And save it to the database
sess.Save(product);
sess.Flush();

Here we create a new Product instance and populate it with some data. Then we save it to the database. The sess.Flush(); makes sure that all pending actions are executed before going on.

// Note that we do not use the table name specified
// in the mapping, but the class name, which is a nice
// abstraction that comes with NHibernate
IQuery q = sess.CreateQuery("FROM Product");
var list = q.List<Domain.Product>();

// List all the entries' names
list.ToList().ForEach( p => Console.WriteLine( p.Name ));

This last part creates a query to get our data back from the database, and just prints out the name of every Product entity in the database.

The full example project

The full example project’s source code is available on GitHub.

Further reading

The end…

If you have any suggestions, there is anything wrong with the code or you just want to say “Hi”, I’d appreciate if you’d leave a comment :)

Also, many thanks to Mohamed Meligy who introduced me to NuGet, without which I’d have spent many more hours trying to figure out which version of SQLite works with which versions of NHibernate in which scenario… -_-”