Pandas merge woes on MultiIndex, solved

July 3rd, 2014

Perhaps you are data munging in Python, using “pandas”, and you attempt to use DataFrame.merge() in order to put two DataFrames together.

“cannot join with no level specified and no overlapping names”

This happens when you have two DataFrames with one having a MultiIndex type, which *could* play nice together (e.g. you have “year, month” on the left, and “year” on the right, *but do not have names set.*

You’ll need to explicitly set names with

leftdf.index.levels[0].name = “onename”
leftdf.index.levels[1].name = “twoname”
rightdf.index.levels[0].name = “onename”

Alternatively, you can make it work if you reindex the right-hand side by the left hand side:

rightdf2 = rightdf.reindex(index=leftdf.index, level=0) ## NOTE Assignment, does not modify rightdf in-place

CHCBP-013 describes unlimited former spouse coverage under CHCBP

April 8th, 2014

(This is extremely specialized subject material. If you found it while searching, you probably understand this, but if you’re just a curious reader, you might want to skip it.)

The Continued Health Care Benefit Program is analogous to COBRA for former TRICARE-covered persons; it is mostly a transitional way to get TRICARE-like (TRICARE less military facilities) benefits self-paid after one ceases to be eligible for TRICARE itself.

Generally the CHCBP eligibility period is limited. However, in the case of former spouses of servicemembers who have not remarried before age 55, it is possible to qualify for unlimited (lifetime) eligibility. This is obvious from law and from published stuff (e.g. continuing legal education materials for the tiny subset of lawyers for whose clients this is a very important topic), but it is nearly impossible to get anything from the “horse’s mouth,” that is, the actual CHCBP plan administrator, which is Humana Military Healthcare Services (Humana Military).

If you call Humana Military at 1-800-444-5445 and ask for the rules regarding former spouse unlimited eligibility, they will punt and tell you it’s something that is decided only at the point at which the normal 3-year eligibility has expired. If you persist and ask how it’s decided, they’ll tell you that there is a questionnaire which is sent, but that they don’t have access to it and can’t send a copy. If, incredulous, you insist that some person, perhaps that person’s manager, does in fact know where the questionnaire is, since it’s obviously already written and gets sent out to people all the time, you will get transferred to a kindly manager who takes your FAX number and swears up and down that they’ll send it to you tomorrow morning since the office is about to close.

If you’re a real ornery gadfly, though, and you’re ready to start writing letters to your congressman etc., you might try sending a letter to Humana Military asking for this information and documenting your attempts to get it and the promises which were made and unfulfilled about sending it to you before. If you do all this, they will mail you a redacted copy of an actual form CHCBP-13, which had been sent to an actual former spouse whose eligibility was expiring. (Maybe, in fact, the first representative was truthful and this is not a document that they have ready, and they write up a new one every time and so the only way to send it out is to take the latest one and redact the policyholder’s personal info. I doubt it.) (For this courtesy I am grateful, O unnamed mail-replier at Humana Military, but the policy of keeping this information completely off the public Web is either backwards or sinister.)

Note that the operative requirements are:

1. A “signed statement of assurance that you have not remarried before the age of 55.”
2. Proof (the standard of which is left to the imagination) that you were “enrolled in, or covered by, an approved health benefits plan under Chapter 55, Title 10, United States Code as the dependent of a retiree at any time during the 18-month period before the date of the divorce, dissolution, or annulment (Both TRICARE and CHCPB would qualify as such a plan).” [sic — Humana’s language implies that the enrolee must have been a dependent of a “retiree” but the actual language of 10 USC 55 sec. 1078a (b) (3) talks about a “member or former member” of the armed forces]
3. “A copy of the final divorce decree or other authoritative evidence” that you are actually receiving or have a court order to receive part of the retired or retainer pay of the service member, or have a written agreement that the service member will elect to provide you an annuity. [DO NOT rely on this nor on Humana’s exact language, for this, get your ducks in a row with the statute etc. — it’s slightly complicated.]
4. The executed (signed) renewal notice page of CHCBP-013 and a check for the next premium payable to “United States Treasury.”

Given that this is a hugely important item to a few (but maybe not all that few) people out there, and that it related to the execution of very clear federal law, I’m rather shocked that there’s no mention ***anywhere on the Internet prior to today(!!!)*** of CHCBP-013 and its contents and requirements.

So, with no further ado, I present you a redacted copy of form letter CHCBP-13, which shows the actual procedural requirements for obtaining unlimited former spouse CHCBP coverage.

Django auto_now types wreck get_or_create functionality

February 11th, 2014

I recently had occasion to lazily use the Django “get_or_create” convenience method to instantiate some database ORM records. This worked fine the first time through, and I didn’t have to write the tedious “query, check, then insert” rigamarole. So far so good. These were new records so the “or_create” part was operative.

Then, while actually testing the “get_” part by running over the same input dataset, I noticed it was nearly as slow as the INSERTs, even though it should have been doing indexed SELECTs over a modest, in-memory table. Odd. I checked the debug output from Django and discovered that get_or_create was invoking UPDATE calls.

The only field it was updating was:

updated_at = models.DateTimeField(auto_now=True)

Thanks, Django. You just created a tautological truth. It was updated at that datetime because … you updated it at that datetime.

Interestingly, its sister field did NOT get updated:

created_at = models.DateTimeField(auto_now_add=True, editable=False)

This field, true to its args, was not editable, even by whatever evil gnome was going around editing the updated_at field.

Recommendation: if you want actual timestamps in your database, why don’t you use a real database and put a trigger on it? ORM-layer nonsense is a surefire way to have everything FUBAR as soon as someone drops to raw SQL for performance or clarity.

Don’t Bother with S3FS for Mounting Amazon S3 on Mac OS X (2014)

January 24th, 2014

As of January 2014, it’s not worth bothering with the “s3fs” software for mounting Amazon S3 buckets on your local filesystem.

The idea of s3fs is simple and great: use FUSE (Filesystem in Userspace) to “mount” the S3 bucket the same way you’d mount, say, an NFS drive or a partition of a disk. Manipulate the files, let s3fs sync it in the background. Sure, you lose some reliability, but we’ve had NFS and SMB and all kinds of somewhat-latent-over-an-unreliable-link-but-mostly-with-filesystem-semantics software for decades now, right?

Well, forget it. s3fs as of January 2014, used on Mac OS X and against an existing set of buckets, is so utterly unreliable as to be useless.

First, s3fs cannot “see” existing folders. This is because folders are a bit of hack on S3 and weren’t done in a standardized, documented way when s3fs was first written. However, since then, at least two other ways of creating folders on S3 have gained currency: an older, deprecated way with Firefox plugin S3Fox, and a newer defacto standard way with Amazon’s own management dashboard/browser for S3. Whatever the historical reason, you can’t see the existing folders.

Second, although from mailing list posts, theoretically you can *create* an s3fs folder with the same name as your existing folder, and then its contents will magically become visible, empirically something rather different happens. A mkdir on the s3fs mount leads to the creation of a mangled *regular* file on the S3 dashboard. Now you have two “folders,” each of which is unusable as a folder on the other (S3 dashboard, or s3fs) system. Argh.

Finally, you might say, ok, fine, this will just make me use flat-level, non-folder-nested choices about my S3 architecture. (Leave aside for the moment that the very reason you want to use S3 is probably exactly so that you can have lots and lots and lots and lots (like 10^8+) files in a way that will cripple any reasonable filesystem tools that see them all in one “directory.”) However, even that doesn’t work reliably, as s3fs demonstrated today when it went into “write-only mode” such that I could create files locally that would show up on S3 but that subsequently would disappear from my local filesystem. WTF?!?

The unfortunate answer is: S3 is not a filesystem, and it was created by people who are smarter than you, and who have very craftily calculated that if you are forced to weave in the S3 API and its limitations into your application code, you will have a damn hard time ripping it out of your infrastructure, and so they are going to have you do just that. They do not want it to be used as a filesystem, and so guess what: you are *not* going to use it as a filesystem. Not gonna happen.

Say what you will, but our hometown heroes here in Seattle are no dummies. Embrace, extend, extinguish, baby. Not just for OS companies anymore…

(Yes, I know that s3fs is not an Amazon project. But it appears to be the community’s best attempt to put filesystem semantics around S3, and that attempt has been rejected by AWS’s immune system.)

Never Trust Microsoft Products On Mac OS X, Again

January 24th, 2014

Something in OS X 10.7+ and MS Office 2008 for Mac has made the entire Office suite, apparently, stop respecting symlinks.

I know that Windows took until well into the 21st century to really deal with symlinks even halfway, but come on. It worked before. There are some directories into which I routinely save document files which are literally not reachable by click navigtation any other way but through symlinks.

If you click on the symlink in the “Save” dialog, it will change the name of the file you’re saving to the name of the symlink and generally fail all over itself.

Never Trust Microsoft Products On Mac OS X

August 26th, 2013

In Microsoft Word 2008 for Mac OS X, if you open a “Find” dialog, and if it has focus, it will capture cmd-S (the universal “Save” command) and cause it to toggle the “sounds like” option in advanced find options. It will sort of capture cmd-W (the universal “close Window,” which will close the Find dialog). It will not capture cmd-Q (the universal “Quit”), which will quit the program and close all its windows, assuming your document has been saved.

Which you thought you’d been doing by hitting cmd-S. And then you wonder why your search results were so weird.

Thanks again, Mac BU!

LinkedIn CPC Ads behaving weirdly

July 30th, 2013

This June/July, over at SimpleVerity, we’ve been running some very tiny, super-targeted CPC ad campaigns on LinkedIn to recruit trial users of our system. We’ve noticed the following odd behaviors, and I wanted to ask the Web if anyone else had seen this:

– Lower bids (bottom of the range) outperform higher bids on both CPC and conversion (learn more form on my landing page). Weird, but perhaps explicable; it could be that for our particular appeal, the “lower ranked” ad slots work better.

– Temporary “spike” in CPC, and BIG spike in conversion, right after a change to the campaign configuration. This is strange, because it seems to result not only in a change in how the LinkedIn users react (could be a result of the ad rotation algorithms after a change), but also how they behave once they get to my landing page. No theory for how this works.

– Auto-Optimize among campaigns seems to prematurely start making optimization decisions before reaching anything close to statistical significance. For example, I was running a campaign where the long-term equilibrium average CTR seemed to be about 0.9% (not bad, right?). I had 15 variations running. However, the auto-optimize algorithm started heavily favoring a few ads before all variations had received even 1,000 impressions. That’s just crazy; the ads being disfavored were about 50/50 bets at that point to exceed the average, yet the algorithm was “optimizing” them into oblivion.

My takeaway is that, at least when working with heavily targeted LinkedIn CPC ads, you have to stay very, very close to the “metal” and pay attention to oddities. Don’t assume that paying the highest bid (or even paying more than the bare minimum CPC price) will work better; relentlessly experiment with spend and bid. Also, don’t let auto-optimize kick in until you are comfortable that you are approaching significance on the expected CTR (at the very least, the CTR that you are hoping to “beat”).

TrueCrypt breaks after OS X 10.8 (Mountain Lion) upgrade

July 8th, 2013

1. You run TrueCrypt as before, and once you finally remember your passphrase and type it correctly, you get an error: “the MacFUSE file system is not available (71)”

2. You look around and you still have /usr/local/lib/*fuse*.so etc., in addition to /Library/Filesystems/fusefs.fs

3. Your MacFuse control panel in System Preferences still exists (but the “uninstall” button doesn’t seem to work!). Also, the script which that button runs, /Library/Filesystems/fusefs.fs/Support/uninstall-macfuse-core.sh — that doesn’t work either (run with sudo).

4. You’ve tried installing “fuse4x” and “fuse4x-kext” from MacPorts, but still nothing.

What I did:

1. Remove MacFUSE manually, completely, using the list of installed files at http://code.google.com/p/macfuse/wiki/FAQ

MacFUSE file system bundle (/Library/Filesystems/fusefs.fs)
MacFUSE Objective-C framework (/Library/Frameworks/MacFUSE.framework)
MacFUSE C-based libraries (/usr/local/lib/*fuse*.dylib) and headers (/usr/local/include/fuse*)
MacFUSE preference pane (/Library/PreferencePanes/MacFUSE.prefPane)
MacFUSE project templates for Xcode (/Library/Application Support/Developer/Shared/Xcode/Project Templates/MacFUSE)
2. Remove /Applications/TrueCrypt.app

3. port uninstall fuse4x and fuse4x-kext

4. Reboot. (Might not be necessary but can’t hurt here.)

5. port install fuse4x fuse4x-kext

6. Reinstall truecrypt (you might need to option-right-click to bypass the security check). Note that installing truecrypt, I believe, re-links the TC binary against the fuse libraries that you just re-installed using MacPorts, so you end up with a different TC binary than before.

7. Run TrueCrypt.app again and hope that it all worked…

5.

Don’t try to do date math in MySQL

January 14th, 2013

MySQL (5.5) has incredibly broken date math semantics.

Subtracting two “datetime” types gives you a number which is manifestly not the number of seconds between those datetimes. (It’s also not ~ 10^n times that number for any n.)

So naive subtraction is broken. What about “timediff?” Well, you can use that function to compare two datetimes, and what it returns you is in the form “HH:MM:SS.” Nice. Seems to be some kind of useful interval type, right? If you decide you just want to do some averages on this result, you can then use the “time_to_sec” function, and now you’re computing some nice figures like the average time to click on an email.

…which, in keeping with the MySQL philosophy, sort of works until it (almost) silently stops working. What I mean is that the first time your date math gives you a figure like “883:15:19,” the “time_to_sec” function will start quietly giving warnings. If you turn on warnings (which really REALLY need to be on by default, here, MySQL folks), you will learn something like:

Warning (Code 1292): Truncated incorrect time value: ‘883:15:39’

Oh, great. There’s some number of hours one can put into a time value which is subsequently converted into seconds. What that number is, who knows. (Apparently not the author of the “timediff” function, because that’s what gave me that incorrect time value.)

Just give up and convert everything to an epoch timestamp. After all, who needs milliseconds anyhow? Other solutions include: use Postgres.

MySQL silently ignores aggregate query errors by default

January 14th, 2013

In a SQL query, if you use aggregate functions (min, max, count, sum, etc.) and mix them with non-aggregate columns, you have to indicate how to “group” things. Otherwise, the output is not predictable.

MySQL by default will just ignore these problems and make up something. This can make bugs in complex queries hard to track down (and it virtually guarantees that a novice or dullard will slip some errors into such queries eventually).

You can fix this with:

SET SQL_MODE=(SELECT CONCAT(@@sql_mode,’,ONLY_FULL_GROUP_BY’));

(That is, you want the “ONLY_FULL_GROUP_BY” option set. The SET above can be run in the mysql> prompt and affects that session only; thinking DBAs should strongly consider enforcing this as a server option.)

I am too tired and busy to give in to the temptation to unleash a rant about MySQL here, but PLEEEEZ. It’s the year 2013 and this is still an issue??

Hat tip Michael McLaughlin: http://blog.mclaughlinsoftware.com/2010/03/10/mysql-standard-group-by/

MySQL docs on this “extension” http://dev.mysql.com/doc/refman/5.1/en/group-by-extensions.html