Category: General

  • Google easter eggs

    Try google "recursion". Google in pig latin. My code hero, Ken Perlin, has contributed with a easter game. And finally, use the features of Google to download music! Also, check out these strange search suggestions.

  • How to upload a file

    First I must mention that this is my first ever blog post using Windows Live Writer. The topic was inspired by a question that was raised on the MSDN forums. How do I upload a file, and how can I control the remote filename? This is how it could be done:

    'The full path to the source file.
    Dim Source As String = "C:\MyFiles\SourceFile.txt"
    
    'The full destination path (will be created).
    Dim Destination As String = "ftp://www.myserver.com/myfolder/destination.txt"
    
    'Use the static (shared) method Create to create a web request.
    'Pass the destination as an argument, and cast it to a FtpWebRequest.
    Dim R As System.Net.FtpWebRequest = CType(System.Net.WebRequest.Create(Destination), _
    System.Net.FtpWebRequest)
    
    'Tell the request how it will login (using a NetworkCredential object)
    R.Credentials = New System.Net.NetworkCredential("myUsername", "P@ssw0rd")
    
    '...and what kind of method it will represent. A file upload.
    R.Method = System.Net.WebRequestMethods.Ftp.UploadFile
    
    'Here I use the simplest method I can imagine to get the
    'bytes from the file to an byte array.
    Dim FileContens() As Byte = System.IO.File.ReadAllBytes(Source)
    
    'Finaly, I put the bytes on the request stream.
    Using S As System.IO.Stream = R.GetRequestStream()
       S.Write(FileContens, 0, FileContens.Length)
       S.Close()
    End Using

    You could increase the level of control by replacing the ReadAllBytes call with some own code to read the bytes. This might be interesting if you’re for example are handling larger files, and want to show progress. To give away all control, you can use the already build function My.Computer.Network.UploadFile.

  • Evolution debate, Fria Tidningen

    This Saturday, I had the honor to write a reply in an ongoing debate on evolution in a Swedish magazine, Fria Tidningen. Check it out here (in Swedish)!

  • Mitt sista ord om IE

    Mitt sista ord om IE – lite gnäll innan jag går vidare. Jag använder Internet Explorer 8 i detta klipp. Förra inlägget finns här.

    En vacker dag kommer jag antingen titta tillbaka på detta med ett leende, eller få äta upp min dumdristighet. 😉

    Internet Explorer 8 och Acid2.

    Internet Explorer 8 och Acid3.

    Internet Explorer 8 och HTML 5.

  • An evening with my wife, for once

    After work with my colleges was canceled, but my wife’s meeting this afternoon was also canceled, so we used this opportunity to grab a few beers and some food at our local restaurant. It is new, so this was the first time. Only the food was a smaller fortune, so perhaps it will be a while before I visit them again, but I will have an after work with my friends at VoF tomorrow (Vetenskap och Folkbildning – a Swedish pro-science association). I am looking forward to that. My children are downtown, to the cinema.

    Office hours are now used for programming a new business system, I am very excited about that. We are using all the cool stuff in this application; a SQL Server database, a great web service and a thick client (Windows Forms). Evenings spent looking at F# examples. I am not sure that I will be using it, but I feel that I need to know it and to be able to work it.

  • Link detection in my Twitter script

    I’ll just get on with my ASP3 Twitter reader written in VBScript so that I can leave the past behind me again. The first part is here.

    VBScript version 5 has simple and good Regex support. Some features are missing, but it’s good. It is available through a class called RegExp, like so:

    Set R=New RegExp

    This is the basic concept (to run it, just add these lines and the line above to a vbs-file):

    'What do I want to search for? Use the Pattern property.
    R.Pattern="a"
    
    'Case insensitive.
    R.IgnoreCase=True
    
    'Do the replacement and show the result in a message box.
    MsgBox R.Replace("String to search", "(new value)")
    
    'Case insensitive.
    R.IgnoreCase=True
    
    'Do the replacement and show the result in a message box.
    MsgBox R.Replace("String to search", "(new value)")

    To do the detection, I’ll use this script, downloaded from here:

    (ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?

    And here is the working code:

    <%
    'Create and configure the DOM Document.
    Set D = Server.CreateObject("MSXML2.DOMDocument.3.0")
    D.async = False
    D.setProperty "ServerHTTPRequest", True
    D.validateOnParse = True
    D.preserveWhiteSpace = False
    
    'Download XML data (pointing to the user's RSS feed).
    Rss="http://twitter.com/statuses/user_timeline/33177615.rss"
    If Not D.Load(Rss) Then
    
     'Download failed.
     Response.write "<p>We can not connect to Twitter right now.</p>"
    
    Else
    
     'Downloading went well. Extract the tweets.
     Set TweetList = D.getElementsByTagName("item")
    
     'Keep track on tweet count - I want to display five of them.
     TweetCount = 0
    
     'Create the Regex object and set the pattern.
     Set R = New RegExp
     R.Pattern = "(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?"
    
     For Each TweetNode In TweetList
      TweetCount = TweetCount + 1
    
      'Extract the items from the tweet node.
      Dt = TweetNode.childNodes(2).text
      Text = TweetNode.childNodes(1).text
    
      'If I want it, the feed contains the URL to the tweet.
      Url = TweetNode.childNodes(4).text
    
      'This is one of the ugly bits - I don't parse the date, I just grab the part that I want.
      Dt = Server.HtmlEncode(Mid(Dt,1,22))
    
      'The tweet starts with my username followed by a colon. I don't want that either.
      Text = Server.HtmlEncode(Mid(Text,13,Len(Text)))
    
      'Link detection!
      Set Matches = R.Execute(Text)
      If Matches.Count > 0 Then
       For I = 0 To Matches.Count - 1
        Text = R.Replace(Text, "<a href=""" & Matches(I) & """>" & Matches(I) & "</a>")
       Next
      End If
    
      'Display it!
      Response.Write "<p><b>" & Dt & "</b><br />" & Text & "</p>"
    
      'And just quit when five tweets are displayed.
      If TweetCount>=5 Then
       Exit For
      End If
     Next
    
     'Release reference to tweet list.
     Set TweetList = Nothing
    
    End If
    
    'Release reference to DOM object.
    Set D = nothing
    %>
  • Intermission

    Before jumping on to the URL detection in Classic ASP (using VBScript), I would like to point out Mikael Söderström’s piece on named arguments and optional parameters in C# 4. Both features are old Visual Basic possessions.

    Again, thanks for a great MCT/MVP Summit, Johan Lindfors. Dag König is a skillful educationalist, and there are lots of things to say about the news in Visual Studio 2010 and the .NET Framework 4.0.

  • Old meets new: Twitter and ASP3

    I had a business case to display a Twitter feed on an ASP3 (VBScript based) page. The code contains a few sticky passages, but all in all it went very well many thanks to the enormous COM toolkit that Microsoft provides. This is how it can be done:

    <%
    'Create and configure the DOM Document.
    Set D = Server.CreateObject("MSXML2.DOMDocument.3.0")
    D.async = False
    D.setProperty "ServerHTTPRequest", True
    D.validateOnParse = True
    D.preserveWhiteSpace = False
    
    'Download XML data (pointing to the user's RSS feed).
    Rss="http://twitter.com/statuses/user_timeline/33177615.rss"
    If Not D.Load(Rss) Then
    
      'Download failed.
      Response.write "<p>We can not connect to Twitter right now.</p>"
    
    Else
    
      'Downloading went well. Extract the tweets.
      Set TweetList = D.getElementsByTagName("item")
    
      'Keep track on tweet count - I want to display five of them.
      TweetCount = 0
    
      For Each TweetNode In TweetList
        TweetCount = TweetCount + 1
    
        'Extract the items from the tweet node.
        Dt = TweetNode.childNodes(2).text
        Text = TweetNode.childNodes(1).text
    
        'If I want it, the feed contains the URL to the tweet.
        Url = TweetNode.childNodes(4).text
    
        'This is one of the ugly bits - I don't parse the date, I just grab the part that I want.
        Dt = Server.HtmlEncode(Mid(Dt,1,22))
    
        'The tweet starts with my username followed by a colon. I don't want that either.
        Text = Server.HtmlEncode(Mid(Text,13,Len(Text)))
    
        'Display it!
        Response.Write "<p><b>" & Dt & "</b><br />" & Text & "</p>"
    
        'And just quit when five tweets are displayed.
        If TweetCount>=5 Then
          Exit For
        End If
      Next
    
      'Release reference to tweet list.
      Set TweetList = Nothing
    
    End If
    
    'Release reference to DOM object.
    Set D = nothing
    %>

    This code does not take care of URL detection and such things. I will look into that too (here).

  • The maintainer might be a maniac serial killer

    Most of the times when I code, I actually think that it is good that the language is structured the way it is, because the purpose of the code is so obvious, so I don’t have to worry about the person who will maintain it. I don’t know about you, but sometimes I really get struck by the feeling that some particular piece of code, will be a problem for the one that is going to understand what is going on, to be able to maintain. Maybe the code is segmented in the wrong way or for the wrong reason, or maybe the code is an invention that might as well be credited to Dr. Horrible. I stumbled upon this tip-of-the-day, and realized that I’m not alone:

    Always code as the if the person who will maintain your code is a maniac serial killer that knows where you live.

  • Hyckleriet kring arternas uppkomst

    Ett debattinlägg på hyckleriet kring arternas uppkomst är publicerat på Newsmill.

  • Ett vykort

    Ett vykort

    Eftersom jag inte kommer hinna med att blogga något denna vecka, så bjuder jag på ett vykort istället. Min minsta var imponerad över att man såg sig själv på skärmen när man filmade med Windows Movie Maker, så han bjöd på en riktig teater. Gissa om jag ska visa honom detta om 15 år.

    Edit: I wonder when those Twitter guys will get their things together and do something that works…?

  • Ut till torpet

    I morgon bitti flyttar jag och familjen ut på torpet för det som är kvar av sommaren. Med undantag av några utflykter, är det där vi kommer att spendera sommaren. Jag hoppas att komma loss till min kompis Björn B. för lite gaming (det brukar bli Heroes III eller IV och något Xbox. Detta innebär för min del att jag blir ganska frånvarande på nätet. Jag har konfigurerat datorn så att min telefon kan jobba som 3g-moden, men det är arbetsgivaren som betalar detta kalas per megabyte, så jag kommer troligen vara försiktig med att följa bloggarna under denna tid. 1-2 gånger per dag kommer jag att snegla på mailen.

  • Internet Explorer 8

    Jag älskar verkligen Microsoft och (nästan) alla deras produkter. Det måste alltid sägas för att slippa en onödig politisk diskussion som annars följer lika säkert som solen går upp, när man sagt något negativt. Jag tolkar det som ett tecken på att företaget har många fans, vilket glädjer mig. Ok? Bra. Till saken. Internet Explorer har mer och mer utvecklats till ett hån mot sina användare. Ni som kör den, vet att den inte är speciellt svarsbenägen (små irriterande fördröjningar när man mittenklickar på länkar och att inbakade script tynger ner sidan) och att den inte kan visa nyare hemsidor. Är man van IE-användare är det inte konstigt att man blir riktigt glad över att IT-stressen släpper när man surfar med t.ex. Chrome 3 eller FireFox 3.5 – webbläsare som fungerar snabbt och visar sidorna snyggt. Tydligen är inte bra webbläsare något konstigt, de flesta som finns idag är bra, men man tänker inte på det eftersom man är van med IE8. Och som dessa tester visar, är inte IE8 “i kölvattnet” eller “lite sämre”. Det är skit, och det är märkligt att man inte lagt ner denna produkt. Att jämföra IE8 med FireFox 3.5 är betydligt löjligare än att kalla Edit för MS-DOS för en ordbehandlare och jämföra den med Microsoft Office 2007. Samtidigt illustrerar IE slutanvändarnas flexibilitet. Den finns där och den fungerar (med lite god vilja), och för de som inte tagit sig besväret att testa något annat, är IE dörren ut till World Wide Web. Min personliga uppfattning är att Microsoft antingen bör träda åt sidan eller göra sen entré med något nytt, något bra. Ni som kör IE förtjänar så mycket bättre. Avslutning här.

  • Hur ser min blogg ut egentligen?

    Så här renderas den i FireFox 3.5:

    (Shiretoko 3.5, Chrome 3.0 och Minefield 3.6 visar sidan på exakt samma sätt som FireFox 3.5.)

    Så här renderas den i Internet Explorer 8, aningen plattare och kantigare än FireFox:

    (Avant 11 och K-Melon 1.5 visar sidan på exakt samma sätt som Internet Explorer 8.)

    Notera att Seamonkey 2 visar skuggor, men inte runda hörn:

    (Opera 11 visar sidan på exakt samma sätt som Seamonkey 2.)

  • VbsEdit

    Detta är kanske lite löjligt att ta upp halvägs in på år 2009, men jag har märkt att det finns personer som producerar grafik med scripting, en del riktigt komplexa saker med typ MathLab eller liknande.

    Eftersom jag ändå tänker ta lite bloggpaus nu, för att njuta av solen tillsammans med familjen, så kan jag berätta att jag i min naivitet tror att man kan komma ganska långt med VbsEdit och ett välskrivet COM-bibliotek. VbsEdit är ganska trevlig att jobba med. Den läser lydigt in typbiblioteken när den stöter på en CreateObject, den har auto list members, och den uppdaterar när man komplerar om inne i Visual Studio.

    Det andra som jag redan plockar med, som ska bli mitt semesterprojekt, är en image hosting-tjänst på svenska, med ett API man kan ladda hem för att bygga egna applikationer på tjänsten. Det hela består av en hemsida och en web service mot en SQL-databas på serversidan, och en .NET-dll på klientsidan.

    Jag hoppas att min nästa post här blir en bild på mig själv där jag njuter i solen.

  • Can a cat give birth to a dog?

    Again a post in Swedish. A reply to the argument that evolution is wrong because cats don’t give birth to dogs, used by Kent Hovind among others.

    Artbildning: Kan en katt föda en hund?

  • Late binding when Option Strict is On

    Once you have an object, you can dynamically decide what method to call, or property to use, by calling the InvokeMember function of the object’s type. In this example, I call the ShowDialog method of the object. Note that object members (non static) must have target instance, in my case X.

    Dim X As New Form1()
    Dim T As Type = X.GetType()
    T.InvokeMember(“ShowDialog”, Reflection.BindingFlags.InvokeMethod, Nothing, X, Nothing)

    How you do things with COM objects that you don’t have a reference to, depends on if you are using Visual Basic in strict mode or not. If option strict is off, this code will actually run:

    Dim X As Object = Microsoft.VisualBasic.Interaction.CreateObject(“ADODB.Connection”)
    X.ConnectionString = “Hej”

    If option strict is on, you will get an error telling you that you can’t do late binding when option strict is on. You can, you just have to do it through the InvokeMember function of the type.

    Dim X As Object = Microsoft.VisualBasic.Interaction.CreateObject(“ADODB.Connection”)
    Dim Args() As String = {“Hej”}
    X.GetType().InvokeMember(“ConnectionString”, Reflection.BindingFlags.SetProperty, Nothing, X, Args)

    With this, you can build programs that use for example Microsoft Word if it is installed, but still can run if it isn’t.

  • Beer after work

    I wonder why I don’t do this more often. A beer after work gives you a chanse to test ideas and talk through more or less successful strategies. I love it.

  • Swedish creationist to the parlament

    Sorry for doing this in Swedish, but basically I’m just whineing about the Christian Democratic Party in Sweden, who wants to send a creationist to the EU parlament.

    Ella Bohlin – En svensk kreationist i Europaparlamentet

  • Filename is the sorce in the jukebox

    There is one oddity in the WinAmpJukebox that I am planning on leaving in. That is the code for determining the artist name and the song name. For this, I do not use the meta data in the MP3/WMA-file, I use the filename, consequently. I use a program called Mp3tag to manage my songs, and I am actually quite indulgent on managing the meta data, but very picky on managing the file name. So this oddity works for me, wild protests might make reconsider.

    I use CDEx to copy my CD:s to to the hard drive, and it lets me specify how I want the file to be named. I prefer this setup: %1\%2\%7. %1 – %4

    Meaning: A folder with the name of the artist (as registered in CDDB), a subfolder with the name of the album, and the song is named after the tracknumber, the artist name and the song name. For example:

    ..\My Music\MP3\Queen\A Night at the Opera\01. Queen – Death on two legs.wma

    This is how it is I currently extract the information from the full path to display it in the jukebox:

    1. Remove the file ending.
    2. Remove any starting number. I use a Regex to detect these two variants:

    “07-In the Neighborhood”
    “07. In the Neighborhood”

    3. If the filename contains a minus separated by two spaces, assume that the artist name and the song name is found, otherwise I assume that the containing folder has the same name as the performing artist.

    This rimes quite well with what you would expect from a jukebox. A disk with a bunch of artist directories, with a few songs in each of them, or possible some genre directories at the root level. But again, protests might make me change this, but for now, I like it a lot.

  • Two clips: Yor and Onion fire cause

    In this clip, The Onion sets thing straight on who started a devastating fire. And in this clip from The Spoony Experement, we get a nice review of Yor – The Hunter From The Future. Enjoy! (I did.)

  • Market it as more primitive than it really is?

    The Sweex digital photo frame MM008 v2 is a great little product, but one thing puzzles me. All the specifications and documentations that I have found on it, states that the display is 480×234 pixels. Anyone who has viewed a 480×234 picture can see that this is not the case. It took me a while to count the pixels on the display, but now I am under the impression that it actually has 480×270 pixels. That is 17.280 pixels more! Why would you ever want your potential customer to think that the product has less capacity than it actually has? And don’t get me started on the time I spent on counting pixels by producing strange pictures in different sizes with special patterns to detect if and how the photo frame interpolated the picture. Phew.

  • The one and only jukebox

    I am very exited about my new jukebox. For perfect playback, it is implemented as an addon to WinAmp. WinAmp is free, and I can take care about the playback later (if ever). It is intended for use on parties, and it prevents that one person picks all the music.

    Of all players that I could have chosen for making an addon to, why WinAmp? Because of the output plugin called SqrSoft Advanced Crossfading! A superb and very intelligent crossfader! If you haven’t got it, get it!

    So, why crossfading?

    If you allow a blank space between songs, people that attends to the party will do one (or both) of the following:

    • Fiddle with the stereo.
    • Go home.

    Crossfading prevents this. Check out for the download, it will be posted soon.

  • Leonard Cohen

    I samband med att Leonard Cohen släppt en ny liveskiva med tillhörande dvd har jag bestämt mig för att lyssna in mig lite på honom. En kollega ser till att jag får låna.

    Företaget har ny hemsida ute! Jag hoppas inte reklambyråns folk blir irriterade på att vi gick igenom hur den renderades, utan plikttroget åtgärdar så att det blir bra. Jag tycker vi har lyft oss, och den nya logotypen håller på att sjunka in. Den syns bättre på håll, och den är lite futuristisk.

  • The differences, part 2

    Visual Basic 9 and C# 3.5 has much in common, and I suspect that they will differ more in the future. I have pointed out some current differences, like completion lists, object initializers, deep XML support and declarative events.

    A few more VB-specific features:

    Properties with parameters is an odd feature. By creating an object with parameterized properties you can give the impression that the object has different object with indexers as members. Properties with parameters can not be accessed from C#. A property with two parameters can look like this:

    Public Property MyProperty(ByVal X As Integer, ByVal Y As Integer) As String
        Get
        End Get
        Set(ByVal value As String)
        End Set
    End Property

    The My namespace in Visual Basic is an extensible namespace with hierarchical arranged functions. It is loaded with function to manage sound, file transfers and other handy things, and you can extend it by simply creating hidden modules under the My namespace.

    Optional parameters in functions is a feature that has been around in Visual Basic for a long while, that will be available in C# version 4. This shows how to only pass the sixth parameter to a function:

    DoSome(, , , , , 55)

    Aditionally, you can clarify by naming the argument. This example also calls the sixth parameter (called B in this example):

    DoSome(B := 55)

    Named arguments will also be available in C# 4, with slightly different syntax (loose the colon).

  • Back to FF

    Since I just gave up Google Chrome (there is nothing wrong with it – it has a great script engine) and moved back to Firefox, I just had to try out some new addons. This post is made using Deepest Sender, so in a while I will be able to say whether I like it or not. Seems to do strange things with my post. I have just installed Power Twitter that added some new buttons to the Twitter site, thanks for that. I have also just uninstalled the TwitterBar since accidental clicks lead to strange tweets. Apparently, TwitterBar was designed for the I-only-click-on-something-when-I-really-really-mean-it kind of person.

    The downsides of going back: Where do I make the setting that tells Firefox to stat on the current tab, when I middelclick on a shortcut? It stays when I middleclick on a link! And yes, Chrome is much faster.

  • Life in Swedish

    I have finally completed the Swedish version of my primitive article on John Conway’s Game of Life. The English version is located here, and the Swedish version is here (external link).

  • John Conway’s game of life

    John Conway’s game of life is the simplest known self-organizing system, and it is a good example of evolution. Just like evolution, the environment decides the fitness of the organism. In the case of evolution, the parameters that describe fitness are complex, and in John Conway’s game of life, they are very simple. The game consists of an area of cells. A cell with too few neighbours (none or one) dies from loneliness, a cell with too many neighbors dies from overcrowding. A cell with two or three neighbours survives and an empty space with two neighbours becomes a cell. So the game of life is an infinite iteration of applying rules and adding energy, just like the physical world is. When you start with a world with randomly added cells, and you apply the rules on the world time and time again, the cells will form structures that are more or less stable. A stable structure can be very simple or rarely very complex. If a structure is moving, it can collide with another structure and perish, or form a new structure. Some structures, stable or unstable, form new structures.

    Math.com writes about John Conway’s game of life here. If you have Java installed, you will able to watch the behavior of a few stable structures.

    The following source code (Visual Basic 9) illustrates how simple the games is, and please notice that there is no implementation of intelligence. Intelligence is simply not required to make complex structures. The code is written in a class that inherits from the System.Windows.Forms.Form class.

    'The resources are a 2D map of bytes, a timer
    'and a delegate (for technical reasons).
    Private World(400, 400) As Boolean
    Private WithEvents T As System.Timers.Timer
    Private Delegate Sub DrawBitmapDelegate(ByVal B As System.Drawing.Bitmap)
    
    Private Sub Form1_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
    
    	'Start off by placing some (about 11,000) random cells in the world.
    	Dim Rnd As New Random()
    	For I As Integer = 0 To 11000
    		World(Rnd.Next(60, 341), Rnd.Next(60, 341)) = True
    	Next
    
    	'Create a timer - one generation lasts for 20 ms.
    	T = New System.Timers.Timer(20)
    	AddHandler T.Elapsed, AddressOf DoGeneration
    	T.Start()
    
    End Sub
    
    Private Sub DoGeneration(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    
    	'Appy the rules of the simulation on the cells in the world.
    	ApplyRules()
    
    	'Display the world on the screen
    	'(that is, copy to a bitmap, draw the bitmap).
    	DrawWorld()
    
    End Sub

    This makes the main program. The following code defines the functions that are called (ApplyRules and DrawWorld) followed by the functions they call in their turn.

    Public Sub ApplyRules()
    
    	'Create a temporary buffer for the new world.
    	Dim TempWorld(400, 400) As Boolean
    
    	'Apply the rules of the world to that new buffer.
    	For Y As Integer = 0 To 400
    		For X As Integer = 0 To 400
    			Select Case CountNeighbours(X, Y)
    				Case 0, 1
    					'With no or one neighbour, the
    					'cell dies of loneliness.
    					TempWorld(X, Y) = False
    				Case 2 'Two neighbours means survival.
    					TempWorld(X, Y) = World(X, Y)
    				Case 3 'Three neighbours: Birth of a new cell.
    					TempWorld(X, Y) = True
    				Case Else
    					'With four or more neighbours, the cell
    					dies from overcrowding.
    					TempWorld(X, Y) = False
    			End Select
    		Next
    	Next
    
    	'Save the changes by making the temporary buffer permanent.
    	World = TempWorld
    
    End Sub
    
    Private Sub DrawWorld()
    
    	'Let the world vector become pixels on a bitmap.
    	Using B As New System.Drawing.Bitmap(401, 401)
    		For Y As Integer = 0 To 400
    			For X As Integer = 0 To 400
    				If World(X, Y) Then
    					B.SetPixel(X, Y, Color.Black)
    				Else
    					B.SetPixel(X, Y, Color.White)
    				End If
    			Next
    		Next
    			'Draw the bitmap on the screen. A thread shift must be done.
    		Dim D As New DrawBitmapDelegate(AddressOf DrawBitmap)
    		Me.Invoke(D, B)
    	End Using
    
    End Sub
    
    'This method does the actual drawing, on a the GUI thread.
    Private Sub DrawBitmap(ByVal B As System.Drawing.Bitmap)
    	Using G As System.Drawing.Graphics = System.Drawing.Graphics.FromHwnd(Me.Handle)
    		'Apply some magnification while doing the actual drawing.
    		G.DrawImage(B, New Rectangle(0, 0, 800, 800), _
    		New Rectangle(0, 0, 400, 400), GraphicsUnit.Pixel)
    	End Using
    End Sub
    
    Private Function CountNeighbours(ByVal X As Integer, ByVal Y As Integer) As Integer
    	Dim Ret As Integer = 0
    	For NY As Integer = Y - 1 To Y + 1
    		For NX As Integer = X - 1 To X + 1
    			If Not (NY = 0 And NX = 0) Then
    				If NY >= 0 And NY <= 400 And NX >= 0 And NX <= 400 Then
    					If World(NX, NY) Then
    						Ret += 1
    					End If
    				End If
    			End If
    		Next
    	Next
    	Return Ret
    End Function

    Another example is posted here.

  • From Xerox to Apple

    Webdesigner Depot shows a short, nice and well illustrated history of graphical user interfaces for operating systems. Apart from the obscure Alto, it starts off with the famous 8010 Star from Xerox from 1981. Impressive stuff! Check it out!

  • Stars do Songsmith

    Microsoft Research has a new cool and helpful application that writes music to a melody. Just sing, and Songsmith writes the music – the commersial is sort of corny. What happens if you run well known songs through Songsmith?

    Billie Jean by Michael Jackson
    Eye of the tiger by Survivor
    Hotel California by The Eagles
    Crazy train by Ozzy Osbourne
    We will rock you by Queen

    Sometimes Songsmith actually improves the song.

    I kissed a girl by Katy Perry

  • Anders laddar upp en låt på YouTube

    Denna händelse skulle kunna beskrivas i flera spaltmeter av text, innehållande detaljerade beskrivningar på hur jag letar efter var man ska klicka, om hur jag tror att allt har hängt sig, o.s.v… Till slut lyckades jag ladda upp detta gamla nummer på YouTube! Hoppas att det kan bli mer snart! Apart

    Dagens ros går till Staffan för att han hjälpte mig med att ta fram en ny layout till evolutionsteori.se!

  • Hur laddar man hem upphovsrättsskyddad musik utan torrents?

    Hur laddar man hem upphovsrättsskyddad musik utan torrents?

    Med eller utan The Pirate Bay eller torrents, kan man enkelt och snabbt ladda hem upphovsrättsskyddad musik. Nu drar rättegången mot The Pirate Bay igång, och fälls de, så borde de få konsekvenser även för Google. Låt säga att jag vill ladda hem Radio ga-ga av Queen.

    Jag börjar med att surfa till Google och knappar in detta i sökrutan:

    -inurl:(htm|html|php) intitle:”index of” +”last modified” +”parent directory” +description +size +(wma|mp3) “queen”

    Med detta säger jag att jag vill filtrera bort de vanligaste dokumenten, att det är ett musikarkiv jag vill  söka i, att det ska vara musik, och att ordet “queen” ska förekomma i resultatet.

    Första träffen ger mig en katalog med musik av Queen. Jag klickar på den.

    Nu ser jag en grön och fin sida, där just Radio ga-ga ligger överst. Jag klickar på den.

    Ett litet popup-fönster med reklam visas. Underst i det lilla fönstret finns en länk med texten “download”. Ljuv musik…

    Ladda inte hem upphovsrättsskyddat material, men fundera gärna på upphovsrättens kompatibilitet med Internet. Det där med att både ha och äta kakan…

  • Office-race

    Det händer inte ofta, men denna helg har jag varit barnfri. Jag utnyttjade den tiden till att ligga i soffan och se samtliga avsnitt av The Office, vilket tog sex timmar. Så kunde en normal dag se ut för 15 år sedan, innan man hade barn. Jag lyckades även göra en uppgradering av PhotoName i morse. Jag är själv igång att organisera och säkerhetskopiera gamla bilder, så jag sitter och väger på vilka funktioner man ska bygga in i programmet; det finns massor som skulle vara värdefullt. Men grundtanken, att lyfta ut fotodatum till filnamnet för att konsekvent bevara bildernas kronologi, är det viktigaste.

  • Tuff vecka

    Detta var en hektisk vecka på jobbet. Den utlovade lågkonjunkturen som går jag fortfarande och väntar på. Min avdelning på jobbet spelade lite curling och tog ett par öl efter jobbet igår, och vem är jag att inte knäppa lite med mobiltelefonen?