Home
November 22, 2011

Regex Escapees

Sometimes when one writes regexes, Its hard to know what needs to be escaped and what doesn’t. But I’ve solved that problem while I was writing a program that generated my regexes for me. Now I have a snippet that both humans and programs can use to write regexes!

This is for the .NET flavor of Regex.

private static string SanitizeToken(string token)
{
	return token
					.Replace(@"\", @"\\")
					.Replace("*", @"\*")
					.Replace("?", @"\?")
					.Replace("+", @"\+")
					.Replace("{", @"\{")
					.Replace("}", @"\}")
					.Replace("^", @"\^")
					.Replace("$", @"\$")
					.Replace(".", @"\.")
					.Replace("[", @"\[")
					.Replace("]", @"\]")
					.Replace("(", @"\(")
					.Replace(")", @"\)")
					.Replace("|", @"\|");
}
November 22, 2011

Making Color From Alpha, Hue, Saturation and Brightness

I find myself wanting to do this sometimes, so here’s a bit of code (I’m sure I stole this code from somewhere else);

public static Color ColorFromAhsb(int a, float h, float s, float b) {

	if (0 > a || 255 < a) {
		throw new ArgumentOutOfRangeException("a");
	}
	if (0f > h || 360f < h) {
		throw new ArgumentOutOfRangeException("h");
	}
	if (0f > s || 1f < s) {
		throw new ArgumentOutOfRangeException("s");
	}
	if (0f > b || 1f < b) {
		throw new ArgumentOutOfRangeException("b");
	}

	if (0 == s) {
		return Color.FromArgb(a, Convert.ToInt32(b * 255),
			Convert.ToInt32(b * 255), Convert.ToInt32(b * 255));
	}

	float fMax, fMid, fMin;
	int iSextant, iMax, iMid, iMin;

	if (0.5 < b) {
		fMax = b - (b * s) + s;
		fMin = b + (b * s) - s;
	} else {
		fMax = b + (b * s);
		fMin = b - (b * s);
	}

	iSextant = (int)Math.Floor(h / 60f);
	if (300f <= h) {
		h -= 360f;
	}
	h /= 60f;
	h -= 2f * (float)Math.Floor(((iSextant + 1f) % 6f) / 2f);
	if (0 == iSextant % 2) {
		fMid = h * (fMax - fMin) + fMin;
	} else {
		fMid = fMin - h * (fMax - fMin);
	}

	iMax = Convert.ToInt32(fMax * 255);
	iMid = Convert.ToInt32(fMid * 255);
	iMin = Convert.ToInt32(fMin * 255);

	switch (iSextant) {
		case 1:
			return Color.FromArgb(a, iMid, iMax, iMin);
		case 2:
			return Color.FromArgb(a, iMin, iMax, iMid);
		case 3:
			return Color.FromArgb(a, iMin, iMid, iMax);
		case 4:
			return Color.FromArgb(a, iMid, iMin, iMax);
		case 5:
			return Color.FromArgb(a, iMax, iMin, iMid);
		default:
			return Color.FromArgb(a, iMax, iMid, iMin);
	}
}
October 6, 2011

OpenGL weirdness

Try this:

        dispList = glGenLists(1);

        glNewList(dispList, GL_COMPILE);

        for(int x=-768; x<768; x++)
        for(int y=-768; y<768; y++)
        {
            glBegin(GL_QUADS);
                glColor3f((double)(rand() % 100) / 500,
			(double)(rand() % 100) / 100, 0);
                glVertex3i((x)  * 1, (y)  * 1, 0);
                glVertex3i((x+1)* 1, (y)  * 1, 0);
                glVertex3i((x+1)* 1, (y+1)* 1, 0);
                glVertex3i((x)  * 1, (y+1)* 1, 0);
            glEnd();
        }

        glEndList();

and render your display list. Then, try this:

        dispList = glGenLists(1);

        glNewList(dispList, GL_COMPILE);
        glBegin(GL_QUADS);	// <- the subtle difference is here

        for(int x=-768; x<768; x++)
        for(int y=-768; y<768; y++)
        {
                glColor3f((double)(rand() % 100) / 500,
			(double)(rand() % 100) / 100, 0);
                glVertex3i((x)  * 1, (y)  * 1, 0);
                glVertex3i((x+1)* 1, (y)  * 1, 0);
                glVertex3i((x+1)* 1, (y+1)* 1, 0);
                glVertex3i((x)  * 1, (y+1)* 1, 0);
        }
        glEnd();		// <- and here

        glEndList();

I don’t know if its my graphics drivers, or graphics card or perhaps just me, but the top code maxed out at 60 fps while the bottom code ran at ~10 fps.

Oh, and don’t ask me why I’m using display lists.

October 6, 2011

Help! GLEW compiles but doesn’t link!

When you compile the glew_static project from glew on Visual Studio and link it with your program, you may get something like this:

app_init.obj : error LNK2001: unresolved external symbol __imp__glewInit
worldscene.obj : error LNK2001: unresolved external symbol __imp____glewBufferSubData
worldscene.obj : error LNK2001: unresolved external symbol __imp____glewBufferData
worldscene.obj : error LNK2001: unresolved external symbol __imp____glewBindBuffer
worldscene.obj : error LNK2001: unresolved external symbol __imp____glewGenBuffers

It’s easy to fix. Just add GLEW_STATIC to the preprocessor definitions and you’re done. This is because without it the header specifies dllimport instead of just extern, which is needed for static linkage.

September 18, 2011

Why I Prefer Initialization Through Constructors

I always prefer initializing my class through the use of a constructor like this:

class Apple
{
	Color color;
	Taste taste;
	List<string> countries;
	public Apple(Color color, Taste taste, List<string> countries)
	{
		this.color = color;
		this.taste = taste;
		this.countries = countries;
	}
}

void DoSomething()
{
	List<string> grownInCountries = new List<string>();
	grownInCountries.Add("Japan");
	grownInCountries.Add("New Zealand");
	grownInCountries.Add("Poland");
	Apple a = new Apple(Color.Green, Taste.Sweet, grownInCountries);
	DoStuffWith(a);
}

Instead of

class Apple
{
	public Color color;
	public Taste taste;
	public List<string> countries;
}

void DoSomething()
{
	Apple a = new Apple();
	a.Color = Color.Green;
	a.Taste = Taste.Sweet;
	a.GrownInCountries = new List<string>();

	a.GrownInCountries.Add("Japan");
	a.GrownInCountries.Add("New Zealand");
	a.GrownInCountries.Add("Poland");
	DoStuffWith(a);
}

To some, the answer seems obvious: constructors enforce filling in all the fields. To others, it may look like a waste of time and increased complexity to apply the boilerplate: less code = less bugs. Either that or the argument is the class becomes less serialization-friendly.

The C# compiler (or C++ or Java compilers for that matter) provide us with Constructors as a facility to make sure that our fields are all initialized upon construction, besides being able to imply the size required for the data structure to the new operator.

The second example also means that encapsulation has been broken and other classes are free to access the variables within Apple (causing coupling). We could argue that the readonly qualifier could be applied to them, but the “countries” field is a reference type and still modifiable via its own methods.

This way you can avoid forgetting to initialize a certain set of fields. Whenever a field is added, the constructor should also get a parameter, forcing the implementor to ensure that all places that create instances of this class will have to initialize the new field, eliminating a whole class of bugs related to uninitialized variables.

July 4, 2011

First test post from BunnyBlogger

Several moons ago I have been working on a special blogging client, that is capable of wysiwyg blogging and allows you to take snapshots from movie files and add images and other images to your post.

I have only shown this to a few people. But now, I’ve been working to bring it up to user-standard so everyone can benefit from a way to blog quickly, without the waiting for image upload messing with your writing flow.

This is a test post from that very program, entering its beta.

August 10, 2010

Will the destructor be called?

Here’s a C++ quiz for all of you: somefunc() will be called from a thread. Do you think this destructor will be called?

class A {
public:
	A () {
		printf("Constructor\t");
	}

	~A() {
		printf("Destructor\n");
	}
};

int somefunc () {
	A inst;
	int* a = 0
	*a = 1;
	return 0;
}
last comments  
astrobunny
astrobunny

Thanks. Well, assignment isn't neccessary the default constructor will be called upon instantiation
RyanA
RyanA

Killin me, I don't even see the assignment ;; btw, nice theme update :)
June 21, 2010

Idioms

What if

for (int i=0; i<100; i++)
{
	doSomething();
}

// and

for (int i=0; i<100; i+=2)
{
	doSomethingElse();
}

Was

doSomething() for 1..99;
while (i=1,2..99) { doSomethingElse(); };

Would the world be a better place?

December 29, 2009

That’s Not The Point

Today I read an interesting chapter in Writing Solid Code, and it showed an example where a supposed optimization led to code bloat:

To represent the hierarchical window structure, Character Windows used a binary tree in which one branch pointed to subwindwos, called “children” and the other branch pointed to windows with the same parent, called “siblings”:

typedef struct WINDOW
{
	struct WINDOW *pwndChild;	/* NULL if no children */
	struct WINDOW *pwndSibling;	/* NULL if no brothers/sisters */
	char *strWndTitle;
	.
	.
	.
} window;		/* Naming: wnd, *pwnd */

You can turn to any algorithm book and find efficient routines to manipulate binary trees, so I was a bit shocked to when I reviewed the Character Windows code for inserting a child window into the tree. The code looked like this:

/* pwndRootChildren is the pointer to the list of top-level windows
 * such as the menu bar and the main document windows.
 */
static window *pwndRootChildren = NULL;

void AddChild(window *pwndParent, window *pwndNewBorn)
{
	/* New windows may have children but not siblings... */
	ASSERT(pwndNewBorn->pwndSibling == NULL);

	if (pwndParent == NULL)
	{
		/* Add window to the top-level root list. */
		pwndNewBorn->pwndSibling = pwndRootChildren;
		pwndRootChildren = pwndNewBorn;
	}
	else
	{
		/*  If Parent's first child, start a new sibling chain;
		 *  otherwise, add child to the end of the existing
		 *  sibling chain.
		 */
		if (pwndParent->pwndChild == NULL)
		{
			pwndParent->pwndChild = pwndNewBorn;
		}
		else
		{
			window *pwnd = pwndParent->pwndChild;
			while (pwnd->pwndSibling != NULL)
			{
				pwnd = pwnd->pwndSibling;
			}
			pwnd->pwndSibling = pwndNewBorn;
		}
	}
}

Despite the fact that the windowing structure was designed to be a binary tree, it hadn’t been implemented that way. Since the root window (the one representing the entire display) never has siblings and never has a title and since you can’t move hide or delete it, … (cut short for tl;dr)… that led somebody to decide that declaring an entire window structure was wasteful, and the wndRoot structure was replaced with pwndRootChildren, a simple pointer to the top level windows.

Replacing wndRoot with a pointer may have saved a few bytes of data space, but the cost in code space was enormous.

Forgive me for copying all that out verbatim, but I think that the complete background is needed to make the point clear. Here’s the code that was supposed to be written that’s found later in the article:

/* pwndDisplay points to the root-level window, which is
 * allocated during program initialization
 */
window *pwndDisplay = NULL;

void AddChild(window *pwndParent, window *pwndNewBorn)
{
	/* New windows may have children but not siblings... */
	ASSERT(pwndNewBorn->pwndSibling == NULL);

	/*  If Parent's first child, start a new sibling chain;
	 *  otherwise, add child to the end of the existing
	 *  sibling chain.
	 */
	if (pwndParent->pwndChild == NULL)
	{
		pwndParent->pwndChild = pwndNewBorn;
	}
	else
	{
		window *pwnd = pwndParent->pwndChild;

		while (pwnd->pwndSibling != NULL)
		{
			pwnd = pwnd->pwndSibling;
		}
		pwnd->pwndSibling = pwndNewBorn;
	}
}

Any experienced programmer in C would have noticed two things:

  • There was a forced special case
  • The cost of the optimization was greater than the yield of the optimization

But anyone can see that. Its obvious because he said it. However, mentioned this common mistake to a couple of colleagues and said that I did make the same kind of mistake, and this is what they said:

Sometimes code that was written back then may be correct back then, but may not be correct now. Just as I wrote an optimization once because computers were not fast enough to handle a certain operation at the time. They do now so that piece of code actually slowed the program down. Also, Opera recently made its engine less memory intensive but more CPU intensive, but after complaints that Opera was taking too much memory, they changed it to be less CPU intensive and more memory intensive. It’s also a balancing act with more input from your users.

The first thing that came to my mind was “Are you listening?” I am not sure if they were trying out of kindness to make me feel better that I make these bugs because of very good reasons and that the badness is unforseeable or that they were just in their own world going off in a skew. Besides the fact that its clearly the latter and that this is not a tradeoff problem nor was it a “we needed it at the time” problem, since it should have been obvious that the supposed optimization was going to cost more than it was worth in memory space alone at the time of writing the code.

I, like many fellow humans am prone to thinking about the more negative side of this. Of course, this was meant to be a negative post, but on the flipside, I learned three mistakes about fellow programmers that I must remember not to make myself.

  1. Winging it
  2. Optimizing with a narrow view
  3. The code I write is always flawless. I’ll fix it later if I have to.

Firstly, winging it and not paying attention to the details of the problem is a fatal mistake I have been guilty of countless times, and have seen many people fall in to as well. our minds are complex-averse, and tend to try and group things into simple groups of things that share the same characteristics based off keywords in a conversation without really understanding it. In this case, my mention of optimization kicked off the ideas of past optimization and tradeoffs in my colleagues’ heads, and was unfortunately all that occupied their heads from that moment on.

Secondly, we programmers are often indulged in our own mindset and steamroll our way through because our egos are big and our power limitless. When we see something that could be good, like an optimization, we tend to bulldoze our way to make sure it gets done.

Thirdly, we programmers are idealists. Not just in the sense that we want everything to be perfect, but we see perfection in everything we write too. This blindness can cause a lot of grief, and the defence is usually “I had no choice at the time”, which is usually an excuse to cover up a more embarrassing mistake.

Finally, coming back to topic after a very very long strayoff, the whole idea of humans and sad facts of software is not the point. The point of the article from the book is to tell you someone’s mistake so you don’t make it, because if this one word of caution saved a bug in a simple subsystem, imagine the number of bugs that would be saved in a complex system of 100 subsystems. These are the kinds of articles books should be packed full of.

last comments  
Ryan A
Ryan A

I so don't like winging it D:
November 4, 2009

GWT: Next level of automation

After playing a little with GWT, and attempting to add a map into my little webapp, I’ve found that this is really a very good idea. By applying a language to abstract all the small difficulties of programming a webpage for different browsers, you essentially move a larger percentage of the work into actually making the application.

Although GWT isn’t perfect, and to get my app up and running I had to spend about an hour or so searching the internet about fixing up some XMLs to import the libraries properly, once that was done, the source code that involved adding a map to the page and a little Javascript button coule fit on the screen, it is a huge step over having to deal with the difficulties faced by web programmers to make their sites both compatible with IE and Firefox.

Though I advocate using the minimum amount of cool new features on your site, GWT would be the next step toward progress with the current mess that is web application programming right now.

page 1 of 3 »