https://xkcd.com/1312/

The WebBrowser nightmare

I recently had to use the WebBrowser .NET component in a project. The control is essentially Internet Explorer embedded in a UserControl component. Although the facilities for JavaScript interoperability and DOM manipualtion are pretty great, the control fails to meet simpler needs.

To override keyboard input handing in the control, we need to set the WebBrowserShortcutsEnabled property to false and handle the PreviewKeyDown event.

Continue reading →

Abstract and parameterized types

Scala supports both abstract and parameterized types, which are essentially revamped generics (in Java) or templates (in C++).

First off, methods can be parameterized, in order to abstract a generic type which can be used by it. The apply method in companion objects is the best place to start. Here's an example from the implementation of the List class in the Scala library.

object List {

  // ...

  def apply[A](xs: A*): List[A] = xs.toList
}
Continue reading →

61 byte selection sort

Here's the absolutely smallest array sorting function in C. It's written by M. Doughlas McIlroy of Darthmouth College, NH USA. It only 67 bytes long (ignoring new-line characters), which is ridiculously impressive. In the function s shown below, a is the starting address of the array, and b is the address of the last element plus one.

s(int*a,int*b)
{for(int*c=b,t;c>a;)if(t=*c--,*c>t)c[1]=*c,*c=t,c=b;}

This can be made even smaller using recursion and by inferring the type specifiers of global object declarations, which is a GCC hack. In the following function, n is the number of elements in the array a.

Continue reading →

Network packets with Python

Next week, I'll have to start a project on implementing RIP (Routing Information Protocol) using UDP sockets in C. I needed a quick way to get the byte structure of RIP packets, and decided to use scapy. It's quite a handy tool and has a simple interface, which is nothing more than an extended Python shell. Auto-completion is supported out-of-the-box, which is good news for all the command-line enthusiasts out there. Here's how we dump an RIP packet straight to a PDF file.

$ scapy
Welcome to Scapy (2.3.3)
>>> entry = RIPEntry(addr='192.168.1.10', nextHop='192.168.1.1', mask='255.255.255.0')
>>> entry.show()
###[ RIP entry ]###
  AF= IP
  RouteTag= 0
  addr= 192.168.1.10
  mask= 255.255.255.0
  nextHop= 192.168.1.1
  metric= 1

>>> r = RIP() / entry
>>> r.pdfdump()

This generates a self-explanatory packet dump. You could also use a different reader; just change the conf.prog.pdfreader object.

Continue reading →