Using highlight.js with WordPress’ Twenty Fifteen theme

I’ve recently switched over to using highlight.js for my code highlighting on my blog mainly because it supports Elixir syntax highlighting.

Out of the box, running highlight.js with the WorPress Twenty Fifteen theme causes lines of code to wrap.

I wanted lines to run continuously with a scroll bar.

The following css tweaks did it for me:

pre {
    border: 0;
    padding: 0;
    white-space: pre;
    overflow-wrap: normal;
}
code {
    overflow-x: scroll;
}

Your mileage may vary, but some quick tests seem to show this working reasonably well.

Of course you might not want to override the pre tag completely and instead push the changes into a class to apply to any pre tags wrapping your code.

And you’ll want to rig this up into a child theme so you don’t jettison your code when you run an update.

Customising your json output in Ruby on Rails 3.2

You know how it goes; you’ve found yourself developing a little application to store and display nursery rhyme lyrics because you’re a good parent and want to get the words right for your tot when you sing to them and really, who can remember all seven verses of Twinkle Twinkle Little Star. So, you scaffold something like:

rails g scaffold NurseryRhyme name:string rhyme:text

And you’re away. Typing (or in fact cut’n’pasting from Project Gutenberg). All is bliss. You nail the improvised high note right at the end of Frère Jacques and your kid smiles from ear to ear.

So now, our story breaks down. Suffice it to say you can grab your data from your auto-generated json api. And it looks something like this:

[
{"name":"Humpty dumpty","updated_at":"2012-04-11T20:07:46Z","rhyme":"Humpty dumpty sat on a wallrnHumpty dumpty had a great fallrnAll the kings horses and all the kings menrnCouldn't put humpty together againrn","id":1,"created_at":"2012-04-11T20:07:46Z"},
{"name":"Jack and Jill","updated_at":"2012-04-11T20:08:18Z","rhyme":"Jack and Jill went up the hillrnTo fetch a pail of waterrnJack fell down and broke his crownrnand Jill came tumbling after","id":2,"created_at":"2012-04-11T20:08:18Z"},
{"name":"Baa baa black sheep","updated_at":"2012-04-11T20:09:02Z","rhyme":"Baa baa black sheeprnHave you any woolrnYes sir Yes sirrnThree bags fullrnOne for the masterrnAnd one for the damernAnd one for the little boy rnWho lives down the lane","id":3,"created_at":"2012-04-11T20:09:02Z"}
]

But you want to import it into an application, that for some reason expects the json to be somewhat differently described. You need to trash the ids and dates and change “rhyme” to “lyric”. Plus, you need each rhyme nested in a “LovelyRhyme” element. Baaa (baa black sheep).

And here’s the tldr; How to customise your json output. Start by opening up your model. You should have something like this:

class NurseryRhyme < ActiveRecord::Base
  attr_accessible :name, :rhyme
end

Add in a little code, as follows:

  def as_json(options={})
     { :LovelyRhyme => { :name => name, :lyrics => rhyme } }
  end

And that will render you this:

[
{"LovelyRhyme":{"lyrics":"Humpty dumpty sat on a wallrnHumpty dumpty had a great fallrnAll the kings horses and all the kings menrnCouldn't put humpty together againrn","name":"Humpty dumpty"}},
{"LovelyRhyme":{"lyrics":"Jack and Jill went up the hillrnTo fetch a pail of waterrnJack fell down and broke his crownrnand Jill came tumbling after","name":"Jack and Jill"}},
{"LovelyRhyme":{"lyrics":"Baa baa black sheeprnHave you any woolrnYes sir Yes sirrnThree bags fullrnOne for the masterrnAnd one for the damernAnd one for the little boy rnWho lives down the lane","name":"Baa baa black sheep"}}]

Awesome. Thanks for reading.

An ASP.NET MVC3 implementation of the cancerous Node.js Fibonacci code

I like to tinker with Node.js. Ted Dziuba doesn’t anymore. He thinks node.js is a cancer.
Obviously, a few people disagree – Joshua Kehn and Brian Beck. Ignoring all issues of relevance or flaimbait…and even ignoring all issues of original intent of the article, I was curious to see how C# under ASP.NET MVC3 fared in this little shootout.

I set up a simple MVC application. One controller. It looks like this:

public class HomeController : Controller
    {
        private int Fib(int? n){
            if (n < 2)
            {
                return 1;
            }
            else
            {
                return Fib(n - 2) + Fib(n - 1);
            }
        }

        public string Index(int? n)
        {
            if (string.IsNullOrEmpty(n.ToString()))
            {
                n = 2;
            }
            return Fib(n).ToString();
        }
    }

I ran it on an instance of IIS6.

$ time curl http://localhost/?n=40
default
real    0m0.343s
user    0m0.015s
sys     0m0.015s

Not too bad really. Haskell, however, is super duper fast – as Mathias Biilmann shows.

There’s a little fun for a Tuesday morning.

ASP.Net MVC RadioButtons Redux

Following on from my little radio button rant, let’s figure out how to implement radio buttons in ASP.Net MVC 3 using Razor views.

For this example, I’m going to set up a simple database with two tables: Person and AgeGroups.

First up, define our AgeGroup model:

public class AgeGroup
{
    public int Id {get; set;}
    public string Description {get; set;}
}

Compile your project (F6) and then right click on the Controllers folder and select Add->Controller. Create a controller, selecting the Template as “Controller with read/write actions and views, using entity Framework”. Your Model class should be “AgeGroup” and your Data context – whatever you’ve set up to be your data context class. Now you have a front end for AgeGroup CRUD. For my purposes, I’m going to populate AgeGroup with four values:

  • 0 to 15
  • 16 to 30
  • 31 to 75
  • 75 and over

Next we need to create a model for our Person table/entity:

public class Person
{
    public int Id {get; set;}
    [Required]
    public string FullName {get; set;}
    
    public int AgeGroup_Id { get; set; }
    [ForeignKey("AgeGroup_Id")]
    public virtual AgeGroup AgeGroups {get; set;}
}

So Person is pretty simple for the sake of the example – just a full name and an age group. Declaring the virtual property of AgeGroup will set up our relationship between Person and AgeGroup in the database.Note that I’ve used a data annotation to make FullName required so you’re going to need to include the data annotations library up top of your model.

using System.ComponentModel.DataAnnotations;

I’ve also taken the decision to explicitly declare my foreign key column :

public int AgeGroup_Id { get; set; }

and then told ASP.NET that it is in fact my foreign key by using the Data Annotation on my virtual property. You don’t need to declare your foreign key column explicitly if you don’t want to, but if you do, when you choose to create your controller and generate your views, it will automatically create a drop down list for you – which is a handy starting point for the sake of our example.

[ForeignKey("AgeGroup_Id")]
public virtual AgeGroup AgeGroups { get; set; }

Again, compile your code and then generate your controller and your views for Person. I’ve chosen to let Entity Framework (EF) generate my views for me as well, just because I wanted something quick.

Now, let’s start with our “create” action. Jump in to your PersonController and note that we are exposing a SelectList of AgeGroups in our ViewBag (the EF framework autogenerates the select list line of code based on our foreign key data annotation we put in our code earlier, so if you didn’t explicitly set your foreign key column, you’ll need to add in a little code here yourself)

public ActionResult Create()
{
    ViewBag.AgeGroup_Id = new SelectList(db.AgeGroups, "Id", "Description");
    return View();
}

Dropping down into your Create.cshtml for Person, you can check the code that actually creates the drop down box for you:

<div class="editor-label">
    @Html.LabelFor(model => model.AgeGroup_Id)
</div>
<div class="editor-field">
    @Html.DropDownList("AgeGroup_Id", String.Empty)
    @Html.ValidationMessageFor(model => model.AgeGroup_Id)
</div>

So far you should have a nice drop down list. Now we want to turn that drop down into radio buttons. To do this, we have to put a little time in and code up a loop, replacing the following code:

    @Html.DropDownList("AgeGroup_Id", String.Empty)
    @Html.ValidationMessageFor(model => model.AgeGroup_Id)

with this:

   @{
     foreach (var ageGroup in ViewBag.AgeGroup_Id)
     {
        string ageGroupId = ageGroup.Value;
        string ageGroupDescription = ageGroup.Text;
        @Html.RadioButtonFor(model => model.AgeGroup_Id, ageGroupId) 
        @ageGroupDescription
     }
    }
    @Html.ValidationMessageFor(model => model.AgeGroup_Id)

There, that wasn’t so hard was it?!?

Btw, if you’re new to ASP.NET MVC then there’s a good roundup of resources on Jon Galloway’s blog.

How to speed up Ubuntu 11.04 – Swappiness

Or pretty much any Ubuntu version really. This is aimed at desktop installations, not servers.

Ubuntu has a fancy little property called swappiness. Swappiness basically tells Ubuntu how often to move processes out of memory and onto the hard drive. Things that are in memory are faster. Just like remembering something is faster than wondering off to google and looking it up. So in general, on your average Ubuntu desktop, you want to tell the operating system to keep processes in memory for longer. Enter swappinesss.

To find out your swappiness open up a terminal and try this:


cat /proc/sys/vm/swappiness

It will probably report back “60”. Now, for desktops, the recomended value of swappiness is 10. So let’s change the swappiness factor – open up /etc/sysctl.conf in your favourite text editor (you get extra imaginary points if you use vim instead of gedit). Again, at the terminal type:


sudo gedit /etc/sysctl.conf

Search for (or add if it isn’t there) “vm.swappiness” and change it to:


vm.swappiness=10

Save, reboot and hey presto off you go. For the curious, read more about swap than you could ever want to know.

I have no idea why Ubuntu doesn’t set this by default on desktop installs really, it’s one of the things that is standing in the way of it really taking off for the average computer user. Not swappiness per se, but just the fact that you have to get your hands a little dirty when you run Ubuntu, when the average person just wants to install and then play Internet, Facebook, Twitter, type a few documents and check their bank balance. Still, now you can do all that. Only faster.