The Roberto Selbach Chronicles

About |  Blog |  Archive

Blog

Linux Kernel Linked List Explained

I appreciate beautiful, readable code. And if someone were to ask me for an example of beautiful code, I’ve always had the answer ready: the linked list implementation in the Linux kernel.

The code is gorgeous in its simplicity, clarity, and amazing flexibility. If there’s ever a museum for code, this belongs there. It is a masterpiece of the craft.

I was just telling a friend about it while we talked about beautiful code and he found this piece that I share here: Linux Kernel Linked List Explained.

Container changes in C++11

The recently approved C++11 standard brings a lot of welcome changes to C++ that modernize the language a little bit. Among the many changes, we find that containers have received some special love.

Initialization

C++ was long behind modern languages when it came to initializing containers. While you could do

[cpp]int a[] = {1, 2, 3};[/cpp]

for simple arrays, things tended to get more verbose for more complex containers:

[cpp]
vector v;
v.push_back(“One”);
v.push_back(“Two”);
v.push_back(“Three”);
[/cpp]

C++11 has introduced an easier, simpler way to initialize this:

[cpp]
vector v = {“One”, “Two”, “Three”};
[/cpp]

The effects of the changes are even better for things like maps, which could get cumbersome quickly:

[cpp]
map<string, vector > m;
vector v1;
v1.push_back(“A”);
v1.push_back(“B”);
v1.push_back(“C”);

vector v2;
v2.push_back(“A”);
v2.push_back(“B”);
v2.push_back(“C”);

m[“One”] = v1;
m[“Two”] = v2;
[/cpp]

This can now be expressed as:

[cpp]
map<string, vector> m = One,

                             {"Two", {"Z", "Y", "X"}}};

[/cpp]

Much simpler and in line with most modern languages. As an aside, there’s another change in C++11 that would be easy to miss in the code above. The declaration

[cpp]map<string, vector> m;[/cpp]

was illegal until now due to >> always being evaluated to the right-shift operator; a space would always be required, like

[cpp]map<string, vector > m[/cpp]

No longer the case.

Iterating

Iterating through containers was also inconvenient. Iterating the simple vector v above:

[cpp]
for (vector::iterator i = v.begin();

 i != v.end(); i++)
cout << i << endl;[/cpp]

Modern languages have long had some foreach equivalent that allowed us easier ways to iterate through these structures without having to explicitly worry about iterators types. C++11 is finally catching up:

[cpp]
for (string s : v)

cout << s << endl;

[/cpp]

As well, C++11 brings in a new keyword, auto, that will evaluate to a type in compile-type. So instead of

[cpp]
for (map<string, vector >::iterator i = m.begin();

 i != m.end(); i++) {

[/cpp]

we can now write

[cpp]
for (auto i = m.begin(); i != m.end(); i++) {
[/cpp]

and auto will evaluate to map<string, vector>::iterator.

Combining these changes, we move from the horrendous

[cpp]
for (map<string, vector >::iterator i = m.begin();

 i != m.end(); i++)
for (vector<string>::iterator j = i->second.begin();
     j != i->second.end(); j++)
    cout << i->first << ': ' << *j << endl;

[/cpp]

to the much simpler

[cpp]
for (auto i : m)

for (auto j : i.second)
    cout << i.first << ': ' << j << endl;

[/cpp]

Not bad.

C++11 support varies a lot from compiler to compiler, but all of the changes above are already supported in the latest versions of GCC, LLVM, and MSVC compilers.

FOR is evil or something

Have you ever wondered how FORs impact your code? How they are limiting your design and more important how they are transforming your code into an amount of lines without any human meaning?

How can you not want to read an article that starts like that? I had to steal the intro from the original. Seriously, I have used FOR since I learned BASIC back in the day. I never thought about how it was limiting my design. I. Must. Learn. How.

The article I am referring to is, Avoiding FORs – Anti-If Campaign. Eager learner I, I could not not read it.

After the resplendent intro, Avoiding FOR goes on to show “how to transform a simple example of a for […], to something more readable and well designed.”

It takes this unreadable piece of code — that I now recognize as unreadable:

[java]
public class Department {

private List resources = new ArrayList();

public void addResource(Resource resource) {
    this.resources.add(resource);
}

public void printSlips() {

    for (Resource resource : resources) {
        if(resource.lastContract().deadline().after(new Date())) {

            System.out.println(resource.name());
            System.out.println(resource.salary());
        }
    }
}

}[/java]

My eyes hurt already. Thankfully the author transforms the aberration above into this clean, much more readable snippet:

[java]public class ResourceOrderedCollection {

    private Collection<Resource> resources = new ArrayList<Resource>();



public ResourceOrderedCollection() {
    super();
}

public ResourceOrderedCollection(Collection<Resource> resources) {
    this.resources = resources;
}

public void add(Resource resource) {
    this.resources.add(resource);
}

public void forEachDo(Block block) {
    Iterator<Resource> iterator = resources.iterator();

    while(iterator.hasNext()) {
        block.evaluate(iterator.next());
    }

}

public ResourceOrderedCollection select(Predicate predicate) {

    ResourceOrderedCollection resourceOrderedCollection = new ResourceOrderedCollection();

    Iterator<Resource> iterator = resources.iterator();

    while(iterator.hasNext()) {
        Resource resource = iterator.next();
        if(predicate.is(resource)) {
            resourceOrderedCollection.add(resource);
        }
    }

    return resourceOrderedCollection;
}

}

public class Department {

private List<Resource> resources = new ArrayList<Resource>();

public void addResource(Resource resource) {
    this.resources.add(resource);
}

public void printSlips() {
    new ResourceOrderedCollection(this.resources).select(new InForcePredicate()).forEachDo(new PrintSlip());
}

}[/java]

Wait, what? Is this an Onion article?

Snarky Mode Off.

I understand what the author wanted to do, but really, the example used is so off the left field that it’s not even funny.

Rolling out your own Fusion Drive with the recovery partition

disk utility showing Fusion Drive

My Macbook Pro has two disks, an HDD and an SSD, each of 240GB or so. With the details of Apple’s Fusion Drive coming out I decided to do what any reasonable geek would do to their production computer: I’ve decided to implement my own untested, highly experimental and barely understood Fusion Drive.

One of the things that initially put me off doing this was that according to the 3,471,918 tutorials that have popped up in the last 10 minutes would cause me to lose my Mountain Lion recovery partition because these partitions are not supported in a Fusion drive. Turns out this is not exactly true.

Fusion Drive is just a marketing term for a what essentially is a CoreStorage logical volume spanning an SSD and an HDD. And although you cannot have the recovery partition inside a CS logical volume, it doesn’t mean you can’t have both a recovery partition and a Fusion Drive at the same time. It’s all in the diskutil man page, by the way:

Create a CoreStorage logical volume group. The disks specified will become the (initial) set of physical volumes; more than one may be specified. You can specify partitions (which will be re-typed to be Apple_CoreStorage) or whole-disks (which will be partitioned as GPT and will contain an Apple_CoreStorage partition). The resulting LVG UUID can then be used with createVolume below. All existing data on the drive(s) will be lost. Ownership of the affected disk is required.

What matters is what’s in bold above: we’re not limited to using whole disks. So here’s what I did.

I rebooted my system and held the option key so I could select my recovery partition as the start up disk. Once the OSX recovery started up, I launched a terminal to do the dirty work.

diskutil list

From this I noted two things: (a) the main SSD partition (the one holding my OSX and that sited by my recovery partition) and (b) the disk name of my HDD. They were respectively disk0s2 and disk1 in my case, but they’ll very likely be different for you. Then the magic begins.

diskutil cs create "Fusion Drive" disk0s2 disk1

(For crying out loud, you need to change disk0s2 and disk1 for whatever makes sense on your system!)

That created the coreStorage logical volume. Then I listed it all again to note what the new logical volume UUID was.

diskutil list

The UUID is a long number identifier like F47AC10B-58CC-4372-A567-0E02B2C3D479. You’ll need that one next to actually create the volume where you’ll be installing your system.

diskutil coreStorage createVolume F47AC10B-58CC-4372-A567-0E02B2C3D479 jhfs+ "Macbook FD" 100%

The command above will create a volume named “Macbook FD” using 100% of the logical volume we had created earlier.

I then restored my Time Machine backup and that’s it.

Update: Note that after this process, the Recovery partition will still be present and things that require it (such as Find My Mac) will work fine. Some people correctly pointed out, however, that you can no longer boot from the recovery partition by using the menu from holding ⌥ (option) during boot. I’m not sure why that is, but fear not, it will still boot normally from pressing ⌘R (command + R).

Not a-ok

I have a little confession to make: our family is going through a rough patch. Both my wife and I are having problems. No, not between us. And both are experiencing very different sorts of problems. But the happening-at-the-same-time complicates the one-supports-the-other thing.

And to compound to that, I have been sick.

As I sat in the waiting room at the hospital the other day, waiting for some exams, I felt like this is one of the worst times of my life. I feel tired, unmotivated, unappreciated, and generally unhappy. And fucking hopeless. That’s the worst part, I suppose.

I also have been distancing myself from friends lately. Ostensibly to avoid distractions in a time where I am having to give all and a bit more to a project I do not believe in. Truth be told, I just don’t feel like small talk but I also don’t want bring others down to my Dark Hole of Misery. And so I’m trying to keep some distance.

I feel lost. I look at my friends and how they all seem to have it all figured out already. I’m still trying to figure out who the fuck I am. I was so sure when I was younger. I was so fucking good at what I did. Now? I just don’t know anymore. I feel unhappy.

I know some people who will be So. Fucking. Happy. reading the paragraph above. This one’s for free for you guys.

But not all is bad news. I actually got some good news last night. I can’t tell the details although I know some of you know exactly what this is about. Anyway, I now have a set date for it and it’s in under six months from now.

I’m actually confident that this will make it all better somehow. Just have to wait.

Sorry for the downer, but I felt like writing something.

How I accidentally because a domain squatter

A couple of days ago, I was listening to one of my favourite podcasts, The Frequency, when one of the hosts, Dan Benjamin, thought of a cool domain name, ohitson.com and checked to see if it was available. Turns out it was and he said he was registering right there and then. Now, two things: (a) I was listening to a recorded podcast, not live; and (b) I thought to myself, damn it! it is a cool domain name.

The next day, I launched Hover and checked the domain name and to my surprise it was available. I simply thought either Dan had given up on it or, most likely, I had misunderstood the domain name he was talking about and fortunately that had made me thing of this cool domain name. I even checked Google to make sure “Oh, it’s on” was really written like that 😛

Obviously I went ahead and registered the name. After that, I listed to that day’s The Frequency and heard Dan tell Haddie something to the effect of “oh, I forgot to register that domain yesterday!” That’s when I thought, oh-oh, maybe I had heard the correct domain name.

As it turns out, I was just listening to today’s episode and guess what? Dan mentions that someone registered it due to his mention on the show (which is technically true.)

But I am a nice guy. I offered to transfer the domain to Dan for free just a few minutes ago. Not sure he’ll see my posts to app.net or Twitter. If not, I’ll try again a few times. I really don’t have any intention to keep this domain name as long as he still wants it. Sounds unfair.

Update 7 Nov 2012: can you believe he actually accepted my offer? What a douche! Just kidding, it was the Fair Thing to Do™ and I’m happy to say the domain has been transferred to His Benjaminship already.

The day a videogame changed my life

Last night, as I tried getting my three year-old to sleep so I could play my brand-new copy of NHL 13, I had an epiphany of sorts. It dawned on me how much videogames influenced my real-life pleasures. And the story actually started a long time ago.

http://cd.textfiles.com/gifgalaxy/PROGRAMS/VGACOPY.GIFThe story begins in a rather pleasant Saturday afternoon in late 1993. We went into a shoddy building, walked up the stairs to the first floor and found this rather unassuming office at the end of the hall. We skimmed over a thick catalog of game titles and started picking a few we wanted to try. They were cheap, pirated games. After selecting the titles, the guy there noted them down and asked us to wait. In the back, two guys got some floppy disks and started copying the games for us with VGAcopy. Nice!

Of the games we bought, only one I can still remember: NHL Hockey. To that day, I had only a general idea of what hockey was: Soccer on the ice. We picked it simply because the clerk there told us it was good.

We went home that day and probably tried some of the other, now-forgotten games, but then we installed NHL Hockey from the floppies to MS-DOS. We were both hooked instantly! The game had an arena atmosphere that later version never quite managed to reproduce. We did not know the many rules of hockey, we learned as we played. I remember vividly as my friend pumped up the volume on the PC when the game would play an 8-bit version of “We will rock you” while two cartoon hands clapped on the virtual jumbotron.

http://www.igcent.com/images/stories/nhl96.jpgWe played that game throughout that night and into Sunday. It was fast. It was fun. We were hooked. NHL 96 was the first game I ever legally bought. And I’ve bought almost every version since then.

Back to how it influenced my real-life, playing the game got me into Hockey as a sport. A Brazilian hooked on Hockey? Not supposed to happen, but one likes what one likes. It also indirectly started my love affair with Canada, but that’s a different story. Following Hockey was not easy until I found a radio that streamed games and later the League started offering live vide streaming for which I have been gladly paying an exorbitant amount of money for half a decade or so. I’ve experienced a similar effect thanks to the Madden and NBA Live series, but NHL Hockey will always be a special case for me.

I realized that thru hockey I’ve made friends, some of whom are real good friends. And all of this started because a couple of decades ago we got some pirated games in a Saturday afternoon.

Want to make a comment or suggestion? Do you feel like you need to correct me for not fitting the Standard Brazilian Specification? Feel free to talk to (or scream at) me, I’m @robteix on App.net and also on Twitter.

In which Rob gets app.net

I got myself an app.net account (@robteix) a couple of days ago. [Cue the ihave50dollars.com jokes.] Still haven’t really used it a lot but am starting to enjoy the discussions about the API development.

I joined mostly to support the idea—which I must admit is pretty insane. But what would the world be without insane ideas? ADN will never be Twitter or Facebook, but maybe it doesn’t need to be. Maybe it really only needs to be a same environment for people like me. I like it.

They do need a better name though.

  • Posted using BlogPress from my iPhone

Could something like “Apollo 18” really have existed?

Conspiracy theories and hoaxes abound when it comes to mankind’s arrival at our moon (or the non-arrival.) One such hoaxes is the Apollo 20, a purported top secret mission that back to the moon back in 1976 to fetch some aliens living there. The secret would have been revealed by no other than William Rutledge, who claims to have been an astronaut in that mission and who nowadays lives and writes out of Rwanda.

Arguably this theory was never as popular as its always popular theory that NASA spent billions of dollars to fabricate the moon landings but somehow forgot to paint stars in the ceiling.

Now however a film promises to inspire the masses who believe NASA has been sending secret missions to Luna. The movie is Apollo 18.
apollo-18-movie
(Promotional picture)

The movie’s premise is that after the Apollo program was cancelled, NASA would have flown another mission and found, of course, aliens and that’s why we’ve never been back to the Moon. It’s one more movie in the style of Cloverfield, where the audience is expected to pretend to be watching to real top-secret leaked footage.

Domension Films’ big cahuna, Bob Weinstein, stated,

We didn’t shoot anything, we found it. Found, baby!

The movie is of course a work of fiction. That’s not hard to figure out, even if you could not look up the actors who were in the movie. For instance, the astronauts of Apollo 18 in the movie are supposed to be Nathan Walker, John Grey e Benjamin Anderson, but the astronaut corps roster was very well known and none of these gentlemen were part of it. Although none of the crews for the cancelled flights (Apollos 18, 19 and 20) were never officially named – what would be the point? –, one can infer from the assignment rotation system NASA used that the Apollo 18 crew would likely be:

  • Richard Gordon
  • Vance Brand

  • Harrison Schmitt

Except Schmitt was activated to the Apollo 17 main crew when it became clear that it would be the last chance for a scientist to step on the moon. Somebody – Joe Engle, perhaps – would have to replace him on Apollo 18.

But the hoax is not really about the movie itself, but about the general idea that NASA ran more missions than we know about. So, could something like Apollo 18 really have existed? Could NASA have performed this secretly?

It is unfortunately impossible to prove a negative, but at least we can think of how likely would that be. I can’t really see how such a thing could have been done. To begin with, there’s this:
flickr-3743794970-original
(Image credit: Euclid vanderKroew)

You see, the Saturn V was big. Really big. Not easy to hide, then. It seems highly unlikely that NASA could have launched a Saturn V out of Cape Canaveral without it being seen.

I also saw this argument on some forum that NASA would have prefferred a night launch to improve the chances to keep it a secret, but the thing is, that big dumb rocket is not very subtle either.
3743667306_c2b398ee5b_z
(Image credit: Euclid vanderKroew)

And then if we discard a launch in the continental US, it would have to be from either a platform at sea or from somewhere in North Africa. Problem here is that the logistics of accomplishing such an feat – let alone in absolute secrecy – are just fenomenal.

As well, the Saturn V was a very public project. All its parts were very well tracked and it’s possible to know where most parts are even today. And some of those parts are huge, not the kind that you can stow in the back of a black unmarked van.

And then there are other factors, of course. We’re used to the image of three astronauts sitting on top of a rocket and a mission control room with, say, 20 or 30 people.
2985911950_0f3a207a10_z
(Image credit: Cory Doctorow.)

But an Apollo flight involved a lot more people than that. In A Man on the Moon: The Voyages of the Apollo Astronauts (Awesome gift! Thank you Stulzer!), Andrew Chalkin estimates the figure at 500,000 workers altogether. Others state the number is more like 400,000 people.

Regardless of the actual figure, it should be clear that such a mission would require the collaboration of hundreds of thousands of people all around the world (more on that below.)

And contrary to what some might want to believe, the Apollo program was not something entirely done behind closely guarded doors at some Air Force base. It involved a lot of private contractors. GE, IBM, Boeing, GM… the list of contractors can occupy several pages. To assume that all the employees involved who have since likely changed jobs multiple times and retired would be able to keep this a secret for four decades really stretches one’s imagination.
figc-3
(Image credit: history.nasa.gov)

As big as the contractors’, the list of academic institutions involved in the program is amazing. Virtually every major US university and institute was included, but the list also included institutions form Australia, Belgium, Canada, England, Finland, Germany, Japan, Scotland and Switzerland. And that takes me to what is, to me, the most important thing to consider.

In order to fly to the Moon, you don’t just point the rocket, turn on the ignition and wait for it to reach its destination. It’s a complex voyage with huge preparations, calculations and adjustments. Orbital mechanics was one of the most interesting things I’ve even studied. But I digress.

An interesting challenge for NASA was to be able to communicate and track the ship all the way to the Moon and back.
flight-profile-p17
(Escaneado pelo autor. NASA Apollo 11 Press Kit Pg 17)

Nowadays NASA added a whole network of satellites to assist the tast, but back when Mercury and Apollo were underway, the tracking depended on a network of tracking stations, vessels and aircraft all around the world.

That network was the Manned Space Flight (Tracking) Network. Starting from Apollo 10, the Deep Space Network was added to assist.
MSFN
(Scanned by the author from NASA Apollo 11 Press Kit, Pg 172)

It’s interesting to know that over the course of its evolution, NASA’s networks included a station in Havana, Cuba. That station was dismantled after years of service due to the Cuban revolution. As Brazilian, I also find special interest in that there was even one station along with the Brasilia International Airport, even though it was quickly disassembled and shipped to Madagascar.)

Although those were NASA installations, they employed locals. These stations all around the world had been performing duties for years under heavy media scrutiny and to expect that all of a sudden they would be able to do it in complete secrecy is beyond reasonable belief. That and the local workers who also had to keep secrets for four decades make the most absurd hole in the hoax.

Now remember that the Apollo missions were tracked and monitored by several governments including, of course, the Soviet Union. In Two Sides of the Moon, Russian cosmonaut Alexei Leonov – trained to be the first man on the moon – states that all the missions were followed by the Russians in a very well equipped Space Transmissions Corps, in Moscow. Now you need the secret to be kept by the Soviets and then, after the USSR fell, by the several nations that sprouted from it.

And the Apollo missions were tracked by amateur astronomers and radio operators all over.

Of course that nothing here proves beyond any doubt that such secret missions were impossible, just unreasonable unlikely. But since you can’t prove a negative, no matter how improbale, there will still be plenty of people who believe.

My need for anonymity

Much has been said about the pros and cons of anonymity lately, prompted by Google+ TOS which require the use of one’s real name. No pseudonyms allowed, except apparently if you call yourself Lady Gaga or 50 Cent.

I have seen many kinds of arguments both for and against the use of aliases and I will not repeat them here. There is however one use of aliases that I haven’t seen stated anywhere and that coincidentally affects me personally. Perhaps this is so because the problem I am about to present is not so common after all. Or perhaps it is common but people decide not to talk about it. I have no way of knowing.

Anonymity is a vital necessity to people with a certain kind of disability, a mental disorder. I am such a person. As some of my friends know and others mock, I suffer from a mental condition called social phobia, also known as social anxiety. I take medications that help me overcome some of the most serious effects and that allow me to do things like write about it on this very blog.

Social anxiety manifests itself in varying degrees in all kinds of social interactions. And the levels of manifestations are not what you might expect. I regularly make presentations without a second thought. I’ve given talks to hundreds of people. And yet, ordering a pizza over the phone is terrifying experience to me. No matter how many times I’ve done it, I still have to “prepare” myself every time. I rehearse, play several unlikely scenarios in my head until I finally get the courage to dial the number and talk to the person on the other side. One characteristic of this anxiety disorder is that rationally I know that there is nothing wrong; there is no risk in calling the pizza place. But the brain acts as if there were. But I digress.

I love coding. I have been doing it since I was a kid and it’s the best thing I know how to do. And then there is open source. Open source projects should be the perfect venue for me to have fun. Except I am scared stiff by the idea that someone might laugh at the code. It came to a point where it is impossible for me to contribute. Then I’ve come up with a solution: an alias. For the past several years I’ve lived two different lives online: one as myself and another as an alias. I keep them strictly separate.

Using the alias, I actively contribute to several different projects. And I enjoy it all. And it would be impossible for me to do that using my own name. My pseudonym allows me to work around my condition. It allows me to live my life.

I understand the rationale behind the requirement for real names on Google+. But I also know that the requirement makes it impossible for people like me to be really free on the Internet. So far, Google hasn’t figured out my alias. Hopefully it never will.

(Photo by Abhishek Singh)