C#

Screen shot of my galaxy generator in action

Screen shot of my galaxy generator in action

I’ve been developing stuff with Unity in my spare time for something like eight years (I started at around v1.5). I was initially drawn in by its alleged Javascript support. Indeed, I like Unityscript so much, I defended it vocally against charges that using C# is better, and wrote this article to help others avoid some of my early stumbles. I also contributed significant improvements to JSONParse — although the fact that you need a JSON module for Unityscript tells you something about just how unlike Javascript it really is.

I’m a pretty hardcore Javascript coder these days. I’ve learned several frameworks, written ad unit code that runs pretty much flawlessly on billions of computers every day (or used to — I don’t know what’s going on with my former employers), created a simple framework from scratch, helped develop a second framework from scratch (sorry, can’t link to it yet), built services using node.js and phantom.js, built workflow automation tools in javascript for Adobe Creative Suite and Cheetah 3D, and even written a desktop application with node-webkit.

The problem with Unityscript is that it’s not really Javascript, and the more I use it, the more the differences irk me.

Anyway, one evening in 2012 I wrote a procedural galaxy generator using barebones Javascript. When I say barebones, I mean that I didn’t use any third-party libraries (I’d had a conversation with my esteemed colleague Josiah Ulfers about the awfulness of jQuery’s iterators some time earlier and so I went off on a tangent and implemented my own iteration library for fun that same evening).

Now, this isn’t about the content or knowledge that goes into the star system generator itself. It’s basic physics and astrophysics, a bit of googling for things like the mathematics of log spirals, and finding Knuth’s algorithm for generating gaussian random distributions. Bear in mind that some of this stuff I know by heart, some of it I had googled in an idle moment some time earlier, and some of it I simply looked up on the spot. I’m talking about the time it takes to turn an algorithm into working code.

So the benchmark is: coding the whole thing, from scratch, in one long evening, using Javascript.

Now, the time it took to port it into Unityscript — NaN. Abandoned after two evenings.

I’m about halfway through porting this stuff to C# (in Unity), and so far I’ve devoted part of an afternoon and part of an evening. Now bear in mind that with C# I am using the Mono project’s buggy auto-completing editor, which is probably a slight productivity win versus using a solid text editor with no autocomplete for Javascript (and Unityscript). Also note that I am far from fluent as a C# programmer.

So far here are my impressions of C# versus Javascript.

C#’s data structures and types are a huge pain. Consider this method in my PNRG class (which wraps a MersenneTwister implementation I found somewhere in a far more convenient API):

// return a value in [min,max]
public float RealRange( double min, double max ){
    return (float)(mt.genrand_real1 () * (max - min) + min);
}

I need to cast the double (that results from mt.genrand_real1 ()). What I’d really like to do is pick a floating point format and just use it everywhere, but it’s impossible. Some things talk floats, others talk double, and of course there are uints and ints, which must also be cast to and fro. Now I’m sure there are bugs caused by, for example, passing signed integers into code that expects unsigned, but seriously. It doesn’t help that the Mono compiler generates cryptic error messages (not even telling you, for example, what it is that’s not the right type).

How about some simple data declarations:

Javascript:

var stellarTypes = {
    "O": {
        luminosity: 5E+5,
        color = 'rgb(192,128,255)',
        planets = [0,3]
    },
    ...
};

C#:

public static Dictionary<string, StellarType> stellarTypes = new Dictionary<string, StellarType> {
    {"O", new StellarType(){
        luminosity = 50000F,
        color = new Color(0.75F,0.5F,1.0F),
        minPlanets = 0, 
        maxPlanets = 3
    }},
    ...
};

Off-topic, here’s a handy mnemonic — Oh Be A Fine Girl Kiss Me (Right Now Smack). Although I think that R and N are now referred to as C-R and C-N and have been joined by C-H and C-J so we probably need a replacement.

Note that the C# version requires the StellarType class to be defined appropriately (I could have simply used a dictionary of dictionaries or something, but the declaration gets uglier fast, and it’s pretty damn ugly as it is. I also need use the System.Collections.Generic namespace (that took me a while to figure out — I thought that by using System.Collections I would get System.Collections.Generic for free).

Now I don’t want to pile on C#. I actually like it a lot as a language (although I prefer Objective-C so far). It’s a shame it doesn’t have some obvious syntax sugar (e.g. public static auto or something to avoid typing the same damn type twice) and that its literal notation is so damn ugly.

Another especially annoying declaration pattern is public int foo { get; private set; } — note the lack of terminal semicolon, and the fact that it’s public/private. And note that this should probably be the single most common declaration pattern in C#, so it really should be the easiest one to write. Why not public int foo { get; }? (You shouldn’t need set at all — you have direct internal access to the member.)

I’m also a tad puzzled as to why I can’t declare static variables inside methods (I thought I might be doing it wrong, but this explanation argues it’s a design choice — but I don’t see how a static method variable would or should be different from an instance variable, only scoped to the method. So, instead I’m using private member variables which need to be carefully commented. How is this better?

So in a nutshell, I need to port the following code from Javascript to C#:

  • astrophysics.js — done
  • badwords.js — done; simple code to identify randomly generated names containing bad words and eliminate them
  • iter.js — C# has pretty good built-in iterators (and I don’t need most of the iterators I wrote) so I can likely skip this
  • mersenne_twister — done; replaced this with a different MT implementation in C#; tests written
  • planet.js — I’ve refactored part of this into the Astrophysics module; the rest will be in the Star System generator
  • pnrg.js — done; tests written; actually works better and simpler in C# than Javascript (aside from an hour spent banging my head against weird casting issues)
  • star.js — this is the galaxy generator (it’s actually quite simple) — it basically produces a random collection of stars offset from a log spiral using a gaussian distribution.
  • utils.js — random stuff like a string capitalizer, roman numeral generator, and object-to-HTML renderer; will probably go into Astrophysics or be skipped

Once I’ve gotten the darn thing working, I’ll package up a web demo. (When Unity 5 Pro ships I should be able to put up a pure HTML version, which will bring us full circle.) Eventually it will serve as the content foundation for Project Weasel and possibly a new version of Manta.

DuckDuckGo vs. Google

DuckDuckGo Bang!

I think it’s safe to say that DuckDuckGo is not quite as good as Google when it comes to search. But it’s not bad at all.

But it’s a lot cleverer than Google. It’s almost as though, rather than working on cloning Facebook, making creepy glasses, or trying to beat Apple by acquihiring a bunch of ex-Apple guys they’ve actually been trying to make a better search engine. To begin with, if you set DDG as your default search engine (on Safari this actually means installing an extension, since Apple doesn’t let you add it the obvious way) your address bar becomes a command line, with special (and very convenient) commands.

For example, if you want to use Google, you simply prefix your search with !g. So there’s that. If you want to use Bing, you can use !b, and !i for Google Image search. If you want to search for something on Amazon it’s !a. Stackoverflow !so. That’s actually enough — right now, DDG wins. Here’s a link to all the bang commands.

Now of course the main argument for DuckDuckGo is that it makes its money comparatively honestly by selling search terms without tracking its users. Well, it claims not to track its users, but even if it does it’s probably advantageous to not have your email, searches, and ad-clicks all being tracked by one entity, right? At least make them work for a living.

Dropbox vs. Box vs. HubiC

Edit: Brain Fart — I seem to have omitted about a paragraph of pertinent information.

I’ll assume you all know what Dropbox is. If you don’t, go get Dropbox now. It’s free and it’s awesome.

The only downside of Dropbox is that if you want more than the 2GB of storage you get for free, it gets more expensive, and the upper limit on how much you can store is (for practical purposes) quite low. Personally, I haven’t found either of these an issue — but thanks to my link on opensourcemac.com, I have a pretty huge “free” account. But it would be awesome to have something like Dropbox that was so big I could just stop managing what I keep on it altogether (of course, this is the problem with stuff that’s free — you waste it).

Box.com has been around about as long as Dropbox (heck, it has an even better domain name, right?) but has been targeted at the enterprise.

hubiC.com (their capitalization) I just found out about via Hacker News. It offers more free storage than Dropbox, but not quite as much as Box, and vastly cheaper paid plans, including about $140/year for 10TB. (I’m not sure how you can actually get 10TB into it, short of using a ZFS or Drobo style multi-disk volume.)

2GB vs 50GB vs 25GB

This is how much storage you get for free.

$100/year for 100GB vs. $10/month for 100GB vs. $13.60/year for 100GB (or $136/month for 10TB)

Edit: I’ve corrected the costs for HubiC.

This is how much it costs for more storage. Box gives you — by far — the most free storage but gets more expensive than Dropbox (while offering various enterprisey features). HubiC is insanely cheaper than both of them. By way of comparison, iCloud costs $20/year for 20GB, so in terms of dollars per unit storage, only HubiC is a better deal. In terms of useful features out of the box, Dropbox support is built into far more programs while iCloud offers useful functionality (notably over-the-air backups of devices and integration with Apple products) to Mac and iOS users that no other platform can (currently) match.

For Android users, the iCloud equivalent is Google Drive, which gives you 15GB free, and costs $60/year for 100GB, making it a bit cheaper (and less useful) than Dropbox.

Mac OS X Integration

All three programs appear as folders in your home directory by default, and stick shortcuts to themselves in Finder’s sidebar. Having installed HubiC and then Box after installing Dropbox, Box was very flaky when first installed. Its installer provided no feedback, and the first few times I tried to launch the application nothing seemed to happen, followed by weird broken delayed launches. Once I’d patiently killed a bunch of Box.app instances and started over it worked well.

Box and Dropbox have similar levels of Finder integration — they indicate the state of files and provide context menu items for sharing links. HubiC appears not to do anything like this, unfortunately.

All three applications provide status menus — those icons that appear in the menubar to the left of the Spotlight magnifying glass. I should note that HubiC’s icon looks like a shapeless blue blob — a blue cloud? — which is an anti-feature. The status menus of all three seem to be perfectly fine and offer decent functionality. Oddly enough, Box and Dropbox no longer keep you apprised of your usage level whereas HubiC does.

Box has one glaring defect — it won’t sync Mac OS X “bundles” (i.e. directories masquerading as files). I have no idea why — they’re just directories. It tells you to zip them up first (gee, how about doing it yourself?)

All three services offer support for all the usual platforms — although I can’t comment on how good any of them are (except the Dropbox client for iOS is decent, and all three work decently in a web browser, although HubiC’s in-browser account management is awful). I cannot yet comment on the security of Box or HubiC. Dropbox offers, and I use, two-factor authentication, and I’m pretty sure HubiC does not (but its website is pretty hard to navigate so maybe it’s there somewhere).

Conclusion

If you just want some free storage and don’t mind not being able to sync bundles then Box is a better deal than Dropbox and it’s probably quite robust given the money behind it. If you’re already using Dropbox and don’t need more storage, Box does not work as well so unless you want its enterprisey features (and you know who you are) you might as well stick with Dropbox. I can’t really comment on HubiC until I’ve exercised it by, saying syncing a buttload of RAW files to it (if I’m going to get more cloud storage, I want enough of it to not need more than one service). If you’re interested, HubiC is a damn good deal for free and it works side-by-side with the others. If it turns out to deliver the goods, I may well end up buying a 10TB plan and switching to it from Crashplan.

The Worst Recurring TV Show Plot Ever

There was an interesting story in the New Yorker (Person of Interest, the TV show that predicted Edward Snowden) that got me watching a show I had initially dismissed (I think because it was marketed as a J.J. Abrams show). It’s got the guy who played Ben in Lost — who’s an excellent actor, even if I’d like to do terrible things to the creators of Lost with a fork.

The basic premise of Person of Interest is that in the wake of “9/11″, the US security apparatus started doing exactly what anyone with a clue knew they were doing and Snowden later revealed they were in fact doing and that a billionaire hacker genius (Ben… er Finch) wrote software to analyze all the data and spit out “persons of interest” — i.e. people planning future terror plots. The wrinkle is that the software initially couldn’t differentiate between people plotting terror attacks and those plotting ordinary violent crimes, so the hacker figured out how to divide its hits into “relevant” (to national security) and “not relevant” (i.e. ordinary criminals). For some reason the non-relevant hits are always in New York, but I digress. The billionaire feels guilty about all the non-relevant people who keep dying, and tries to save them (with the help of an improbably effective ex-CIA agent).

I mention all this by way of diversion. The show is exceptionally well-made, cleverly understated, and intelligent. So it’s with considerable annoyance that — watching through season 1 on iTunes — I stumbled into the worst recurring TV show plot ever. OK, there are probably worse recurring TV show plots, but this one is egregious and not worthy of an intelligent TV show such as Person of Interest. The summary goes like this (not a spoiler — this plot cannot be spoiled):

  1. People are getting killed mysteriously.
  2. A drug company is involved.
  3. And it turns out they’re suppressing information that lots of people died horribly during the clinical trial of a drug they’re just about to release.

I think I’ve seen this plot in pretty much every episodic cop show on television, and a bunch of lawyer and doctor shows too. My memory is hazy, but I’m pretty sure it’s occurred in The Good Wife, Law and Order (and perhaps Criminal Intent as well), Bones, etc. Shows that are generally  intelligently written, well-acted, and strongly plotted. (OK, Bones has kind of jumped the shark.)

Yes, drug companies do evil things. Yes, they’re motivated by profit. But the way to make a buttload of money as a drug company is not — repeat not — to produce a drug that kills people, cover up the deaths, and then release the drug.

Now, if the bad guy were a stock market speculator who wanted to make sure a particular drug got released because he/she had some kind of weird futures contract, or was shorting a rival pharmaceutical company, or something like that — OK, that’s kind of barely plausible. But to knowingly release a drug that will get your company sued to oblivion is simply stupid.

Now there are cases of drug companies covering up deaths caused by their drugs. A recent example which got a lot of coverage is the story of acetaminophen overdoses caused by (a)  the drug being lethal at doses as low as double the maximum recommended daily dose, (b) confusion caused by infant tylenol being twice as concentrated as children’s tylenol, and (c) the presence of tylenol in many, many “cocktail” drugs that are frequently taken together. An older example I recall is a drug used to help smokers quit that was associated with a notable, but statistically insignificant, number of sudden deaths. There was also some controversy over Prozac being prescribed for kids and possibly leading to suicide. And of course there’s Vioxx. But these are all drugs that were already on the market, and the cover-ups and maneuverings were over marketing issues (can we call our drug “the safest”? or will the government put our drug on a list of drugs covered by public insurance?). This is about protecting markets and avoiding lawsuits.

Please. Enough.

Here’s an evil thing Big Pharma actually does (and the only TV show I know of that nailed this was House M.D.):

  1. Create a drug that’s just like a drug you already sell which is going out of patent (but “with a vitamin E molecule tacked on the side” to paraphrase House from memory)
  2. Conduct many clinical trials of your new drug vs. the old drug and placebo
  3. Assuming the new drug is exactly as effective as the old drug and the trials are conducted by perfectly by disinterested parties, one in twenty will show the new drug is more effective than the old drug — publish only those results (journals have a strong bias against publishing studies with no statistically significant result, so it’s not like you even need to work hard to suppress the null findings)
  4. Market the hell out of the new drug (e.g. bribe doctors to prescribe or recommend it, scare patients into demanding it)

But that probably won’t create a grisly trail of corpses for your investigators to discover.

AppleTV

Yesterday, 9to5 Mac noticed that Apple had rejigged its online store so as to position AppleTV as a product category. Also interestingly, Lee Clow has apparently hinted that, for the first time since 1984, Apple may be airing a super bowl spot. And then during Apple’s first quarter earnings call, Tim Cook foreshadowed new product categories for 2014. We’ve also had rumors of Apple cutting content deals over the last year that never turned into announcements.

It seems pretty clear that one new product category is going to be AppleTV. And here’s where things get really interesting.

Facts

  • Apple’s online store now treats AppleTV as a product category rather than an accessory.
  • Apple is not currently selling an Apple-branded 4K display (the 4K displays it is selling are from Sharp)
  • Apple’s OS-level support for 4K displays is conspicuously poor (they need to be treated as Retina displays)
  • iOS now provides proper (API) support for bluetooth game controllers
  • The price for high quality 4K displays is about to drop well under $1000
  • The current AppleTV does not support 4K displays
  • The current AppleTV does not support 802.11ac

Opinions

  • The last crop of consoles (Xbox One, PS4, Wii U) had the most anemic rollout (in terms of launch titles) in recent memory
  • The way AppleTV’s remote app works is primitive compared to the way Chromecast can be “handed” a playback task (and Apple knows this)
  • AppleTV currently needs a system update in order to add a new content channel; the tools for managing “apps” in AppleTV are primitive to put it mildly
  • There is already an ecosystem of iOS-compatible controllers and iOS games supporting those controllers
  • 4K displays blur or even erase the line between monitors and TVs

Rumors

  • Apple has bought a Super Bowl spot
  • Nintendo has suggested it is looking at developing titles for mobile platforms
  • Apple has been negotiating content deals with major players (movie studios, etc.) but it has borne no visible fruit as yet

Predictions

  • Apple is at last going to release an AppleTV console (whether it’s called AppleTV or not remains to be seen)
    • It will have access to major new sources of content
    • It will have an App Store
    • It will support Bluetooth controllers
    • It will support the use of other iOS devices as controllers
    • It will be powered by the A7 or something more powerful
    • If it is powered by a new chip (e.g. “A7x”) it will support 4K (the A7 can drive 2K)
    • It will have a shockingly good set of launch titles (how else to explain the lackluster launch titles for all the other consoles?)
    • It will not have a tuner or Cablecard support or any other horrific kludge
    • It may introduce streaming video with ads for content from networks (effectively on-demand playback of licensed content with ads)
    • It will cost $199-399 (I’d predict $199, but Apple might actually sell a range of products with varying storage capacities)
    • The ghastly Apple Remote iOS app will be given a proper overhaul, and work in more of a peer-to-peer manner (and be able to hand off tasks to the AppleTV)
  • An even smaller $99 version which doesn’t play games might continue as AppleTV Nano or some such
  • We’re going to see extensive 4K support across Apple’s product lines over the next 12 months
  • We’re going to see Apple-branded 4K displays (“Retina HD” perhaps?) designed to work seamlessly with all this new stuff