Nick Desaulniers

The enemy's gate is down

The Persistence of Memory

| Comments

I would like to die on Mars…

Well, isn’t that forward thinking? Granted, the full quote I would like to die on Mars, just not on impact is meant to sound hopeful of his company, SpaceX. I agree that some day, humans will be buried on Mars. But is it forward thinking, enough? Does it push the needle to where it needs to be pushed? Does it strive for innovation and push our imagination like Star Trek did? Or is it just a realistic goal for SpaceX?

The person with big dreams is more powerful than one with all the facts.

Albert Einstein

While Elon would like to die on Mars, I think it would be neat to transfer my “soul” into a computer. We refer to data persistence within a computer as memory, using transistors and capacitors to store charges, effectively “remembering” a particular state. While neurons, dendrites, and synapses within the human brain don’t quite work the same as RAM, I believe we will find a way to interface them some day. If one could transfer to a computer, maybe they could transfer back, or swap even. One could theoretically trade entire bodies. The jury is still out for me as far my opinion of Google’s Glass, but I see wearable computing as a step in the right direction towards interfacing with the human body. I guess it reminds me of the Heads in Jars from Futurama. I recognize that the old guard must give way for the new guard, lest the new be held in place, bound socially by the old.

In database systems, there is this notion of Atomicity, where a set of operations is guaranteed to either complete as a group, or all fail should at least one fail. One of the most popular examples is a bank transfer. Say you’re transferring $100 from Bank A to Bank B. Bank A’s database should not dock your account $100 until Bank B has added $100, and vice versa. Imagine if the power went out after Bank A docked your account, but before Bank B added to your account; that money could just disappear. Bank B may have received it but not credited your account, or Bank A may have it, just not a record that it’s yours. You may have just doubled your money, or lost all of it. The notion of Atomicity provides for “transactions,” or sets of instructions that are guaranteed to all pass or all fail.

Atomicity would be important for a memory transference device. Once you were transferred into a machine, would it still be “you” if you remained in your body? A physical clone, is as much you as an identical twin, but will never have the same memories and experiences that shape their mind. If you merely copied your mind to a machine rather than transferred it, then you would still remained trapped in your rotting piece of meat.

This is what I mean by transfer my “soul.” An actual atomic transaction moving all of your memories and experiences from body to machine, all at once, or not at all. I probably wouldn’t want to be the first volunteer for such a machine, because if the machine failed at the atomic transaction, your soul would either be as lost as the $100 from the earlier example, or you’d just be copied, not moved.

In a world where diseases are too profitable to cure, I can imagine a world where the richest 1% live forever while the poor are forced to die. Frozen Walt Disney just sat up. An abuse of the technology, not too different a world from the one in Surrogates.

Have you not done tormenting me with your accursed time! It’s Abominable! When! When! One day, is that not enough for you, one day he went dumb, one day I went blind, one day we’ll go deaf, one day we were born, one day we shall die, the same day, the same second, is that not enough for you? They give birth astride a grave, the light gleams an instant, then it’s night once more.

Pozzo Waiting for Godot by Samuel Becket

They say that it is fear of death and what comes after death that makes men turn to religion.

Mustafa Mond Brave New World by Alduos Huxley

Ever since my father passed away, I’ve occasionally suffered from existential anxiety attacks. It usually starts with me thinking about those Discovery Channel shows about how the old the universe is, and how old it will become. Then my mind starts to think of all of the really cool technological advancements that have occurred in my lifetime, and how I wont be around to experience all future advancements, like a game that others get to play while I have to sit on the sidelines and watch. Of course, if I’m dead then I guess I won’t care. Currently, I calm myself down my telling myself that such an event is a long time away and I will live a long and happy life with many descendants, though I have no guarantees. My father only lived to be 48.

‘That’s such a weak excuse,’ said Valentine. ‘Everyone dies. Everyone leaves. What matters is the things you build together before they go. What matters is the part of them that continues in you when they’re gone.’

Valentine Children of the Mind by Orson Scott Card

Where before they would bloom and wither in the space of a single day, now they hold their blooms for three and four days at a time. Moistened by the dew of night, bathed in the light of the sun, the white flowers strive to live their lives to the fullest, beautifying the town as if striving to live out the portion of life denied to those whose “tomorrows” were snatched away from them forever.

White Flowers Lost Odyssey

Human beings, who cannot live forever, daring to take a journey without end. This might be the ultimate tragedy, but it could just as well be the ultimate comedy. Kaim knows one thing, however: one cannot simply dismiss it as an exercise in futility.

The Upstreamers Lost Odyssey

Randy Pausch’s The Last Lecture taught me that legacy is the greatest thing you can leave behind. While I haven’t yet started the business I’ve always wanted, my first legacy I will leave my kiddos is my collection of Iron Maiden vinyl records. They and their children will probably think I was nuts, but there is the slim chance they might really appreciate my taste in music. I also want to write a book someday, that way I can marvel at how my ideas will outlast me.

I like to think that something survives after you die, it’s strange to think that you accumulate all this experience, and maybe a little wisdom, and it just goes away. So I really want to believe that something survives, that maybe your consciousness endures. But on the other hand, perhaps it’s like an on-off switch. “Click!” And you’re gone.

Steve Jobs Steve Jobs by Walter Isaacson

It terrifies me to no end to think what could possibly drive someone to suicide. What doom a person would have to be surrounded with to honestly believe that no matter what they did, that they could not change their current situation. I believe the journey is ultimately worth it. It terrifies me to think of all of the amazing minds this world has seen, among so many who choose not to develop their own, that have come and gone. Those who could change the world yet are snatched away.

This body holding me reminds me of my own mortality. Embrace this moment. Remember. We are eternal. All this pain is an illusion.

Parabola Tool

I’m sorry this post turned a little dark. By talking about my fears, I hope to not let them control me. I believe publishing this will be a relief. I think I’ll join Elon on Mars, but unlike Elon, I believe I will transcend my physical being. It’s important therefor, to treasure your body while it lasts.

‘But it [life] won’t have amounted to anything,’ said Grego. ‘If your children die, then it was all a waste.’ ‘No’ said Olhado quietly. Grego shook his head. ‘Yes it does, Olhado. Death undoes everything.’ Olhado shrugged. ‘Then why do you bother doing everything, Grego? Because someday you will die. Why should anyone ever have children? Someday they will die, their children will die, all children will die. Someday stars will wind down or blow up. Someday death will cover us all like the water of a lake and perhaps nothing will ever come to the surface to show that we were there. But we were there, and during the time we lived, we were alive. That’s the truth-what is, what was, what will be-not what could be, what should have been, what never can be. If we die, then our death has meaning to the rest of the universe. Even if our lives are unknown, the fact that someone lived here, and died, that will have repercussions, that will shape the universe.’

Children of the Mind Orson Scott Card

There will allways be hope, wherever you are, until you yourself abondon it.

Old Revolutionary Lost Odyssey

Basic JIT

| Comments

Ever since I learned about Just In Time Compilation from the various Ruby VMs and JavaScript VMs, I’ve been inspired. I could tell you all about how just in time (JIT) compilation worked, and how it could give your interpreted language a speed boost. It was so cool. Well, it still is! There’s a ton of research going on around JIT compilation. But the problem for me is that I could never figure out, let alone guess, how it was being done. How could you compile code at runtime, and then execute it? I asked Benjamin Peterson about how he had learned so much about JITs, and he referred me to pypy (a Python JIT)’s source. But digging through source was too much; I just wanted a simple example I could grok quickly. So I’ve always been left wondering.

Luckily, I have an awesome job where I can meet face to face with the people who are doing the work on making awesome production JIT compilers. I spent part of last week at GDC demoing Unreal Engine 3 running in the browser. The demo was actually the hard work of many, and I’ll dive into it more in another post following up the events, but Luke Wagner, a Mozillian working on the JavaScript engine, added OdinMonkey to SpiderMonkey to allow optimizations of asm.js.

Luke is super friendly, and just listening to him talk with Dave Herman and Alon Zakai is a treat. I asked Luke the basics of JIT’ing at tonight’s Mozilla Research Party and he explained clearly. Compile a simple object file, use objdump to get the resulting platform specific assembly, use the mmap system call to allocate some memory that you can write to AND execute, copy the instructions into that buffer, typecast it to a function pointer and finally call that.

So my goal was to at runtime, create a function that for simplicity’s sake multiplied two integers. The first thing I did was write up a simple .c file, then compile that to an object file with the -c flag.

1
2
3
4
// Compile me with: clang -c mul.c -o mul.o
int mul (int a, int b) {
  return a * b;
}

As a heads up, I’m on 64bit OSX. So the generated assembly may differ on your platform. Obviously, the production JIT maintainers have abstracted away the platform dependency, taking into account what platform you’re on. My example doesn’t, but that why I’m walking you through the steps I took to find out the x86_64 instructions. The next step is to grab binutils, which is not installed by default in OSX. I used homebrew to install it: brew install binutils. Homebrew installs gobjdump but it works with the same flags.

Once you have binutils and [g]objdump, the next step is to read out the machine code from your object file, which is represented in hexadecimal. By running gobjdump -j .text -d mul.o -M intel you should get something similar (remember, architecture dependent).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ gobjdump -j .text -d mul.o -M intel

Disassembly of section .text:

0000000000000000 <_mul>:
0: 55 push rbp
1: 48 89 e5 mov rbp,rsp
4: 89 7d fc mov DWORD PTR [rbp-0x4],edi
7: 89 75 f8 mov DWORD PTR [rbp-0x8],esi
a: 8b 75 fc mov esi,DWORD PTR [rbp-0x4]
d: 0f af 75 f8 imul esi,DWORD PTR [rbp-0x8]
11: 89 f0 mov eax,esi
13: 5d pop rbp
14: c3 ret

Ok, so those instructions vary in size. I don’t know any x86 so I can’t comment too much on that particular Instruction Set Architecture but they’re obviously in pairs of hexadecimal digits. 162 == 28 meaning that each pair of hex digits can be represented by a single byte (or char of memory). So these can all be thrown in an unsigned char []. The man page for mmap explains all of the fun flags, but the important point is that this way of allocating memory makes it executable, so it can do bad things that memory allocated from malloc can’t. I’m sure the JavaScript engine guys have fun with that. Once memory is copied in, you can typecast the memory to a function pointer. Make sure to check out the syntax that reminds me of a function pointer in an argument list, but being used as an L-value. Of course, you could just put the cast right in front of the memory before you use it, but I find this as neat, not so common C syntax. I kind of have a thing for stuff like that. Then we can call it! The resulting code looks like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h> // printf
#include <string.h> // memcpy
#include <sys/mman.h> // mmap, munmap

int main () {
// Hexadecimal x86_64 machine code for: int mul (int a, int b) { return a * b; }
unsigned char code [] = {
  0x55, // push rbp
  0x48, 0x89, 0xe5, // mov rbp, rsp
  0x89, 0x7d, 0xfc, // mov DWORD PTR [rbp-0x4],edi
  0x89, 0x75, 0xf8, // mov DWORD PTR [rbp-0x8],esi
  0x8b, 0x75, 0xfc, // mov esi,DWORD PTR [rbp-04x]
  0x0f, 0xaf, 0x75, 0xf8, // imul esi,DWORD PTR [rbp-0x8]
  0x89, 0xf0, // mov eax,esi
  0x5d, // pop rbp
  0xc3 // ret
};

  // allocate executable memory via sys call
  void* mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC,
                   MAP_ANON | MAP_PRIVATE, -1, 0);

  // copy runtime code into allocated memory
  memcpy(mem, code, sizeof(code));

  // typecast allocated memory to a function pointer
  int (*func) () = mem;

  // call function pointer
  printf("%d * %d = %d\n", 5, 11, func(5, 11));

  // Free up allocated memory
  munmap(mem, sizeof(code));
}

Voila! How neat is that! It works! Luke’s directions, an hour of working on this, and this article in particular, and we have a simple JIT working. Again, this simple example is super non-portable and dealing with memory in this fashion is generally unsafe. But now I know the basics of JIT’ing code, and now so do you!

Thanks Luke!

Commandments of a Mobile Web

| Comments

Over the past few years, there’s been certain paradigm shifts in web development. When you think of milestones that really changed how development on the web was done, the two biggest were Ajax and HTML5. Development was identifiably different before and after such technological advancements. There were some who initially doubted the technologies, but I’m sure such doubters eventually saw the light. After spending time working on applications for Mozilla’s upcoming mobile operating system, Firefox OS, and talking with my fellow employees, I feel that the mobile web is another one of those shifts in how we approach web development that looking back will be an identifiable point in time where we can say that we did things differently before and after. So in that sense, I want to share some of the insights I’ve found to help other developers wrap their heads around how developing for the mobile web isn’t their traditional cup of tea.

Internet connectivity is not guaranteed

This is a fundamental divorce from the World Wide Web and the Internet. I feel that a lot of people having trouble differentiating the Web from the Internet; where you’ve had one, you’ve always had the other. Don’t assume your application will always have a valid connection. When a user is on a wifi connection, or hardwired, it’s so obvious that if they’re on your website, then they must be connected to the Internet. Right? But what happens now when one of your users loads up your site or app on a mobile device, then enters a tunnel? What does it do when offline? Does it work? Maybe it doesn’t make sense if you’re offering a service that requires data from the back end, but does that mean that the front end should totally look like crap or break when the back end can’t be reached? Do your Ajax requests have error callbacks? Do you try and reconnect your WebSocket connections after they’ve failed? Do you cache previous requests or use one of the many forms of offline storage to show something to the user? Developing on the loopback is literally the best case for connectivity, but it gives the developer a false sense of how latency and connectivity issues affect their application. It’s literally shocking the first time you encounter your site/application offline if you didn’t think about the user experience up front.

Bandwidth is not free

The advent of broadband made it acceptable for sites to utilize massive amounts of assets. Seeing sites that load up so much stuff makes my heart sink when I wonder about viewing such a site on my mobile device. I only pay for so much mobile data per month, then I’m billed ridiculous amounts as a “Data Overage”. Users in other countries frequently have a more pay as you go style plan, so they’re being billed for each bit across the wire. In countries without the infrastructure necessary to get broadband Internet to every household, mobile is more prolific in getting users connected.

Things like minification and gzip certainly help, but deferred loading of assets until they’re necessary is frequently overlooked. Massive libraries are nice for devs, but may end up giving mobile users more problems than they are worth. There exist more advanced techniques such as WebSocket compression.

How much does your site weigh?

An expensive website does not make an awesome app

Why doesn’t my million dollar website make a kick ass web app?

This point is brought to you by Matt Basta. The point is that there is something fundamentally different between a web “site” and a web “app”. In a web site the usual flow involves loading up a page and maybe navigating between pages. An app more often than not will be a single page that loads data asynchronously and dynamically modifies the content displayed to the user. Some web sites make great use of things like Ajax, and are great example of single page sites. But not all are. Some still haven’t come around to loading all data asynchronously on request. And it’s not that they necessarily even have to, they can be a website and never have to be anything more. But you’ll find that some sites make better apps than others.

No chrome

Not the browser made by Google, Google Chrome; the actual controls on the top of your browser such as the back and reload buttons, and the url bar. This point comes from Chris Van Wiemeersch. One of the things you’ll find when evaluating whether a site makes a good app is whether it relies on chrome to navigate. If it does, then it’s not really going to cut it as an app. If you’re going to make a single page app, try making it fullscreen in your browser and try navigating around. Are you hindered without the chrome? One thing I found recently was an error condition where I notified the user that they had to be online to check for an update. But when I was developing, I would just refresh the page to clear the error message and try again. On a device, as an app, where there was no chrome, this meant closing and restarting the app. That sucked, so I made it so the user could click/touch, after figuring out their connectivity issues, to retry the fetch. Even better may have been to listen for online events!

Traditional forms of input are not fun

Here’s some tips from Matthew “Potch” Claypotch.

Fingers aren’t as precise as cursors

Having tiny click targets is really frustrating. How many times have you clicked the wrong thing on a mobile device? Tiny buttons are not the easiest thing for users to specify, especially when groups of them are clustered nearby. Custom buttons enabled by a little CSS can go a long way.

Typing on little keyboards in tedious

This is an effect of tiny buttons, but requiring the user to type in large strings gets annoying fast. Sometimes this can’t be avoided, but it should be when it can. Just as typing in a long, complex url to a mobile browser is not enjoyable, neither is doing so in an app.

Detect features not browser engine (User agent sniffing is a sin)

Print this and staple it to your wall above your workspace. This should be old news at this point.

Vendor prefixes are meant for browser vendors to test, not production code

I place a majority of the blame for this on vendors; prefixes should never see the light of day in release builds. It’s ridiculous to have to write four copies of the same rule, when you’re trying to express one thing. I should rewrite this sentence four different ways to prove a point. -o-Do you understand what I’m getting at? -ms-It’s almost like rambling. -moz-Repetitive department of repetition. -webkit-This is ridiculous.

But developers need to recognize the habit as an addiction, and not feed it. If you have, I forgive you. Now stop doing it.

These two particular articles are just so good, it wouldn’t do them justice to try and summarize them. Please go read them, I’ll wait. this and this

Developing towards WebKit and not HTML5 is a sin

I understand that Google Chrome is your favorite browser, and I am so happy for you; but it is not mine. I’ll be the first to admit that Google caught all of the other browser vendors with their pants down, but when I see pages that look flawless in Chrome and not so hot in others, it reminds me of days when sites only worked in IE6. Surely you remember those days. I hate when content publishers try and dictate which browser I should use to view their content. I understand WebKit based browsers dominant in mobile, but so did IE6 in desktop share at one point. It’s not unreasonable to expect users to use the most updated version of their browser, but empower your users to choose their browser. Don’t take that choice away from them.

A neat point by Robert Nyman is that WebKit itself already has forks. Can you imagine if there were eventually vendor prefixes for forks of WebKit? Continuing with vendor prefixes means that we’ll now have seven vendor prefixes: unprefixed, -moz-, -o-, -ms-, -webkit-o-, -webkit-chrome-, -webkit-safari-. Awesome! Maybe I should rewrite this sentence seven different ways to make a point!

I’m also curious if Google, Apple, and the WebKit maintainers are turning a blind eye to this, or what their opinions are? Being a vendor and wanting an open web are almost conflicts of interest; you want your browser to “win” or dominate in marketshare, but at the same time you don’t want any one browser having too much marketshare.

Design Responsively

What is responsive design? Responsive design is making a site look great on any size screen, without duplicating assets or sniffing a user agent string. Firefox has a neat web dev tool called “Responsive Design View”. It’s great for testing out your site on various screen sizes. Twitter Bootstrap is an excellent example of a framework for developing a single app that looks great on any screen size. Even if you don’t want to use a whole big framework, simple things like using CSS rules in terms of percentages instead of hard coded pixels can go a long way.

Sites that are trying to become more app like have trouble with conforming to responsive design. Instead of starting with a site and trying to figure out how to hide or not display information as the screen gets smaller, you’ll find it much easier to start small, and dynamically add content as the screen gets bigger.

High performance code respects battery life

In the end of the day, all of the code you write that runs in the browser is a set of instructions the processor can decode, not necessarily the high level JavaScript you wrote. While it’s important to avoid premature optimizations, having a few rules of thumb up front will help you write better, faster code. If the same overall action can be expressed in one instruction or one hundred, which do you think will use less power? Keep in mind that transistors leak current while switching.

Native methods over library methods, CSS over JS

What do I mean by “native methods?” Like C++? Well, yes. You see under the hood the DOM bindings that you’re calling are probably written in C++. Call toSource() on document.getElementById(). The [native code] statement in the returned string refers to the implementation. While type specialized code emitted by the JIT can match or even beat native code, you can only count on that for hot loops. In the same vein, library code is going to be slower than any code written natively. I’m not saying that you shouldn’t use libraries, just know that the use of libraries can incur some overhead. Things like animations will also be faster when handled by natively implemented CSS over JS. You can use JS to dynamically add classes to elements to get finer resolution over events, but then get the performance of CSS.

Avoid JIT bailout

The Just In Time (JIT) interpreter is a new breed of VM that most browser vendors are now using. The JIT can analyze running code, and emit native code that is faster than reinterpreting code again, and even higher-optimized code for type stable JavaScript, as long as certain “guard” conditions are met. When a guard fails, the JIT has to bailout the emitted native code and start reinterpreting code again.

Keep up to date on new APIs

HTML5 is a big spec, and is getting bigger. So big that some recommendations are being spun off from the original HTML5 spec. As an engineer, I’m painfully aware that you need to keep up in whatever industry you work in in order to stay relevant. The complacent are the most vulnerable. There’s a lot to keep track of with HTML5 and CSS3, but many new features offer higher performance methods of skinning the cat.

requestAnimationFrame

window.requestAnimation frame is a godsend for animation. Not too long ago, I wrote up a quick example of various ways of implementing animation loops and their issues; you should check it out.

indexedDB over localstorage

The indexedDB api might not be as simple as localstorage’s is, but localstorage is synchronous and is noticeably slow on mobile. If you can bite the bullet and use indexedDB, you’ll find you’re JS isn’t blocking on serializing/deserializing objects for storage. Fabrice DesrĂ© shared this with me.

WebWorkers

Webworkers can’t modify the DOM, but they can do heavy lifting without blocking the main thread.

CSS translate over absolute top and left rules

Harald Kirschner recommends CSS translates over top and left rules for absolutely positioning some elements.

Gradients are expensive

Dan Buchner notes that without beefy graphics processing units of their desktop counterparts to enable hardware acceleration, things like gradients will give you noticeable performance hits.

createDocumentFragment

Dan also suggests queuing up DOM changes. Whenever you manipulate items in the DOM, you’re going to trigger a reflow, which may consist of an update to the layout and/or a repaint. Minimizing these makes for a faster update to the DOM. For example, it can be faster to use document.createDocumentFragment and append child nodes to it, and then append that to the DOM, instead of appending lots of child nodes in between timer calls. Surprise, this isn’t actually a new DOM binding from HTML5.

Conclusion

These are just some tips I have for application developers. I am by no means an expert; I’m sure if you dig deep enough, you can find plenty of examples of my past work that contradicts some of my recommendations from this article. But I’m a little smarter today than I was yesterday, and now so are you! What are some tips that you have to share that you’ve found helpful developing for the mobile web?

C Function Pointers Alternate Syntax

| Comments

On an interview with Square, I made the mistake of stating that one of the benefits of working with JavaScript over C is that functions are first class in JavaScript, therefore they may be passed around. To which the interviewer replied, “Well, C can do that, what about function pointers?” What? Luckily, I was able to get out of that jam by guessing that JavaScript had a nicer syntax.

While I was taught some C in university, we had never gone over function pointers or more in depth topics such as static or dynamic linkage. I was so embarrassed that my expensive (read overpriced) degree had not taught me more about the C programming language, especially from the Computer Engineering department that focuses on software AND hardware. On my exit interview with the dean, I was very opinionated on the amount of C that was (or wasn’t) taught at my university. His argument was that there are only so much of so many languages you can cover in a university, which to some extent is valid. My problem has been that I’ve enjoyed learning many different programming languages, though I didn’t really get it the first time around (with Java). I think knowing many different languages and their respective paradigms makes you a better programmer in other languages, since you can bring a Ruby Way to Rust or a JavaScript functional style into C.

I had read two books in the meantime that really flushed out more of the C language to me and I would definitely recommend them to those who want to learn more about the language. They are Head First C by Dave and Dawn Griffiths and 21st Century C by Ben Klemens. I’m also aware that The C Programming Language by Brian Kernighan and Dennis Ritchie is also known as the canonical text. The book is often referred to as ‘K&R’ after the authors’ initials, and Dennis Ritchie was the original creators of the C language and co-developer of Unix. I’d love to get a chance to read it someday.

This article appeared on Hacker News and really piqued my interest. Defenitely a great read. What really stuck out to me was one of the comments though. The author of the comment mentioned a less ugly syntax for function pointers, with a link to an example. Now I’m not sure what the commenter meant by “these params decay naturally to function pointers” but I was skeptical about this different syntax. Even the Wikipedia article used the syntax that I was familiar with. So I wrote up a quick example to try it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// compiled with:
// clang -Wall -Wextra function_pointers.c -o function_pointers
#include "stdio.h"

void usual_syntax (void (*fn) (int x)) {
  puts("usual syntax start");
  fn(1);
  puts("usual syntax end");
}

void other_syntax (void fn (int x)) {
  puts("other syntax start");
  fn(2);
  puts("other syntax end");
}

void hello (int x) {
  printf("hello %d\n", x);
}

int main () {
  puts("hello world");
  usual_syntax(hello);
  other_syntax(hello);
}

Sure enough we get:

1
2
3
4
5
6
7
hello world
usual syntax start
hello 1
usual syntax end
other syntax start
hello 2
other syntax end

So the moral to the story I guess is that there’s always more to your favorite language. From using variadic macros with compound literals to enable a more functional style in C to reflecting upon a function’s number of arguments or name or adding attributes to a function or the y-combinator in JavaScript, I learn something new every day. And I hope that you did too! Thanks for reading! If you have some other recommendations on good programming books, or design patterns, please leave a comment or write a reply blog post!

[Internet] Freedom Is Not Free

| Comments

Last week, the Internet community lost a member in the on going war against the copyright industry. While I’ve never met the deceased, or even heard of the deceased before his suicide, I’m horrified. I’m horrified that the government we are asked to put so much faith in, would give someone, not that different from myself, such a ridiculous sentence. That I could be thrown away, locked away from the things that I love for 35 years, for freeing information that should have been free, and was later made free.

That my government would strike such fear into someone’s life that they would prefer death by their own hands to punishment. Why do we put up with this?

The Internet, and the technology sector evolves so quickly. It’s amazing that the law the deceased was being prosecuted under, pertaining to computers, is from 1986. Can you even remember what computers were like in 1986? I didn’t even exist! My first family computer ran Windows 95. I can only imagine how archaic laws would be that were based on such rapidly evolving tech.

The limiting of information is problematic to me. How do the people of China, Iran, and others feel about their government? I assume they are aware that the government is limiting their body of knowledge. Even the US television news agencies can’t get the story straight. It reminds me of George Orwell’s 1984, where the language is limited to curtail expression. If the free world uses the Internet as Transactive Memory, does the oppressed world know what they’re missing? Can you know what you’re missing, before you’ve lost it?

The media and copyright lobby disgust me. I’m disgusted that my former state senator is now the Chairman and CEO of the MPAA. Remember learning in high school civics the term “Revolving Door”? Case in point.

America was constitutionalized as a republic, but through amendment has evolved into a democratic republic. The idea of a republic was important to an agrarian society, and we still feel the effects every first Tuesday in November; the least convenient day of the week. Voting for someone just to represent you was convenient when your form of long-range communication was a man on a pony. With the rise of the Internet, and representatives who work for their lobbies and not the people, why do we still elect officials? Why are we a republic? Why not just a democracy? Allow voters to authenticate and cast their vote online. Everyone. No computer or internet? I’m sure your local library offers both free for public use. “But people don’t always know what’s right.” Sure, I think some people aren’t too bright. But then I see the deadlock in congress, fiscal cliff after fiscal cliff, and I can’t help but think we could do better if we just fired all of these assholes.

Why can’t the difference in viewpoints be celebrated? A good leader recognizes both sides of the coin. I love having a diverse team of people with varying backgrounds, because they come up with solutions I never could have. And if you want to beat your enemy, you have to know your enemy. That means empathizing, understanding where they come from.

If you give orders and explain nothing, you might get obedience, but
you’ll get no creativity. If you tell them your purpose, then when your
original plan is shown to be faulty, they’ll find another way to achieve
your goal. Explaining to your men doesn’t weaken their respect for you,
it proves your respect for them.

Han Tzu Shadow of the Giant Pg. 303 by Orson Scott Card

I don’t hate anyone for what they believe, nor do I try to persuade them otherwise. I just feel like the technologically minded are under represented in Washington. I wish we had a technological party. We need a party that strives to protect the internet, the ideals behind the freedom and preservation of information, the technical investment in sovereign energy and our failing infrastructure, and internet access speeds that are unrivaled in the world, not stagnated by corporations who are relatively regional monopolies. One where social issues are open to debate, but also where protecting our greatest asset and achievement is top priority. One where the media industry is invited to the table, unlike the back door policies they would try to slip in under our noses. My dad advocated a turn the other cheek policy. That’s called acting like an adult.

My belief of good vs. evil is that there is no good or evil, but that people are inherently selfish. They do things that are perceived by others as evil. But they don’t do things because those actions are evil, they do them because they gain some form of personal utility from the action; they perceive the action as good. And it is good…to them. It’s easy to be evil. It’s the easy way out. It’s harder to think about other people. It’s tougher to do the right thing. Being good is so recognizably hard; it’s impressive.

The president of MIT, L. Rafael Reif, had this to say regarding the deceased: “It pains me to think that MIT played any role in a series of events that have ended in tragedy…” Fuck you. Maybe if MIT’s bottom line wasn’t their acceptance rate, they might be able to look out for more than just their own.

All that is necessary for the triumph of evil is that good men do
nothing.

Edmund Burke Thoughts on the Cause of Present Discontents

Suicide is never the answer. No matter how shitty your current situation is, no matter if things will never go back to the way they were, you will always be able to change your situation. Maybe not immediately, but that’s what goals are for. Anyone who ever committed suicide to prove a point could have done more for their cause dedicating the rest of their life to it. If you’re feeling depressed, talk to someone. It will make you feel so much better to talk to someone about what’s upsetting you. As much as people like to shit on the Catholic Church, I feel like the Catholic practice of penance (confession), provides a cathartic placebo effect. If you are depressed or hurting, and you need someone to talk to, even a complete stranger, feel free to contact me. I will always provide an ear and a shoulder.

It seems strange that my life should end in such a terrible place, but
for three years I had roses and apologized to no one. I shall die here.
Every inch of me shall perish. Every inch, but one. An inch. It is small
and it is fragile and it is the only thing in the world worth having. We
must never lose it or give it away. We must NEVER let them take it from
us. I hope that whoever you are, you escape this place. I hope that the
world turns, and that things get better. But what I hope most of all is
that you understand what I mean when I tell you that, even though I do
not know you, and even though I may never meet you, laugh with you, cry
with you, or kiss you, I love you. With all my heart, I love you.

Valerie V for Vendetta

The next time the media industry tries to limit what you have access to on the Internet, make a big ruckus. Inform everyone you know about the facts. Pushing for an increase in media piracy activities is not the right answer. Instead we should push to boycott working for organizations like the RIAA and MPAA and their ilk. Think about how much better off we would be in the United States if teachers were paid like rock stars and rock stars were paid like teachers? Instead, everyone in the media industry needs a fat paycheck. Celebrity is the case in point of the blind leading the blind. Did you know that EMI owns the copyright to the footage of Martin Luther King’s “I have a dream” speech? If you can find it, I bet it wont be up long. Frankly, I’m surprised EMI doesn’t also own the Declaration of Independence and Constitution, charging admission.

Revolutions are a continuation of the battle between sword and shield. Something new is created and shows potential, then doubters pop up seeking to curtail that which upsets their competitive edge. In the case of information, many make money and become powerful off limiting the access to knowledge. I think all knowledge that is beneficial to mankind should be open, and that the Internet is the ultimate utility for the sharing of our collective knowledge. Where do you draw the line, you might ask? I think the knowledge required to make atomic weapons and 3D-print receivers is decidedly unbefitting of society, for instance. And in the end, you can’t take any of the knowledge you protect with you. If everyone shared what they knew, then you’d have a more improved life, since then the right people would be in the know to advance our being. Technology would advance even faster than it does currently if we weren’t limited to tick-tock product cycles and business secrets.

So what does a rant about government, antiquated laws, corrupt representatives, celebrating diversity, hypothetical political parties, inaction, and established industries have to do with anything? They’re all anchored to a suicide. They’re all that’s been running through my mind lately. What I see in the deceased, I see in myself. Standing amongst my peers, celebrating Internet Freedom Day , listening to Peter Eckersley of the EFF talk, I realized ‘The power is yours!’. So now I add my voice to the or so 20 Internet activists that will continue to spring up as one falls.

What will you do to shape the world you live in? What are you going to do to fix it? If you don’t, I will. Because if you want something done right, you have to do it yourself.

It has to start somewhere It has to start sometime
What better place than here, what better time than now?

Rage Against the Machine Guerrilla Radio

Closures: JavaScript, Ruby, and Rust

| Comments

It’s all about closures. Understanding scope is paramount to coding. What can you access and what can’t you access. Closures allow us to access variables that otherwise might be awkward to pass into a function. Closures can help us out of tricky situations, but can confuse those from backgrounds with (typically) statically typed languages that may not support closing over variables.

Rust is an up and coming systems level programming language being developed at Mozilla. Let’s take a look at the syntax of closures in Rust, but first let’s see how closures are implemented in some other, more popular languages.

In JavaScript, closures are super common. Here’s a simple example.

1
2
3
4
5
6
7
var x = 5;

function myClosure (y) {
  return x + 1;
};

console.log(myClosure(10)); // 6

JavaScript has function scope; the definition of a new function creates a new scope. But if a reference to an identifier is not found within the local scope, the next outer scope is consulted and so on until it is either found, or a ReferenceError is raised. We could prevent this for example by shadowing the variable name by naming it in the parameter list:

1
2
3
4
5
6
7
var x = 5;

function myClosure (x) {
  return x + 1;
};

console.log(myClosure(10)); // 11

Notice how in the above snippet, we cannot close over the outer x? This is called variable shadowing. In JavaScript, no matter if you use a function definition or function expression to define a function, as long as you do not shadow a particular variable, then you may close over it.

Let’s see how Ruby handles closures.

1
2
3
4
5
6
7
x = 5

def my_closure y
  x + 1
end

puts my_closure 10 # NameError: undefined local variable or method `x' for main:Object

Oops. Looks like Ruby doesn’t support closures! But I thought it was supposed to be easier to write than Java! Well, it turns out Ruby does support closures, it just has an alternate syntax for functions that close over references to variables in the outer scope. This alternate syntax actually creates a new object containing the captured scope. Lets take advantage of Ruby’s lambdas to close over variables:

1
2
3
4
5
6
7
x = 5

my_closure = -> x do
  x + 1
end

puts my_closure.call 10 # 6

Note, we could have also used the older lambda syntax, or even a Proc object. I won’t cover the difference between the two here; there are better blog posts on the differences. My point is that not all languages support closures with their default function declaration syntax (like in JavaScript). This provides a nice syntax into closures in Rust.

1
2
3
4
5
6
7
8
9
fn main () {
  let x: int = 5;

  let my_closure = |_: int| -> int {
    x + 1
  };

  io::println(fmt!("%d",my_closure(10))); // 6
}

Note: Rust has some really nice type inference. We can write the previous snippet more succinctly:

1
2
3
4
5
6
7
8
9
10
11
fn main () {
  //let x: int = 5;
  let x = 5;

  //let my_closure = |_: int| -> int {
  let my_closure = |_| {
    x + 1
  };

  io::println(fmt!("%?",my_closure(10))); // 6
}

It might seem obvious that my point about different languages having different syntaxes. I guess a better stating of that point is that closure definitions in Rust differ from vanilla function definitions like Ruby and as opposed to JavaScript.

Rust aims to be a systems level programming language to replace C and C++. With closures, type inference, and a syntax that faintly reminds me of Ruby’s block lambda syntax, I’ll take it!