Thursday, August 30, 2012

VB.NET cheat sheet

I've been doing quite a bit of programming in VB.NET recently. It's almost exactly the same as C# but a few things have caught me out. I've written up a small cheat sheet with the noticeable differences (plenty of websites will give you a huge list of irrelevant differences).

Keywords

C#VB.NET
thisMe
baseMyBase
abstractMustOverride/MustInherit
virtualOverridable
sealedNotInheritable
class Class : InterfaceImplements (statement)
internalFriend
staticShared
typeof()GetType()

If you want a static class in VB.NET, you'll need to use the Module keyword.

(One thing to note here is how much more intelligible some of the VB.NET keywords are.)

Logic

C#VB.NET
&&AndAlso
||OrElse

There is no equivalent for And and Or in C#.

Numeric type suffixes

C#VB.NET
12.34M (for Money)12.34D (for Decimal)
12.34D (for Double)12.34R (for Real)

Lambdas

C#apples.Single(x => x.Colour = "red")
VB.NETapples.Single(Function(x) x.Colour = "red")

Initialising lists and objects

C#var apple = new Fruit { Colour = "green" };
VB.NETDim apple = New Fruit With {.Colour = "green"}

C#var apples = new List { new Fruit { Colour = "red" }, new Fruit { Colour = "green" } };
VB.NETDim apples = New List(Of Fruit) From {New Fruit With {.Colour = "red"}, New Fruit With {.Colour = "green"}}

Anonymous types

C#apples.Select(x => new { Colour = x.Colour });
VB.NETapples.Select(Function(x) New With {.Colour = x.Colour})

Nulls and Nothing

If you're coming from C#, the Nothing keyword does not do what you'd expect. What would you expect the following code to do?

Dim value = ""
If value = Nothing OrElse value Is Nothing Then
    Throw New Exception()
End If

If you said "not throw an exception" you'd be wrong. Weirdly, the first condition is true but the second condition is false, so it throws. Compare with similar C# code:

var value = "";
if (value == null)
    throw new Exception();



In this case, the exception doesn't get thrown.

Monday, August 27, 2012

Barrett is an idiot

I spent 1.5 hours of my life last week listening to people talk about the "Seven Levels of Consciousness".

Richard Barrett, a man lacking wits but making up for it with entrepreneurial enthusiasm, has improved the old pyramid model of Maslow (the hierarchy of needs) by creating an hourglass model.

Old:

Improved:


One will instantly see the superiority of this new model. For one thing, it's symmetrical. And it has circles. If there is anything more scientific than pyramids, it's circles. And the number seven.

I have to say how impressed I am. Barrett has taken a relatively meaningless concept, the hierarchy of needs - wholly unproven and unprovable - and improved it by extension and inversion via the science of the Vedas. If it's science you're after, an ancient holy text is the best place to look. He's melded religious myth and pseudo-science and made a business out of it, selling it to morons world-wide.
Vedic science specifies seven levels of consciousness. These are waking, sleeping, dreaming, soul consciousness, cosmic consciousness, God consciousness and unity consciousness. It appeared to me that the descriptions of the last four of these levels of consciousness described the underlying features of self-actualisation. (From Maslow to Barrett)
One could wonder how this sort of garbage could become such a integral part of corporate consciousness, especially at the management level. But it's not an anomaly. Business is full of unproven ideas and myth. Modern myth may appear to be especially good targets of ridicule but old myths are no less absurd, merely more accepted because they've been around longer.

Friday, August 17, 2012

Euler problem 19

I started writing this blog entry a year ago. It's about an Euler problem I solved in F#. The code makes more sense to me now than it did a year ago and I haven't touched F# since then. I guess I'm just way smarter now.



Solving Euler problem no. 19 is the solution I'm most proud of. It's the first problem that I solved in F# with no assistance by the 'net.

The problem:
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
It isn't an overly complex problem but there a couple of tricky aspects. The approach that I used was to start on the first Sunday of 1901 (6th Jan) and add seven days over and over (i.e., only counting Sundays) until the end of 2000. I could have used the .NET DateTime type to solve this problem very easily, but I decided to see if I could solve the problem using my own date type.

I solved the problem by using a few F# features, namely:
  • pattern matching
  • tuple
  • record
  • list
The first problem was February. February is a prickly month. Pattern matching will solve it! The febDays function accepts a year as a parameter and returns the number of days that February has.

    let febDays y = match y with
                            | y when y % 400 = 0 -> 29
                            | y when y % 100 = 0 -> 28
                            | y when y % 4 = 0 -> 29
                            | _ -> 28

After February was ready, I needed to know the number of days in any month, given the month (as a number) and the year. I used pattern matching again. Therefore,

    let daysInMonth (m, y) =
            match m with
            | 2 -> febDays y
            | 4 | 6 | 9 | 11 -> 30
            | _ -> 31

The other interesting function was to be able to add a day to a date. I did:

    let addDay date =
        match date.day with
        | d when d < 1 || d > daysInMonth(date.month, date.year) -> failwith "Not a valid day of the month."
        | d when d = daysInMonth(date.month, date.year) -> match date.month with
                                      | m when m < 1 || m > 12 -> failwith "Not a valid month."
                                      | m when m = 12 -> { day = 1; month = 1; year = date.year + 1}
                                      | _ -> { day = 1; month = date.month + 1; year = date.year}
        | _ -> { day = date.day + 1; month = date.month; year = date.year}

The code above isn't the whole solution, but it's the interesting parts. As you can see, I pretty much pattern matched the whole solution. It's a shame that C# doesn't have pattern matching because it's a really powerful language concept.

Wednesday, August 15, 2012

Flat Earth vs Climate Change

The following is an exchange between me and someone I'll call Matt. He has some interesting ideas about climate change... After his response, I didn't think I could take the discussion anywhere else. He's clearly a downer and therefore not amenable to reason.



Well constructed and very much in line with what I think on the topic, particularly the part about The vested interests and the role of the big ball of burning gas above our heads in global warming.

http://www.theage.com.au/opinion/climate-change-science-is-a-load-of-hot-air-and-warmists-are-wrong-20120801-23fdv.html

Gee I’m glad I get to give an extra 500 per year to the government though.

Matt



Matt, I think this debate is distracting you from a much more significant dispute. The real controversy is between those that believe in the Ice Wall and the downers – those believing in the Waterfall. They both have photographic evidence:

Ice Wall:
     







Waterfall:









But whose testimonial can we believe? Personally, I think a British Naval Officer’s account is very convincing:
It would be impossible to conceive a more solid-looking mass of ice; not the smallest appearance of any rent or fissure could we discover throughout its whole extent, and the intensely bright sky beyond it but too plainly indicated the great distance to which it reached southward.
This debate is not simply an Antarctic concern, it has global ramifications that also impacts on the “theory” of global warming. If warmists are correct, the implications of an ice wall is extremely concerning. I think downers are drawn towards their “theory” more because of alarmist fear-mongering than they are by empirical evidence.

It’s even possible that their photo could have been faked!

Patrick



Hi Partick,

Agreed, global warming in all of its various extremist incarnations is distracting us all from much more significant debates and issues.

It is far more relevant deciding what to have for dinner tonight and we can all really make a difference here.

In light of my own experimentation and investigation it is just not possible for me to deny that the earth is warming. Just this morning I had to take about 2mil of ice off my car windows. This time last year, it was probably more like 3mil.

My position is more in line with that of the author of this article.

The question that seems to be supressed at every debate on the issue is:

How much is man kind contributing and how much is a natural cosmic or environmental cycle?

The very idea that man kind may not be directly responsible for global warming is considered heresy! In science! According to our politicians - the science of climate, the most chaotic system known to man, is decided, and we're all to blame.

In truth, what makes me most concerned is that people are tired of hearing about it and cannot fathom the thought that perhaps they have been misled to such a gargantuan degree the very world will never be the same.

It all just makes me so HAPppy!

This article was all about the global ramifications of warmist theories and the rampant misuse/misinterpretation of so called "empircal" data so I very much agree with you - individuals will use populist interpretations of statistics to prove whatever wacky theory pops into their heads.

84% of all people know that.

Friday, August 10, 2012

Computer Othello, Part 5: Resources

This post lists the best info I could find on how to write a computer version of Othello.

General

http://en.wikipedia.org/wiki/Reversi#Rules
Rules for Othello/Reversi

http://chessprogramming.wikispaces.com/Othello
Details on bitboards, hashes, deep-first searches and transposition tables. Contains source code (generally in C or C++)

http://www.radagast.se/othello/howto.html
A description of what is required to implement a better than average computer player.

https://skatgame.net/mburo/ps/compoth.pdf
A paper that describes the best Othello computer players from the 80s and 90s (IAGO, BILL and LOGISTELLO)

Strategy (human and computer)

http://radagast.se/othello/Help/strategy.html
http://www.samsoft.org.uk/reversi/strategy.htm

Implementation

http://users.informatik.uni-halle.de/~jopsi/dass4/
A break-down of the tasks involved in creating an Othello game. Has info on implementing the rules and how the minimax search works.

http://www.dcs.gla.ac.uk/~daw/masters-projects/dissertations/Colquhoun.2008.pdf
Computer science student's paper.

http://www.cs.kent.edu/~jmelnyk/othello/
A description of someone's attempts to write-up Othello depth-first searches (alpha-beta, negascout, MTD(f), Multi-ProbCut, etc.)

Computer player

http://samsoft.org.uk/reversi/openings.htm
A list of the standard Othello openings.

http://xenon.stanford.edu/~lswartz/cs221/desdemona_writeup.pdf
Description of various evaluation strategies.

http://othello.dk/book/index.php/Thor_Database
The Thor database was the only archive of Othello games that I could find on the net.

Finally

If you want to see what I did with this information, there is my source code for Othello. It's fairly well written, the UI looks okay and is easy to use and the computer player plays well. I implemented most things you'd do in a world-class computer player. However, you'd have to make it a lot more efficient, if you wanted to take on those players.

It was interesting, frustrating and fun to try to write a decent Othello game. I learnt a huge amount too.

Thursday, August 9, 2012

Best films I've seen this year

I don't see many new great films anymore. I watched most of the backlog years ago. Only one or two new noteworthy films are released every year. However, I've managed to watch some really good films this year. They are:

El Norte: About Guatemalans that escape to the US via Mexico. Probably the best film I've ever seen about a typical experience of an asylum seeker.

12 Angry Men: A jury discuss a murder they're to give a verdict on. They're stuck in a hot room debating the various accounts of the witnesses. The film must be every liberals favourite film, but that doesn't stop it from being a really exciting unravelling of preconceived ideas. "Nobody wears eyeglasses to bed."

Night of the Living Dead: Original zombie film. It has a simple but really effective plot. Extremely tense.

The Lady Eve: It's a rom com. There are a few cheesy bits, but it's generally pretty funny and endearing.

Frozen Planet (not a film): A nature documentary series about life in the Arctic and Antarctic. It made me appreciate just how utterly brutal life in the natural environment is for every living creature except (most) humans (and some pets). Nature is cruel, violent, and completely indifferent. Creatures spend their lives hungry, hunted, cold and alone.

It made fully realise that rather than trying to emulate (bourgeois rhetoric on markets), admire (people who like natural/organic products), or lament the loss of nature (millenarian and some Green movements) we should thank our lucky stars that we're somewhat removed from that pitiless existence. We should do everything we can to reject the laws of nature (that doesn't, in turn, threaten our existence).

Saturday, August 4, 2012

Hardcore Minecraft

We played multiplayer Minecraft again tonight, after many moons. This time we played in hardcore mode; no re-spawn. It played like the game I've always wanted Minecraft to be. Challenging, tense and satisfying. I definitely want to play more.

A majestic canyon

A field of sheep

Mana from Heaven

My companion's remains. The rock fell out from under him, into lava. He followed.
It was a disturbing, saddening and somewhat guilt-ridden experience.

Friday, August 3, 2012

Troubles with Unity and Mono

Using Unity for my Othello game was not without issues. The biggest issue I experienced related to Unity's use of Mono. Here is why:

A depth-first search generates a lot data. Oridinally, in .NET, that would be fine. You create the data, process it and forget about it - the .NET garbage collector (GC) will release the data from memory when required. That isn't true of Mono 2.6. The garbage collector in Mono 2.6 is kind of rubbish. (See what I did there?) Mono 2.8 has a new garbage collector, but Unity 3.5 uses Mono 2.6. And my Othello game uses Unity 3.5.

For my Othello implementation, every turn by the computer player was a new search. It leaked memory all over the place because the GC wasn't dumping the data. It could easily use a gig of RAM over a game, even with shallow searches (depths of 5 or less).

To resolve this issue, I - though Andrew came up with the idea - used a struct instead of a class for the objects used in the search (EvaluationNode and GameState). I re-used memory by storing search results in arrays where the indexes were reset every turn of the game. This negated the need for garbage collection. In the source code, the classes that manage this process are called the EvaluationNodeBuffer and EvaluationNodeCollection.

These changes turned out to be a really good use and re-use of memory. It is also an excellent example to demonstrate the differences between a struct and a class. It also allowed me to search to much greater depths for the computer player.

A problem with this technique is that it makes it very difficult to write code to re-use part of the search tree between turns. Finding which parts of the tree to prune and to then re-organise the arrays and indexes would be technically tricky and CPU intensive. Therefore, for now, the computer player continues to re-searche all game states between turns. Furthermore, any sort of parallel programming to speed-up the search would be hindered by this approach.

What about Unity 4? That's out soon. Will that support the newer version of Mono? Unfortunately not.
We will be shipping Mono 2.6 with Unity 4.0. This will allow the same subsets of .NET features as in Unity 3, depending on the profile you choose in your player settings. (Unity 4 FAQ)

Thursday, August 2, 2012

The Lello-Lea Hypothesis

The Ice-Wall of Antarctica
A report from the Society:

The standard flat-Earth model (SFEM) postulates an ice-wall beyond Antarctica. SFEM supersedes waterfall theories of other flat Earth models and replaces the controversial spherical-earth conjecture's (SEC) notion of Antarctica as an island continent.

The Lello Hypothesis states: "the universe is a series of flat earths stacked within a vast crystalline cylinder folded back on itself to form a never ending torus. I.e., a cosmic, hollow, ice-donut." The Lea Modification, sometimes known as the Lello-Lea Hypothesis, states that: "interspersed with crystalline water (H2O), exists an abundance of naturally occurring granular material composed of finely divided rock and mineral particulates forming 'deserts' - similar to observable regions on Earth."

It should be noted that these hypotheses are not to be confused with the weaker and frankly implausible set of ideas that A. Hayes has expounded in which a series of flat earths are distributed across the inner surface of a torus of indeterminate extent. Hayes is also known for the infinite cylinder hypothesis (ICH). ICH is perhaps even more unlikely than his inside-out donut.

The Society for the Lello-Lea Toroid Flat Earths Hypothesis is searching for intelligent life on other flat earths. First contact will provide the empirical evidence, and hence proof, of the Lello-Lea Hypothesis. Meanwhile, scientists are formulating a mathematical proof for the minimum quantity of flat earths that must exist.

Chalmers' recent work (unpublished, in correspondence with the author) has yielded a breakthrough on the topic, establishing deep relationships with elliptic curve theory and the calculus of manifolds, while raising the lower bound on the number of flat earths that must exist to -4. We are assured that more revelatory findings are to follow.

It is not expected that the combined forces of the Society and scientists will be able to provide the actual number of flat earths in our toroidal universe. However, we believe that within the next ten years, we will be able to prove that:
  1. We do indeed live in a multi-earth, toroidal universe (i.e., SEC is fallacy.)
  2. There are at least 3 flat earths.
A. Hayes, and others, have proposed expeditions to the Ice-Wall to conduct experimental drilling. A small party would also test a radical SFEM speculation of going "beyond the Ice-Wall." Funding and applications for strategic and/or technical approaches is being sought.