• About
    • About

Steve Cooper's Personal Blog

  • Game Crafter II – Battle Deathmongery

    July 20th, 2009

    I’ve been thinking about writing a board game after seeing [The Game Crafter](http://www.thegamecrafter.com) and realising the effort of getting a physical game produced might now be relatively low.

    The idea is to create a war-themed board game, something to try to simulate small-scale battles — something like Memoir 44. I have an idea for a basic mechanic, where each unit in the game has a standing order: something like a miniature ‘program’ that dictates what the unit does. A little like roborally. So an order might look like this;

    > Advance: if there is no enemy within line of sight, move two spaces towards an enemy objective. Otherwise, move towards the nearest unoccupied or allied cover.

    So that is the basic mechanic. Each round the players change some of the orders. I’ve got to put together a deck of orders that works sensibly, and a map, and then I can put together a paperprototype and subject someone to a game.

  • Initial impressions of the iPhone 3GS

    July 19th, 2009

    I got my iPhone delivered Saturday morning, and I have been playing with it heavily all weekend. This is a post about my initial impressions of the phone.

    Unlike a lot of the people who would have reviewed the iPhone, I’m not a big phone fan. My previous phone was a cheap pay-as-you-go device, and I’ve owned a palm PDA in the past. I’ve owned a couple of iPods, too. So I was expecting something which felt like, well, a phone, a PDA, and an iPod mashed into a single box.

    But this is something else. The combination makes it a different class of device from any of its constituent parts. It is quite hard to articulate how it is different, but it certainly is.

    It has started to teach me something about application design, for a start.

    Take the feeling of things being integrated and automatic. The phone is sold with unlimited web connectivity – 3g and EDGE and wifi – and has gps, and it has a camera. Now, I would expect to be able to take a photo, and then be able to look at a map, and then browse the web a bit. What I wasn’t expecting is apps that write blog posts, take photos, automatically geocode them with information from the gps, and then upload them to my site and inject them into the blog post. That makes it really easy to share stuff you’ve seen.

    I never used the camera on my old phone because it was difficult to get the photos off. Once they were off the phone and onto my PC I would have to upload them onto flickr or FTP. Then I would have to get that URL and copy it into the body of the blog post. It was all such a hassle that I never bothered. Now, I can do it right inside the wordpress app that was free on the app store. So I’m going to be doing it a lot more, I think.

    Which brings me on to the app store. There are an awful lot of apps available, and they really are very good. I have long experience with palm, and that always had a good community of developers and products, but thos is a level above. The app store seems to make it worth developer’s time to write apps; I suppose because apple deal with the money and the front end (the app store itself) it is easier to get something written. The small number of different phones must make a big difference, too. A friend of mine used to write java apps for phones, and spent a great deal of his time just making sure his app worked on as many of the hundreds of popular phone models out there. Since there are only a handful of different models of iPhone, I imagine that’s a lot easier.

    Anyway, enough for now. I am just delighted with this gizmo.

  • Clare’s Birthday Dinner

    July 19th, 2009

    Clare’s birthday meal at Red Chilli went very well. We had ten people, and that meant that we could share. Tried a bunch of different things, had good conversation, then everyone came back to our place and we had cake and wine. Thanks to everyone who attended; it was a great night out.

  • The Game Crafter

    July 17th, 2009

    An interesting site for all my gamer mates; [The Game Crafter](http://www.thegamecrafter.com/home) is a site which lets you design your own card and board games, and package them up for purchase. [Hacker News](http://news.ycombinator.com/) had it linked as ‘CafePress for boardgames.’

    Anyway, the barrier to entry has dropped significantly for producing home-baked games.

  • Fitness, Fatness; what matters for diseases like heart disease?

    July 16th, 2009

    I’ve been reading the rather excellent [junk food science](http://junkfoodscience.blogspot.com/) blog recently, and I’ve found it really interesting. The author shares some of the big research into obesity and nutrition. What’s really interesting is that many of the guidelines we hear on a regular basis seem to have no scientific credibility. And I don’t mean things that sound outlandish, like diets composed entirely of cranberries and algae smoothies, but really straightforward, everyone-believes this stuff. Things like;

    – being overweight causes heart disease.
    – eating fruits and vegetables is good for you.
    – reducing your fat intake is healthy.

    What’s interesting is how little is shown to be true by actual respectable science. In [this article](http://junkfoodscience.blogspot.com/2007/10/junkfood-science-exclusive-big-one.html), the author considers the results of the Women’s Health Initiative (WHI) Dietary Modification Trial. This trial was a study of nearly 50,000 postmenopausal women; some ate a ‘healthy diet’ high in fruit, vegetables, fibre, and whole grains, and low in fat. The control group ate whatever they felt like. The women were on the study for eight years, and at the end they were tested for heart disease, weight, cancers, etc. Here’s what the study found;

    Cardiovascular disease:

    > “a dietary intervention that reduced total fat intake and increased intakes of vegetables, fruits, and grains did not significantly reduce the risk of CHD, stroke, or CVD in postmenopausal women.”

    Breast cancer:

    > “We found no evidence that lower intake of total fat or specific major types of fat was associated with a decreased risk of breast cancer.”

    Colon and rectal cancer:

    > “a low-fat dietary pattern intervention did not reduce the risk of colorectal cancer in postmenopausal women during 8.1 years of follow-up.”

    Body Weight:

    > The women following a “healthy” diet for eight years didn’t end up thinner. They lost a bit at the beginning, but had regained it back years before the end of the trial, despite continued restrained eating and eating fewer calories (361 kcal/day less than they had been at the start of the study). During the last years of the trial and at the end, the researchers found an insignificant difference in weight changes between the intervention and control group of a mere 0.7 kg. They concluded:

    >> “A low-fat eating pattern does not result in weight gain in postmenopausal women.”

    Which is pretty amazing. Women on eight years of a recommended healthy diet were just as likely to get heart disease, clogged arteries, strokes, or three kinds of cancer, and were no thinner than the women who ate whatever they fancied.

    A similar [study of male veterans](http://junkfoodscience.blogspot.com/2009/06/paradoxes-compel-us-to-think.html) found similar things. They followed about 1,000 men who were healthy in 1987, and followed up in 2004. By then, 208 had died. The overweight men in the study had a 34% better survivability than normal [BMI](http://en.wikipedia.org/wiki/Body_mass_index), whereas obese men had a 44% better chance of being alive.

    That’s a fairly hefty foundation stone in a lot of the advice we see on how to live healthily. That being overweight leads to all manner of diseases and problems is heard so often that it’s incredible that it isn’t really backed up by the literature. And if that isn’t credible, then all the smaller studies and claims, about foods being either Good or Bad (chocolate, red wine, antioxidants, dihydrogen monoxide, polyungiptomobes) are probably equally suspect.

    It’s got me intrigued. Over the next little while, I’m going to try to find the real papers, the real studies, that have managed to show what really does, and does not, have a benefit.

    So my first aim will be to find out what effect cardiovascular fitness has on heart disease. Does getting fit help you avoid heart disease?

  • Athlete’s Foot: the Vibram Fivefingers

    July 16th, 2009

    As a kid, I always enjoyed going barefoot. I used to spend summer holidays walking around without shoes, and my feet used to toughen up over those six week breaks. But then when I went back to school and got back into smart shoes, my soles would soften up again and my barefoot pleasure was curtailed.

    So when, on occasion, I’ve daydreamed about the perfect shoe, it hasn’t been about the latest Jimmy Choos, but something more like the Vibram Five Fingers, a shoe I’ve discovered on the web. What I’ve always wanted, but never seen before, is as minimal a pair of shoes as possible; something that’ll stop my feet being cut to ribbons, but let me feel like I’m not really wearing shoes.

    So here’s the Five Fingers;

    ![Vibram Five Fingers](http://www.vibramfivefingers.com/products/images/products/116C//large.jpg)

    What we’re looking at is a shoe which is basically enough tough rubber to save your feet from dogshit and broken glass on the streets, with just enough structure to strap it onto your feet.

    So they’ve got a couple of interesting points; some in terms of health and fitness, and some social.

    Healthwise, there’s evidence that training shoes might be pretty bad for your feet, and the fivefingers gets you back to something close to nature. There’s some folks who believe that [Homo Sapiens evolved to be joggers](http://www.fas.harvard.edu/~skeleton/pdfs/2004e.pdf); (Harvard Uni, pdf)

    > However, although humans are comparatively poor sprinters,
    they also engage in a different type of running, endurance running
    (ER), defined as running many kilometres over extended time
    periods using aerobic metabolism. Although not extensively studied
    in non-humans, ER is unique to humans among primates, and
    uncommon among quadrupedal mammals other than social carnivores
    (such as dogs and hyenas) and migratory ungulates (such as
    wildebeest and horses.

    What’s interesting, from a health and fitness point of view, is that if humans are designed to jog, then the feet should be a bloody well-adapted instrument, and shoes might just be screwing with their optimal comfort. And in fact, a lot of joggers suffer foot and leg injuries. Some of that probably comes from hard asphalt, and some comes from poor footware.

    From a social point of view, I have a restrained optimism. There are social situations that call for shoes; in fact, it’s pretty much unheard of to go without shoes. So in situations which require shoes, these may well serve well enough to get by; I’m wondering if I can away with them in the office.

    Somewhere in between health and social norms is gym etiquette. My gym, at least, doesn’t allow people to wander around barefoot. So these might serve people who want to run barefoot on the treatmill or do kicking martial arts training on the heavy bag.

    Now, [Wired](http://www.wired.com) described them as [“Ugly as a bucket of vomit”](http://www.wired.com/reviews/product/pr_vibram_fivefingers_kso) but they, like me, were intrigued and gave it a decent review. Personally, I really like the look.

    I think I’m going to put this on my shopping list as my next toy.

  • Immutable objects in C#

    July 14th, 2009

    Immutability is one of those programming subjects we hear about fairly regularly at the moment. It’s supposed to be one of those principles which make parallel programming easier, and since we’re currently in the world of 4-core machines, parallel is big right now.

    Unfortunately it’s really hard in C# to create immutable objects. Or at least, C# isn’t really designed for it, so if you try to write an app using immutable data structures, you may find yourself writing a lot of boilerplate just to adhere to this particular paradigm. Which means at some point you’ll stop bothering, because it’s just too much work.

    So, in the interests of reinventing the wheel, I’ve written a small code generator which creates immutable structs, which have ‘mutator’ functions. Mutators are methods which return whole new objects with just one property changed. For instance, if you have an immutable rectangle defined like this;

    var firstRect = new Salamander.Models.Rectangle(100, 100, 100, 100);

    then you can create a new object will all the same properties except one like this;

    var secondRect = firstRect.WithTop(50);

    Anyway, the system consists of two files; the generator itself [(Immutable.ttinc)](https://stevecooper.org/documents/Immutable.ttinc) and a file which defines the immutable types to create [(myImmutableTypes.tt)](https://stevecooper.org/documents/myImmutableTypes.tt). You’ll need to include them both in your c# project, then right-click the `.tt` file and choose ‘Run Custom Tool’

    ## To define your own custom types

    You’ll need to look inside the `.tt` file and write a line which describes the type you’d like to create — basically just a namespace-qualified type name, and a list of fields;

    GenerateImmutable(“Db.Person: string FirstName; string SecondName”, “A Person”);

    The second parameter is a class-level xml comment

    ## Immutable.ttinc

    <#+

    private class Member
    {
    public string Type;
    public string Name;
    }

    void GenerateImmutable(string definition)
    {
    GenerateImmutable(definition, string.Empty);
    }

    void GenerateImmutable(string definition, string comment)
    {
    var typeBuilder = new System.Text.StringBuilder();

    int indexOfColon = definition.IndexOf(':');
    if (indexOfColon == -1)
    {
    Error("No colon; expected, eg 'Rectangle: ‘”);
    }

    string ns = “”;
    string typeName = definition.Split(‘:’)[0];
    string members = definition.Split(‘:’)[1];

    //
    // NAMESPACE
    //
    int lastNsDot = typeName.LastIndexOf(“.”);
    if (lastNsDot != -1)
    {
    ns = typeName.Substring(0, lastNsDot);
    typeName = typeName.Substring(lastNsDot+1);
    }

    if (String.IsNullOrEmpty(ns) == false)
    {
    typeBuilder.Append(“namespace “).AppendLine(ns).AppendLine(“{“);
    }

    //
    // TYPE DEFINITION
    //
    typeBuilder.Append(” ///

    “).Append(comment).AppendLine(“

    “);
    typeBuilder.Append(” public partial struct “).AppendLine(typeName).AppendLine(” {“);
    var memberList = members
    .Split(‘;’)
    .Select(x => x.Trim())
    .Where(x => x.Length > 0)
    .Select(x => x.Split(‘ ‘))
    .Select(arr => new Member { Type = arr[0], Name=arr[1] })
    ;

    //
    // CONSTRUCTOR
    //
    typeBuilder.Append(” ///

    Create a new “).Append(typeName).Append(“

    “).AppendLine();
    typeBuilder.Append(” public “).Append(typeName).Append(“(“);
    foreach(var memberItem in memberList)
    {
    typeBuilder.Append(memberItem.Type).Append(” “).Append(memberItem.Name).Append(“,”);
    }
    typeBuilder.Length = typeBuilder.Length-1; // remove trailing comma
    typeBuilder.AppendLine(“)”);
    typeBuilder.AppendLine(” {“);
    foreach(var memberItem in memberList)
    {
    typeBuilder
    .Append(” this.”)
    .Append(memberItem.Name)
    .Append(” = “)
    .Append(memberItem.Name)
    .Append(“;”)
    .AppendLine();
    }

    typeBuilder.AppendLine(” }”);

    //
    // fields
    //
    typeBuilder.AppendLine(” // fields”);
    foreach(var memberItem in memberList)
    {
    typeBuilder
    .AppendFormat(” public readonly {0} {1};”, memberItem.Type, memberItem.Name)
    .AppendLine();
    }
    typeBuilder.AppendLine();

    foreach(var memberItem in memberList)
    {
    typeBuilder
    .AppendLine(” ///

    mutator for ” + memberItem.Name + ” property

    “)
    .AppendFormat(” public {0} With{1}({2} new{1})”, typeName, memberItem.Name, memberItem.Type)
    .AppendLine(” {“)
    .AppendFormat(” var newItem = new {0}(“, typeName)
    ;

    foreach(var memberItemParam in memberList)
    {
    if (memberItem.Name == memberItemParam.Name)
    {
    typeBuilder.Append(“new”).Append(memberItem.Name).Append(“,”);
    }
    else
    {
    typeBuilder.Append(“this.”).Append(memberItemParam.Name).Append(“,”);
    }
    }
    typeBuilder.Length = typeBuilder.Length-1; // remove trailing comma
    typeBuilder.AppendLine(“);”);
    typeBuilder.AppendLine(” return newItem;”);
    typeBuilder.AppendLine(” }”);
    typeBuilder.AppendLine();
    }

    typeBuilder.AppendLine(” }”);

    if (String.IsNullOrEmpty(ns) == false)
    {
    typeBuilder.AppendLine(“}”);
    }

    Write(typeBuilder.ToString());

    }

    #>

    ## myImmutableTypes.tt

  • Passed my microsoft exam

    June 9th, 2009

    I’ve been studying for my Microsoft certification for the last four days, and this afternoon I passed. So I am now certified in the [world’s most boring subject](http://www.microsoft.com/learning/en/us/exams/70-536.aspx).

  • Make a cafe au lait in the office

    February 3rd, 2009

    I’ve just gone to the nearby coffee bar for a lunchtime latte, and I was bitterly disappointed. Filth! So I won’t be buying latte there any more.

    Instead, I’ll be making cafe au lait in the office. Cafe au lait isn’t just white coffee; it’s a 50-50 mix of hot milk and double-strength coffee, and bears a remarkable resemblance to a caffe latte, just without the foam cap. It’s much richer and more luxurious than a white coffee.

    If if you have fresh coffee and fresh milk, you can make a very passable cafe au lait in minutes. Here’s the skinny.

    ##Equipment:

    – a cafetiere.
    – a microwave.
    – a large mug or microwave-safe jug, to heat the milk.
    – a smaller mug, to serve.

    ##Ingredients:

    – milk.
    – coffee ground for cafetiere.

    ##Method:

    The steps are; start the coffee brewing, heat the milk, plunge the coffee, then mix.

    _Start the coffee brewing:_ To make the coffee, boil a kettle of water and either let it cool for a minute, or put some cold water. Boiling water can scald the coffee. I know this sounds precious, but it makes a difference; you won’t taste as much bitterness in the coffee, and you should notice more of the flavours.

    Now you’re going to make double-strength coffee. I use two heaped desert spoons in a cafetiere that will make three cups (two mugs) of coffee, but then I half-fill the cafetiere. Give it about three minutes to brew. During those three minutes, we’ll heat the milk.

    _Heat the milk:_ Take your large mug and half-fill it with milk. Nuke it for about a minute and a half.

    _Plunge and mix:_ When that’s done, your coffee should be about ready. Plunge the cafetiere, then mix the milk and coffee about 50-50. You will end up with something that looks like white coffee, with some wisps of white almost-foam floating on the surface. You’re done!

    Drink in small amounts; it’s a rich drink and you don’t need huge quantities. Save yourself from bad industrial estate caffe latte!

  • Python-style string formatting for C#

    January 24th, 2009

    [Jon Skeet][skeet] recently asked in one of [his posts][op]:

    > it would be really nice to be able to write:
    >
    > `throw new IOException(“Expected to read {0} bytes but only {1} were available”, requiredSize, bytesRead);`

    Which would do the same as

    throw new IOException(String.Format(
    “Expected to read {0} bytes but only {1} were available”,
    requiredSize, bytesRead));

    And it got me wondering about the String.Format method, and how much uglier it makes C# code to read than, say, the equivalent python code. Alongside each other;

    // C#
    string message = String.Format(
    “Expected to read {0} bytes but only {1} were available”,
    requiredSize, bytesRead);

    // python
    message = “Expected to read %s bytes but only %s were available” % (requiredSize, bytesRead)

    I think I’d solve the problem, not by creating a new constructor for `IOException`, but by making String.Format part of the C# syntax. It works very nicely for python, and it’s such a common thing to do that I tink it would warrant a change to the language. Given how cumbersome String.Format is, it’s often shorter and clearer to use simple string concatenation. This makes things rather inconsistent.

    Here’s what I came up with. It’s a ‘first draft’, and more for interest’s sake than as something I’d put into production.

    Instead of passing an object array in as the values, I’m reading from the properties of an object. So you can do it with objects or tuples;

    var person = new Person()
    {
    firstname=”Steve”,
    secondname=”Cooper”
    };

    Then you can inject the tuple into a format string like this;

    string message = “{firstname} {surname} says injecting properties is fun!”.ㄍ(person)
    // message == “Steve Cooper says injecting properties is fun!”

    So you’ll see this weird thing on the end of the format string that looks like a double-chevron. This is supposed to look like a double arrow, pushing values into the format string. In fact, it’s the [Bopomopho letter ‘G’][g] and therefore a perfectly normal C# method name.

    Here’s the code for the double-chevron method. I say again, this is _just a proof of concept_, not production code. Use at your own peril. (In fact, don’t use. Write your own. It’ll be more solid.)

    public static class StringFormatting
    {
    public static string ㄍ(this string format, object o)
    {
    var rx = new System.Text.RegularExpressions.Regex(@”{(?w+)}”);
    var match = rx.Match(format);
    while (match.Success)
    {
    string name = match.Groups[“name”].Value;
    format = format
    .Replace(“{“, “{{“)
    .Replace(“}”, “}}”)
    ;
    format = format.Replace(“{{” + name + “}}”, “{0}”);

    object prop = o.GetType().GetProperty(name).GetValue(o, null);
    format = string.Format(format, prop);
    match = rx.Match(format);

    }
    return format;
    }
    }

    [skeet]: http://msmvps.com/blogs/jon_skeet/default.aspx
    [op]: http://msmvps.com/blogs/jon_skeet/archive/2009/01/23/quick-rant-why-isn-t-there-an-exception-string-params-object-constructor.aspx
    [g]: http://www.alanwood.net/unicode/bopomofo.html

←Previous Page
1 2 3 4 5 6 … 18
Next Page→

Blog at WordPress.com.

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
 

Loading Comments...
 

    • Subscribe Subscribed
      • Steve Cooper's Personal Blog
      • Already have a WordPress.com account? Log in now.
      • Steve Cooper's Personal Blog
      • Subscribe Subscribed
      • Sign up
      • Log in
      • Report this content
      • View site in Reader
      • Manage subscriptions
      • Collapse this bar