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.