Campaign Manager: Serializing Recursive Objects

There’s an idea for a game that’s been rattling around my brain for a while, so I finally decided to learn enough Unity to birth it.

To get an idea of what I have in mind, think Sid Meier’s Civilization, but for elections: you play a campaign manager, and your job is to get your candidate elected. This is complicated by the fact that the candidate may be prone to gaffes (think Joe Biden) or unmanageable (think Donald Trump); union leaders, state governors, CEOs, etc. can all promise their support, but they’ll all want something in return.

The thing I learned this week is the Unity JSON Serializer. It’s used to store prefabs and other data structures in the editor, so I figured it would be the natural tool for storing canned scenarios, as well as for saving games. It has a few quirks, though: for one thing, it can only serialize basic types (int, string, and the like), and a few constructs like struct, and arrays and List<T> of basic types. If you’re used to the introspection of languages like Python and Perl, you’re likely to be disappointed in C#. For another, in order to avoid runaway recursion, it only serializes to a depth of 7.

To start with, I defined class Area to represent an area such as a country, like the US. An Area is divided in various ways: politically, it’s divided into states. Culturally, it’s divided into regions like the Pacific Northwest or the Bible Belt. Other divisions are possible, depending on what you’re interested in. So I added a Division class:

namespace Map {
    [Serializable]
    public class Area
    {
	public string id;
	public string name;
	public List<Division> divisions = new List<Division>();
    }

    public class Division
    {
	public string id;
	public string name;
	public List<Area> children;
    }
}

As you can see, this is recursive: an Area can have multiple Divisions, each of which can contain other Areas with their own Divisions. This allows us to divide the United States into states, which are in turn divided into Congressional Districts, which in turn are divided into precincts.

Since neither of our classes are elementary types, they can’t be serialized directly. So let’s add struct SerializableArea and struct SerializableDivision to hold the structures that will actually be stored on disk, as opposed to Area and Division which will be used in memory at run time, and use the ISerializationCallbackReceiver interface that will give our classes a hook called when the object is serialized or deserialized.

Without wishing to repeat what’s in the docs: in order to get around the various limitations of the Serializer, the way to serialize a tree of objects is to serialize an array of objects, and use identifiers to refer to particular objects. Let’s say our in-memory Area tree looks something like:

  • Area United States
    • Division Political
      • Area Alabama
      • Area Alaska
    • Division Regions
      • Area Bible Belt
      • Area Pacific Northwest

(That’s just an outline, of course. Each node has more members than are shown here.) We can serialize this as two arrays: one with all of the Areas, and one with all of the Divisions:

  • Area United States
    • List<SerializableArea> childAreas:
      • SerializableArea Alabama
      • SerializableArea Alaska
      • SerializableArea Bible Belt
      • SerializableArea Pacific Northwest
    • List<SerializableDivision> serialDivisions:
      • SerializableDivision Political
      • SerializableDivision Regions

We don’t want to recurse, but we do want to be able to rebuild the tree structure when we deserialize the above. So SerializableArea contains, not a list of Divisions, but a list of identifiers that we can find in serialDivisions. Likewise, SerialDivision contains not a list of Areas, but a list of identifiers that we can look up in childAreas.

Naturally, Area and Division each contain a Serialize() method that recursively serializes it and its children.

The next question is: so you’ve been asked to serialize an Area. How do you know whether you’re supposed to add it to an existing childAreas list or start your own?

Answer: if the serialization was invoked through OnBeforeSerialize(), then you’re serializing the top level object and should allocate a list to put the children in. Otherwise, append to an existing list, which should be passed in as a parameter to Serialize().

If anyone’s interested in what it looks like when all is said and done, here it is:

namespace Map {

    [Serializable]
    public class Area : ISerializationCallbackReceiver
    {
	public string id;
	public string name;

	public List<Division> divisions = new List<Division>();

	[Serializable]
	public struct SerializableArea
	{
	    public string id;
	    public string name;
	    public List<string> divisions;
	}

	public List<Division.SerializableDivision> serialDivisions;
	public List<SerializableArea> childAreas = new List<SerializableArea>();

	public void OnBeforeSerialize()
	{
	    serialDivisions =
		new List<Division.SerializableDivision>(divisions.Count);
	    childAreas = new List<SerializableArea>();

	    for (int i = 0; i < divisions.Count; i++)
		divisions[i].Serialize(ref serialDivisions, ref childAreas);
	}

	// Look up a Division by name, so we can avoid adding it twice
	// to serialDivisions.
	private int FindDivisionById(string id,
				     ref List<Division.SerializableDivision>dlist)
	{
	    for (int i = 0; i < dlist.Count; i++)
		if (dlist[i].id == id)
		    return i;
	    return -1;
	}

	public void Serialize(ref List<SerializableArea> alist,
			      ref List<Division.SerializableDivision> dlist)
	{
	    SerializableArea sa = new SerializableArea();
	    sa.id = id;
	    sa.name = name;
	    sa.divisions = new List<string>(divisions.Count);

	    alist.Add(sa);

	    for (int i = 0; i < divisions.Count; i++)
	    {
		sa.divisions.Add(divisions[i].name);

		int d = FindDivisionById(divisions[i].id, ref dlist);
		if (d < 0)
		    // Don't add a Division to dlist twice.
		    divisions[i].Serialize(ref dlist, ref alist);
	    }
	}
    }

    public class Division : ISerializationCallbackReceiver
    {
	public string id;
	public string name;
	public List<Area> children;

	[Serializable]
	public struct SerializableDivision
	{
	    public string id;
	    public string name;
	    public List<string> areas;
	}

	public void Serialize(ref List<SerializableDivision> dlist,
			      ref List<Area.SerializableArea> alist)
	{
	    SerializableDivision sd = new SerializableDivision();
	    sd.id = id;
	    sd.name = name;
	    sd.areas = new List<string>(children.Count);

	    dlist.Add(sd);

	    for (int i = 0; i < children.Count; i++)
	    {
		sd.areas.Add(children[i].name);

		int a = FindAreaById(children[i].id, ref alist);
		if (a < 0)
		    // Don't add an Area to alist twice.
		    children[i].Serialize(ref alist, ref dlist);
	    }
	}

	private int FindAreaById(string id,
				 ref List<Area.SerializableArea> alist)
	{
	    for (int i = 0; i < alist.Count; i++)
		if (alist[i].id == id)
		    return i;
	    return -1;
	}
    }
}
Hell Is a School, Apparently

By now, you’ve all seen this T-shirt, which began circulating approximately several years before 17 people were killed at Stoneman Douglas High School, in Florida:

T-shirt: "Dear God, why do you allow violence in schools?" "I'm not allowed in schools. -- God"

As many people have pointed out, the implication is that, against all theology, God—or at least the God of sanctimonious T-shirt wearers—is not omnipresent. That a simple legislative measure is sufficient to banish God from a place.

But if you point this out, or indeed dare to make fun of a religious idea, institution, or person in a public forum, you’ll see veiled threats of hell:

godly comments

I’ve found that Christians far prefer veiled threats over overt ones. I think they’re uncomfortable with their own beliefs, and prefer to skate around them. Or maybe what they believe deep down isn’t what they believe in public. At any rate, the usual response I get is that Hell, in the afterlife, is simply an absence of God.

So, it’s like a school, I guess.

I’ve attended public school, and I still go there, for special events. I’ve never seen a pitchfork or smelled a lake of molten sulfur (and if there were, I’m sure there’d be railings so you didn’t fall in accidentally).

But really, if The Bad Afterlife is like being in an American public school, then sure, I’ll take that. It sounds an awful lot like ordinary life right now.

Grand Juries: The System Is Biased

Four months ago, I was kindly invited by the county to sit on a grand jury. The whole thing turned out to be more interesting than I had expected, and while I’m not allowed to talk about deliberations or the internals of the process, to allow jurors to speak freely inside the courtroom, I wanted to share a few thoughts.
First of all, this is a grand jury. The kind you’re probably thinking of, the 12 Angry Men type of jury of your peers, is a petit jury. The grand jury looks at an indictment and decides whether there’s probable cause to go forward to trial. That is, the petit jury decides whether the defendant did what they’re accused of doing. The grand jury merely decides whether there’s something going on; whether it’s worth having a trial at all.

One of the first things that struck me is how biased the system is in favor of bringing a case to trial.

  1. To start with, the evidentiary bar is much lower: instead of “beyond a reasonable doubt” or “preponderance of the evidence”, which a petit jury uses, the grand jury merely looks for “probable cause”. Basically, was a crime committed, and is there reason to think that the defendant may have committed it? The bar is low, so it’s easy to pass. Basically, this just excludes cases where a cop arrests someone for looking funny.
  2. The cases are introduced by a state prosecutor, who also educates the grand jury in legal matters (e.g., explaining the difference between first and second degree assault), and are read by another state employee, such as a police detective. That is, the state presents the (alleged) facts of the case, the state provides legal guidance, and no one is there to speak for the accused. It’s a bit like when your car mechanic tells you that you need a new part, and is also the person who explains what that part does.
  3. Related to the above: the prosecutor decides which cases to bring before a grand jury, and when. This isn’t a bad thing, as it means that the prosecutor doesn’t push a case before it’s ready, but it does mean that by the time a case gets to a grand jury, it’s probably good to go.
  4. As I understand it, a petit jury has to render a unanimous verdict. That is, twelve out of twelve people have to agree. In a grand jury, on the other hand, twelve out of twenty-three people (at least, in this county) have to agree. That is, almost half of the jury could have reservations, and the case could still move forward.
  5. Not all errors are equally costly: there are two types of mistake a grand jury can make: it can accept a case with no merit, or it can reject a case that ought to go to trial. In the first case, someone walks who should have gone before a judge, and possibly sent to prison. In the second case, someone has to waste a few hours or days getting their case thrown out of court. The impact of the two types of error is not the same, and so there’s the temptation to play it safe and let iffy cases proceed.

To give you an idea of how biased the system is, the state prosecutor who conducted orientation said that grand juries do dismiss cases, maybe two or three times a year. A year. I estimate that over 2000 cases a year get presented to grand juries in that courthouse, so that’s a rejection rate of about 0.1%.

I’m not saying that the system is broken, or hopelessly unjust, or anything like that. Just that the way things are set up, if you can get a case before a grand jury, it’s a very safe bet that it’ll proceed (I was going to say “that it’ll make it to trial”, but then I realized that there are a lot of pitfalls between the grand jury and the trial.)

“It’s Getting Old” Isn’t A Rebuttal

One response that I see a lot on Twitter and elsewhere is some variation on “calling Trump supporters racist is getting old”. And maybe I’m growing stupid as I grow older, but it finally dawned on me what was bugging me about that.

I’ve been in plenty of discussions where one side or another used an argument that had been debunked long ago — I used to debate creationists on Usenet, after all. But this feels different. It’s “Oh God, here we go again”, but not in a “now I need to dig up the FAQ one more goddamn time” way.

“Calling me racist is old” is all about style, not substance. It doesn’t say “I’m not a racist”, it merely says “Stop using those words”. It’s not about hearing a false factoid that just won’t die; it’s about hearing a joke for the millionth time that wasn’t even that funny to begin with.

It’s the sort of thing you say when you’re trading insults or yo-mamma jokes with someone. It’s not serious. It doesn’t matter. Certainly neither you nor anyone you know or care about is in danger of losing their health insurance, or die from a back-alley abortion, or have ICE break into their home and ship them to a foreign country.

It is, in short, something said by those who have the luxury of caring only whether their team wins, not whether said win is going to have any real-world repercussions.

Does Christianity Offer the Best Basis for Science?

There’s an argument I’ve run across several times, that theism, and specifically Christianity, forms a much better basis for science than does atheism. Indeed, some people go so far as to claim that only Christianity provides a foundation for science. Matt Slick at CARM lays it out well (though Don Johnson Ministries makes a similar argument). After listing a number of influential scientists who were Christians, Slick writes:

To many Christians, the idea that God existed and brought the universe into existence meant that the universe could be understood because God was a God of order and his character would be reflected in creation (Rom. 1:20).  Instead of a Pantheon of gods who ran the universe in an unpredictable fashion, Christianity provided the monotheistic bedrock (Isaiah 43:10; 44:6,8; 45:5) upon which the scientific study of nature could be justified.  Many Christians expected to find the secrets that God had hidden in the universe and were confident in being able to discover them.  This is a critical philosophical foundation that is necessary if an emerging culture is to break the shackles of ignorance and superstition in order to discover what secrets exist in the world around them.

This emphasis on order seems odd, since one of the main features of Christianity is miracles, that is, violations of natural law. Without at least the resurrection of Jesus, there is no Christianity. Add to that the various miracles Jehovah, Jesus, and various and sundry saints are said to have performed, the common notion that God sometimes responds to prayer by performing additional miracles, and weekly transubstantiation in church, and you get a picture of reality in which any regularities, any laws of nature exist only so long as a malleable deity permits them to exist.

If scientists like Kepler and Newton saw the Christian God as fundamentally one of order rather than caprice, and drew inspiration for their scientific pursuits from that, fine. But that’s hardly the only type of Christianity out there. I doubt that theirs was even a majority view. But in a time and place where pretty much everyone was Christian (and where not being Christian often carried either social stigma or legal penalty), of course Christians are going to be the ones doing science.

It seems to me that Taoism is a much better match for Matt Slick’s description than Christianity. You could, I think, make a strong case for the notion that the Tao is natural law. There’s certainly the notion that you can either go with the Tao, or you can wear yourself out trying to go against it.

(Yes, this still leaves the question of why so many scientific discoveries came from Europe rather than China. But that’s an interesting question for another day. I suspect that the fact that Europeans wrote American history textbooks has something to do with it.)

I suppose it wouldn’t do to mention alchemy and algebra, whose prefix “al” betrays their Muslim origin. Or the fact that a large proportion of visible stars have Arabic names.

I also don’t see why it takes a whole religion or worldview to want to figure out what makes the world tick. Anyone can see that day follows night, summer follows spring, rocks always roll downhill, never up, and that oaks only come from acorns. Clearly there are some regularities, and these can be investigated. We’re curious creatures; figuring stuff out is fun.

There’s a related claim to the one that Christians founded all the sciences: that Christians founded all the major universities. I haven’t checked this, but I see no reason to doubt this claim.

This brings me to my final point: let’s grant, at least for the sake of argument, that Christians, motivated by their understanding of God as a lawmaker, got all of the sciences started; that most or all of the major universities were founded as institutions to learn how God set up the universe; that Christianity is the only religion — the only worldview — that could have kickstarted science this way, and that out of those beginnings grew science as we know it today… so what? Why keep religion around today?

A scaffolding is essential when beginning a new building. But after a certain point, it needs to go. I was on an all-milk diet for the first, crucial part of my life, and that helped make me into the person I am today. But that doesn’t mean that I should continue to drink milk as an adult; I especially shouldn’t be on an all-milk diet.

Whatever benefits religion may once have provided to science, these days it just gets in the way, from creationism to anti-gay “conversion therapy” to faith-based climate change denialism. It’s time to jettison it.

Wheeze A Coda Dog

The Alexa app on my tablet wanted to share with me the exciting (to it) news that Amazon has released a companion device to its Echo, called an Echo Dot, and invited me to ask “Alexa, what’s Echo Dot?” to learn more.

According to said app’s transcript, here’s the conversation we just had:

– Alexa, what’s echo dog?
– Sorry, I couldn’t find the answer to your question.
– Alexa, what’s the Dutch?
– The Netherlands national football team represents the Netherlands in international football.
– Alexa, what’s the code coda?
– Sorry, I couldn’t find the answer to your question.
– Alexa, what’s the code doctor?
– Sorry, I couldn’t find the answer to your question.
– Alexa, what’s the coda?
– Coda is a term used in music primarily to designate a passage that brings a piece to an end.
– Alexa, what’s Echo Dot?
– [Spiel about Echo Dot]
– Alexa, order some Echo Q-Tips.

I Get Spam

Track lighting, from Wikimedia Commons

I don’t often get spam worth sharing, but this one is comedy gold. (See also below for post-419 comments.)

From: “Mr Ronald Anthony”<mrronaldanthonys@—.—>
Subject: RE: ISSUES OF FRAUD CRIME AGAINST YOU (FBI)

THIS IS THE (F.B.I)
http://www.fbi.gov

FBI Headquarters in Washington, D.C.
Federal Bureau of Investigation
J. Edgar Hoover Building
935 Pennsylvania Avenue,
NW Washington, D.C. 20535-0001

FEDERAL BUREAU OF INVESTIGATION (FBI)

Attention

This the Federal Bureau Of Investigation (FBI) We are writing in response to our track light monitoring device which we received today in our office about the illegal transactions that you have been involve in for a long time now.

We understand from our general investigations that some con men from Australia has been ripping a man off him hard earned money with the pretense of dealing with birds Company that will deliver a pet to him and the proposed amount which was to be transferred to you is the sum of $5,000,000 Usd as stated in our record here.

We also got a complain from our Australia man counterpart stating that your identity/information’s was used to dupe a Australia business man to the tune of $4 Billion Usd by some Australia Fraudsters which you have been in contact with for some time now.

The German Government has ordered for your urgent arrest regarding the crimes that was committed with your name,after all the series of investigations conducted here in our office we tracked your record and we found out that you have never been jailed or had any fraudulent case that may jeopardize your image and personality.

All this information’s are on record and we are going to use it against you in the world court when this case will be brought before it and we called the Australia High Commission for an urgent compensation for the bad deed that has been committed with your name.

The Australia Government has made available the sum of $950,000.00 Usd for your compensation and then we would like to inform you to stop any further communications with the con men so that you will not be brought before the law..

We also discovered that you have made some payments to them earlier for this same funds that was to be sent to you.

Don’t forget that all your properties will be confiscated as soon as you are jailed because it will be believed that you got them from fraudulent and dubious business transactions like the one that you are in right now.

We have forwarded a copy of this information’s to all the states crime agencies including,

National Crime Information Center (NCIC)

CrimTrac Agency, Canberra,

Crime and Corruption Commission

Crime and Misconduct Commission

Home Land Security Service.

Economic And Financial Crimes Commission (EFCC)

Nigerian Local Metropolitan Police (NLMP)

So all you need to do right now in other to clear your name from the scam list which has already been forwarded to our office is to secure the CLEAN BILL CERTIFICATE immediately.

This Certificate will then clear your name from the scam list and also after the Certificate has been issued to you, you will then forward it to the payment officer for the urgent transfer of your compensation funds of $950,000.00 Usd.

You are required to forward to us your private contact number for oral communications and don’t forget that you will be given only 72hours to secure the CLEAN BILL CERTIFICATE or you will face the law and its consequences.

Your e-mail address is now under our e-mail track monitor, so you should make sure that you don’t respond to any e-mail that is being sent to you from anybody or organization that claims to be working for the Government.

Forward the details of the payment you made to them earlier, and also all the information’s/documents that was forwarded to you by those criminals that you have been in contact with for a long time now.

Also below is my attached Identity Card for your perusal.

Get back to us as soon as you receive this e-mail so that we can guild you on how to secure the Certificate within 72hours.

THANKS FOR YOUR CO-OPERATION.

Thanks as I wait for your response

Respectively
Mr Ronald Anthony
FBI AGENT


I’ve seen some unconvincing 419 scams before, but this one is like two kids on each other’s shoulders, wearing an overcoat, trying to sneak into Buckingham Palace by pretending to be an Interpol inspector. And using Clouseau as a model.

Having said that, isn’t it amazing what they’re doing with track lighting nowadays? And I hope guilding doesn’t hurt.

If you liked that, you’re sure to enjoy this PSA for Camp Quest Northwest.

A Positive Review

I know this is bad form, but I really like this review of something I wrote:

If it is a Poe, it is a pretty clever one: goes suspiciously overboard only 3-4 times

I might need to add “goes suspiciously overboard only 3-4 times” to my bio.

Let’s Get This Out of the Way

Here’s a link to something I claim you’ll find interesting:

http://www.youtube.com/Rick-Astley-Never-Gonna-Give-You-Up

Right. That’s April Fools Day taken care of. Now let’s move on.

A Brush With Celebrity

And not just any celebrity, but the highest:

Now, the next time someone tells me, “You’re not really an atheist. You secretly believe in God”, I’ll be able to say, “You’re right. And I have photographic evidence.”