Monday 30 October 2017

Black Milk: On Writing, Motherhood, and the Harem Within, by Elif Shafak

I've vaguely heard about Elif Shafak before, but she only came to my attention when she did a TED talk that I really liked. I mean, it was a little on the feminist side, but the speaker was both articulate and correct - not to mention cute, so I wondered what she wrote about. So I started with Black Milk. And it was as much feminist as they get, discussing women writers in the context of the author's own challenges as a woman and a mother affected by postpartum depression. Therefore, if you don't like these kinds of books, don't read it.

Personally I liked the writing a lot. I didn't really feel interested in the subject so much, but that's also a plus for the book: if you can make people like reading about something they don't care about, then you are doing it right. I find different viewpoints on life interesting, as well, so all in all I enjoyed reading the stories. Yet, the feminism bit threw me off a little. Shafak identifies a lot not only with being a woman, but being a feminist middle East female writer, and she doesn't let anyone forget it. It is difficult to feel connected with the author when she's constantly reminding you of the differences between you. Even the thumbelinas in the book (thumb sized representations of the facets of her personality) are all female. It is true that you hear a lot more about the feminine side of guys rather than the masculine side of women, but still.

What I thought was a little bit misleading was the description of the book as a memoir. In fact, there is little of the author's actual experiences in the book. Instead, there are short anecdotes of her life, strongly dramatized and fantasized, followed by longer analogies with other female writers and their own stories. The book does present a very personal viewpoint on all it describes, but it reveals the author just through comparison rather than through confession. It does not feel intimate, it feels pretentious, an intellectual treatise on things Shafak claims very personal and emotional.

Bottom line: while I liked it, as something very different from what I read and a well written book by a very imaginative author, I think it would have benefited more from a more personal and less argumentative touch.

Tuesday 17 October 2017

Monday 16 October 2017

The False Admiral (Evagardian #1), by Sean Danker

Book cover Imagine a space pulp "escape from a room" story and you get The False Admiral (also known as simply Admiral). Sean Danker writes a short and fast paced story about three Evagardian space navy members that find themselves on a derelict ship on an unknown alien planet. From start to end the hero of the story, helped by the other younger three, must solve problem after problem in order to keep them alive. It's a short, fun and simple book.

At first I was convinced that this was not the beginning of the story. The main character mentions previous events that are not described in the book and he makes efforts to hide his real identity from the others, to the point where they have to choose between trusting him or arresting him as an enemy spy. But no, that part of the story is not written yet. A second book in the Admiral series has been released, called simply Free Space, but I will probably not read it. And this is not because I did not enjoy Admiral, but because I have other stories I would rather read.

Bottom line: when you need a quick disconnecting read, try this book. It's dubious sci-fi and it is rather more similar to detective noir than space opera or military stories, but it is fun.

Friday 13 October 2017

Memory alignment in C++ and C# and probably in every other language that can integrate with C++

I've learned something new today. It all starts with an innocuous question: Given the following struct, tell me what is its size:
    public struct MyStruct
{
public int i1;
public char c1;
public long l1;
public char c2;
public short s1;
public char c3;
}
Let's assume that this is in 32bit C++ or C#.

The first answer is 4+1+8+1+2+1 = 17. Nope! It's 24.

Well, it is called memory alignment and it has to do with the way CPUs work. They have memory registers of fixed size, various caches with different sizes and speeds, etc. Basically, when you ask for a 4 byte int, it needs to be "aligned" so that you get 4 bytes from the correct position into a single register. Otherwise the CPU needs to take two registers (let's say 1 byte in one and 3 bytes in another) then mask and shift both and add them into another register. That is unbelievably expensive at that level.

So, why 24? i1 is an int, it needs to be aligned on positions that are multiple of 4 bytes. 0 qualifies, so it takes 4 bytes. Then there is a char. Chars are one byte, can be put anywhere, so the size becomes 5 bytes. However, a long is 8 bytes, so it needs to be on a position that is a multiple of 8. That is why we add 3 bytes as padding, then we add the long in. Now the size is 16. One more char → 17. Shorts are 2 bytes, so we add one more padding byte to get to 18, then the short is added. The size is 20. And in the end you get the last char in, getting to 21. But now, the struct needs to be aligned with itself, meaning with the largest primitive used inside it, in our case the long with 8 bytes. That is why we add 3 more bytes so that the struct has a size that is a multiple of 8.

Note that a struct containing a struct will align it to its largest primitive element, not the actual size of the child struct. It's a recursive process.

Can we do something about it? What if I want to spend speed on memory or disk space? We can use directives such as StructLayout. It receives a LayoutKind - which defaults to Sequential, but can also be Auto or Explicit - and a numeric Pack parameter. Auto rearranges the order of the members of the class, so it takes the least amount of space. However, this has some side effects, like getting errors when you want to use Marshal.SizeOf. With Explicit, each field needs to be adorned with a FieldOffset attribute to determine the exact position in memory; that also means you can use several fields on the same position, like in:
    [StructLayout(LayoutKind.Explicit)]
public struct MyStruct
{
[FieldOffset(0)]
public int i1;
[FieldOffset(4)]
public int i2;
[FieldOffset(0)]
public long l1;
}
The Pack parameter tells the system on how to align the fields. 0 is the default, but 1 will make the size of the first struct above to actually be 17.
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyStruct
{
public int i1;
public char c1;
public long l1;
public char c2;
public short s1;
public char c3;
}
Other values can be 2,4,8,16,32,64 or 128. You can test on how the performance is affected by this, as an exercise.

More information here: Advanced c# programming 6: Everything about memory allocation in .NET

Update: I've created a piece of code to actually test for this:
unsafe static void Main(string[] args)
{
var st = new MyStruct();
Console.WriteLine($"sizeof:{sizeof(MyStruct)} Marshal.sizeof:{Marshal.SizeOf(st)} custom sizeof:{MySizeof(st)}");
Console.ReadKey();
}
 
private static long MySizeof(MyStruct st)
{
long before = GC.GetTotalMemory(true);
MyStruct[] array = new MyStruct[100000];
long after = GC.GetTotalMemory(true);
var size = (after - before) / array.Length;
return size;
}

Considering the original MyStruct, the size reported by all three ways of computing size is 24. I had to test the idea that the maximum byte padding is 4, so I used this structure:
public struct MyStruct
{
public long l;
public byte b;
}
Since long is 8 bytes and byte is 1, I expected the size to be 16 and it was, not 12. However, I decided to also try with a decimal instead of the long. Decimal values have 16 bytes, so if my interpretation was correct, 17 bytes should be aligned with the size of the biggest struct primitive field: a multiple of 16, so 32. The result was weirdly inconsistent: sizeof:20 Marshal.sizeof:24 custom sizeof:20, which suggests an alignment to 4 or 8 bytes, not 16. So I started playing with the StructLayoutAttribute:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyStruct
{
public decimal d;
public byte b;
}

For Pack = 1, I got the consistent 17 bytes. For Pack=4, I got consistent values of 20. For Pack=8 or higher, I got the weird 20-24-20 result, which suggests packing works differently for decimals than for other values. I've replaced the decimal with a struct containing two long values and the consistent result was back to 24, but then again, that's expected. Funny thing is that Guid is also a 16 byte value, although it is itself a struct, and the resulting size was 20. Guid is not a value type, though.

The only conclusion I can draw is that what I wrote in this post is true. Also, StructLayout Pack does not work as I had expected, instead it provides a minimum packing size, not a maximum one. If the biggest element in the struct is 8 bytes, then the minimum between the Pack value and 8 will be used for alignment. The alignment of the type is the size of its largest element (1, 2, 4, 8, etc., bytes) or the specified packing size, whichever is smaller.

All this if you are not using decimals... then all bets are off! From my discussions with Filip B. Vondrášek in the comments of this post, I've reached the conclusion that decimals are internally structs that are aligned to their largest element, an int, so to 4 bytes. However, it seems Marshal.sizeof misreports the size of structs containing decimals, for some reason.

In fact, all "simple" types are structs internally, as described by the C# language specification, but the Decimal struct also implements IDeserializationEventListener, but I don't see how this would influence things. Certainly the compilers have optimizations for working with primitive types. This is as deep as I want to go with this, anyway.

Thursday 12 October 2017

Hex, by Thomas Olde Heuvelt

book cover Hex has a very King-like feel. The quintessential American little town, the close knit community, the apparent order and control, the breaking of chaos and the reveal of the true face of humanity. And yet, the inspiration for the story came from Roald Dahl's The Witches and it was originally about a little Dutch town. However Thomas Olde Heuvelt saw an opportunity while reviewing the English translation of the book and updated it for an American audience.

The premise is interesting enough. Imagine a modern town that is also haunted by the 350 year old witch that cursed it. People have molded their lives around the witch, using the Internet and technology to monitor her and hide her from the world outside their little town. And when something goes wrong, it goes very wrong. However, I loved that the end was not the typical American horror story, in which the baddie does unspeakable things and the heroes suffer and maybe prevail after grievous losses. It's difficult to talk about it without spoiling the ending, so you will have to read the book and remember me when Katherine displays shock.

Now, I can't say I loved the book. It is well written and the characters are compelling enough. However, it did feel like someone was excited to write a story in the American way, and that is exactly what I did not expect from the author. I mean, I've read The Boy Who Cast No Shadow and that was both powerful and fresh. Hex is not very long, though, and easy to read. Perhaps its best feature is also its worst: it is predictable. You read it and it's like those supposedly funny fail videos where you know something is going to happen, you can even guess what it is going to be, but you are still watching to see it unfold. If you like Stephen King, you will like this book.

Friday 6 October 2017

Counterfeit Sky - Failure

As an experiment, try to find this video without knowing the name of the song or of the band. I tried so hard until my brain just gave up and remembered the name of the band all by itself. So here is the video. Now I can always find it when I need it. Cool song and video, I think.



And so that other people can find it: it's a music video about an astronaut crash landing on an alien planet and finding his own dead bodies and more versions of himself continuously falling and dying in different ways.

Obsidian and Blood, by Aliette de Bodard

book covers for the three bookds Obsidian and Blood is a collection of all the works in the Aztec magical universe created by Aliette de Bodard. It contains the three books Servant of the Underworld, Harbinger of the Storm and Master of the House of Darts, plus three short stories (which perhaps you should read first). The stories can be found online, if you want a free taste.

Now, while I enjoyed the books, I felt a little cheated. In fact, these are not fantasy books as much as policiers, just set in the tiny and magical Aztec world. Acatl, priest of the Dead, is trying to solve the mystery of various murders and magical transgressions. He is driven, moral and relentless, willing to sacrifice everything in order to save his friends, loved ones and ultimately the world. So it's basically a cop book, only with Aztec gods around.

The writing style is very technical, reminding me of so many other authors that learned the craft in writing classes, with a mentor and a group and so on. However, it was in no way innovative. I felt that the books are the written equivalent of TV movies: professional, but mediocre. And while I stuck through all the books instead of stopping with the first, it's kind of like watching the rest of a miniseries just because you watched the first episode.

The context is the only thing that elevates the book above average. It is an interesting setup to base the stories on Aztec mythology, but I felt that modern sensibilities prevailed and the author chickened out when it came to child sacrifices and ritual torture and so on. They are mentioned, but everybody, whether heroic or villainous, is rational and follows a modern way of thinking.

Bottom line: I wish these were filled with the horror and majesty of the old blood gods, making me feel something visceral and true, more like the short stories and less than the books. As such, these are just police mystery stories set in the Mexica empire.

Monday 2 October 2017

Debugging in Eclipse

For anyone coming from the welcoming arms of Visual Studio 2015 and higher, Eclipse feels like an abomination. However, knowing some nice tips and tricks helps a lot. I want to give a shout out to this article: Again! – 10 Tips on Java Debugging with Eclipse which is much more detailed that what I am going to write here and from where I got inspired.

Three things I thought most important, though, and this is what I am going to highlight:
  1. Show Logical Structure - who would have known that a little setting on top of the Expressions view would have been that important? Remember when you cursed how Maps are shown in the Eclipse debugger? With Show Logical Structures you can actually see items, keys and values!
  2. The Display View - just go to Window → Show View → Display and you get something that functions a bit like the Immediate Window in Visual Studio. In other words, just write your code there and execute it in the program's context. For a very useful example: write new java.util.Scanner(request.getEntity().getContent()).useDelimiter("\\A").next() in the Display window, select it, then click on Display Result of Evaluated Selected Text, and it will add to the Display window the string of the content of a HttpPost request.
  3. Watchpoints - you can set breakpoints that go into debug mode when a variable is accessed or changed!

For details and extra info, read the codecentric article I mentioned above.